E-mail address list parser
421208
private static function parse_address_list($str, $decode = true, $fallback = null)
    {
        // remove any newlines and carriage returns before
        $str = preg_replace('/\r?\n(\s|\t)?/', ' ', $str);

        // extract list items, remove comments
        $str = self::explode_header_string(',;', $str, true);
        $result = array();

        // simplified regexp, supporting quoted local part
        $email_rx = '(\S+|("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+"))@\S+';

        foreach ($str as $key => $val) {
            $name    = '';
            $address = '';
            $val     = trim($val);

            if (preg_match('/(.*)<('.$email_rx.')>$/', $val, $m)) {
                $address = $m[2];
                $name    = trim($m[1]);
            }
            else if (preg_match('/^('.$email_rx.')$/', $val, $m)) {
                $address = $m[1];
                $name    = '';
            }
            // special case (#1489092)
            else if (preg_match('/(\s*<MAILER-DAEMON>)$/', $val, $m)) {
                $address = 'MAILER-DAEMON';
                $name    = substr($val, 0, -strlen($m[1]));
            }
            else if (preg_match('/('.$email_rx.')/', $val, $m)) {
                $name = $m[1];
            }
            else {
                $name = $val;
            }

            // dequote and/or decode name
            if ($name) {
                if ($name[0] == '"' && $name[strlen($name)-1] == '"') {
                    $name = substr($name, 1, -1);
                    $name = stripslashes($name);
                }
                if ($decode) {
                    $name = self::decode_header($name, $fallback);
                    // some clients encode addressee name with quotes around it
                    if ($name[0] == '"' && $name[strlen($name)-1] == '"') {
                        $name = substr($name, 1, -1);
                    }
                }
            }

            if (!$address && $name) {
                $address = $name;
                $name    = '';
            }

            if ($address) {
                $address      = self::fix_email($address);
                $result[$key] = array('name' => $name, 'address' => $address);
            }
        }

        return $result;
    }
316157
def lists_for_email(self, email_address):
        """"""
        params = {"email": email_address}
        response = self._get(self.uri_for("listsforemail"), params=params)
        return json_to_py(response)
627988
def _parse_address(self, val):
        

        ret = {
            'type': None,
            'value': None
        }

        try:

            ret['type'] = val[1]['type']

        except (KeyError, ValueError, TypeError):

                pass

        try:

            ret['value'] = val[1]['label']

        except (KeyError, ValueError, TypeError):

            ret['value'] = '\n'.join(val[3]).strip()

        try:

            self.vars['address'].append(ret)

        except AttributeError:

            self.vars['address'] = []
            self.vars['address'].append(ret)
107438
def parse_email_headers(s)
		keys={}
		match = (s =~ /\A((\w[\w\s\_\-]+: .*\n)+)\s*\n/)
		if match != 0
			keys[:data] = s
		else
			keys[:data] = $'
			headers = $1
			headers.split("\n").each do |l| 
# Fails if there are other ':' characters.
#				k, v = l.split(':')
				k, v = l.split(':', 2)
				k, v = normalize_key_and_value(k, v)
				k = k.to_sym
#				puts "K = #{k}, V=#{v}"
				keys[k] = v
			end
		end
		keys
	end
529801
def list_addresses(self, tag_values=None):
        
        '''
            
        '''
        
        title = '%s.list_addresses' % self.__class__.__name__

    # validate inputs
        input_fields = {
            'tag_values': tag_values
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)
            
    # add tags to method arguments
        kw_args = {}
        tag_text = ''
        if tag_values:
            kw_args = {
                'Filters': [ { 'Name': 'tag-value', 'Values': tag_values } ]
            }
            from labpack.parsing.grammar import join_words
            plural_value = ''
            if len(tag_values) > 1:
                plural_value = 's'
            tag_text = ' with tag value%s %s' % (plural_value, join_words(tag_values))
    
    # report query
        self.iam.printer('Querying AWS region %s for elastic ip addresses%s.' % (self.iam.region_name, tag_text))
        address_list = []
        
    # discover details associated with instance id
        try:
            response = self.connection.describe_addresses(**kw_args)
        except:
            raise AWSConnectionError(title)

    # populate address list with response
        response_list = response['Addresses']
        for address in response_list:
            address_list.append(address['PublicIp'])

        return address_list
565770
def extract_emails(text):
    """"""
    text = text.replace(u'\u2024', '.')
    emails = []
    for m in EMAIL_RE.findall(text):
        emails.append(m[0])
    return emails
787475
def getaddress(self):
        """"""
        self.commentlist = []
        self.gotonext()

        oldpos = self.pos
        oldcl = self.commentlist
        plist = self.getphraselist()

        self.gotonext()
        returnlist = []

        if self.pos >= len(self.field):
            # Bad email address technically, no domain.
            if plist:
                returnlist = [(SPACE.join(self.commentlist), plist[0])]

        elif self.field[self.pos] in '.@':
            # email address is just an addrspec
            # this isn't very efficient since we start over
            self.pos = oldpos
            self.commentlist = oldcl
            addrspec = self.getaddrspec()
            returnlist = [(SPACE.join(self.commentlist), addrspec)]

        elif self.field[self.pos] == ':':
            # address is a group
            returnlist = []

            fieldlen = len(self.field)
            self.pos += 1
            while self.pos < len(self.field):
                self.gotonext()
                if self.pos < fieldlen and self.field[self.pos] == ';':
                    self.pos += 1
                    break
                returnlist = returnlist + self.getaddress()

        elif self.field[self.pos] == '<':
            # Address is a phrase then a route addr
            routeaddr = self.getrouteaddr()

            if self.commentlist:
                returnlist = [(SPACE.join(plist) + ' (' +
                               ' '.join(self.commentlist) + ')', routeaddr)]
            else:
                returnlist = [(SPACE.join(plist), routeaddr)]

        else:
            if plist:
                returnlist = [(SPACE.join(self.commentlist), plist[0])]
            elif self.field[self.pos] in self.specials:
                self.pos += 1

        self.gotonext()
        if self.pos < len(self.field) and self.field[self.pos] == ',':
            self.pos += 1
        return returnlist
612716
function LIST(element_parser, delimiter_parser, save_delimiter) {
        if (typeof save_delimiter === "undefined") { save_delimiter = false; }
        var _func = 'LIST';
        var _parser = CONCAT(element_parser, REPEAT(CONCAT(delimiter_parser, element_parser), 0));

        return function (buffer, index, depth) {
            if (typeof depth === "undefined") { depth = 0; }
            _trace(_func, depth, true);

            var r;
            var _r = _parser(buffer, index, depth);

            if (paka.S.OK == _r.status) {
                var _children = [];

                _children.push(_r.children[0]);

                for (var i = 0; i < _r.children[1].children.length; ++i) {
                    if (save_delimiter) {
                        _children.push(_r.children[1].children[i].children[0]);
                    }
                    _children.push(_r.children[1].children[i].children[1]);
                }

                r = R.ok(paka.P.LIST, index, _r.length, _children);
            } else {
                r = R.error(paka.P.LIST, index, null, 'Failed to match LIST');
            }

            paka.S.ERROR == r.status && _update_last_error(r);
            _trace(_func, depth, false, r.status);
            return r;
        };
    }
166142
def clean_addresses(addresses):
    
    if addresses is None:
        return []
    addresses = addresses.replace("\'", "")
    address_list = re.split('[,;]', addresses)
    clean_list = []
    for address in address_list:
        temp_clean_address = clean_address(address)
        clean_list.append(temp_clean_address)
    return clean_list
350687
private Address[] getAddresses(List<String> strAddresses, String delimiter) throws OrganizationException {
		Address[] addressArray = new Address[strAddresses.size()];
		int count = 0;
		for (String addr : strAddresses)
		{
            try{
            	addressArray[count] = new InternetAddress(addr);
            	count++;
            }catch(Exception e){
            	throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage());
            }
        }
        return addressArray;
	}
642261
def lisp(self, foldername="INBOX", reverse=False, since=None, stream=sys.stdout):
        
        def fromval(hdr):
            if hdr:
                return parseaddr(hdr)

        for folder, mk, m in self._list(foldername, reverse, since):
            try:
                print(json.dumps({
                        'folder': folder.folder or foldername or "INBOX",
                        'key': "%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
                        'date':  str(m.date),
                        "flags": m.get_flags(),
                        'from': fromval(m.get_from()),
                        'subject': re.sub("\n|\'|\"", _escape, m.get_subject() or "")
                        }), file=stream)
            except IOError as e:
                if e.errno == errno.EPIPE:
                    # Broken pipe we can ignore
                    return
                self.logger.exception("whoops!")
            except Exception as e:
                self.logger.exception("whoops!")
679488
def p_simple_list(p):
    ''''''
    tok = p.lexer
    heredoc.gatherheredocuments(tok)

    if len(p) == 3 or len(p[1]) > 1:
        parts = p[1]
        if len(p) == 3:
            parts.append(ast.node(kind='operator', op=p[2], pos=p.lexspan(2)))
        p[0] = ast.node(kind='list', parts=parts, pos=_partsspan(parts))
    else:
        assert len(p[1]) == 1
        p[0] = p[1][0]

    if (len(p) == 2 and p.lexer._parserstate & flags.parser.CMDSUBST and
            p.lexer._current_token.nopos() == p.lexer._shell_eof_token):
        # accept the input
        p.accept()
913518
def parse_top_level(self):
        
        contacts = []
        while not self.eos:
            contact = self.parse_contact()  # match a contact expression.
            if not contact:  # There was no contact so end file.
                break  # This would be a nice place to put other expressions.
            contacts.append(contact)
            # skip all whitespace between the end of the last contact and the
            # next non whitespace character, ie until something interesting.
            self.parse_whitespace()
        output = {}
        for key, value in contacts:
            output[key] = value
        return output
1015095
function buildEmail(envelope, data) {
  return simpleParser(data)
    .then(function(parsedEmail) {
      const sender    = envelope.mailFrom.address;
      const receivers = envelope.rcptTo
        .map(recipient => [ recipient.address, true ])
        .reduce(tupleToObject, {});

      const headers   = [ ... parsedEmail.headers ]
        .map(readHeader)
        .reduce(tupleToObject, {});

      const email     = {
        sender,
        receivers,
        data,
        headers,
        body:      parsedEmail.text,
        html:      parsedEmail.html,
        attachments:      parsedEmail.attachments
      };

      return email;
    });
}
205289
def email_addresses2marc(self, key, value):
    
    m_or_o = 'm' if value.get('current') else 'o'
    element = {
        m_or_o: value.get('value')
    }

    if value.get('hidden'):
        return element
    else:
        self.setdefault('371', []).append(element)
        return None
1216923
def __parse(self, aliases, email_to_employer, domain_to_employer):
        """"""

        self.__parse_organizations(domain_to_employer)
        self.__parse_identities(aliases, email_to_employer)
901236
function addressList() {
        return wrap('address-list', or(
            and(
                address,
                star(and(literal(','), address))
            ),
            obsAddrList
        )());
    }