Return a MATCH query string from a list of IR blocks.
516567
def emit_code_from_single_match_query(match_query):
    """"""
    query_data = deque([u'MATCH '])

    if not match_query.match_traversals:
        raise AssertionError(u'Unexpected falsy value for match_query.match_traversals received: '
                             u'{} {}'.format(match_query.match_traversals, match_query))

    # Represent and add the MATCH traversal steps.
    match_traversal_data = [
        _represent_match_traversal(x)
        for x in match_query.match_traversals
    ]
    query_data.append(match_traversal_data[0])
    for traversal_data in match_traversal_data[1:]:
        query_data.append(u', ')
        query_data.append(traversal_data)

    query_data.appendleft(u' (')            # Prepare to wrap the MATCH in a SELECT.
    query_data.append(u'RETURN $matches)')  # Finish the MATCH query and the wrapping ().

    # Represent and add the LET clauses for any @fold scopes that might be part of the query.
    # Sort for deterministic order of clauses.
    fold_data = sorted([
        _represent_fold(fold_location, fold_ir_blocks)
        for fold_location, fold_ir_blocks in six.iteritems(match_query.folds)
    ])
    if fold_data:
        query_data.append(u' LET ')
        query_data.append(fold_data[0])
        for fold_clause in fold_data[1:]:
            query_data.append(u', ')
            query_data.append(fold_clause)

    # Represent and add the SELECT clauses with the proper output data.
    query_data.appendleft(_construct_output_to_match(match_query.output_block))

    # Represent and add the WHERE clause with the proper filters.
    if match_query.where_block is not None:
        query_data.append(_construct_where_to_match(match_query.where_block))

    return u' '.join(query_data)
99809
def in_query(expression):
    """"""
    def _in(index, expression=expression):
        """Return store key for documents that satisfy expression."""
        ev = expression() if callable(expression) else expression
        try:
            iter(ev)
        except TypeError:
            raise AttributeError('$in argument must be an iterable!')
        hashed_ev = [index.get_hash_for(v) for v in ev]
        store_keys = set()

        for value in hashed_ev:
            store_keys |= set(index.get_keys_for(value))

        return list(store_keys)

    return _in
95408
def get_ops_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None):
        
        if (start_block_height is None and end_block_height is not None) or (start_block_height is not None and end_block_height is None):
            raise ValueError("Need either both or neither start/end block height")

        con = cls.db_open(impl, working_dir)
        range_query = ' WHERE ops_hash IS NOT NULL'
        range_args = ()

        if start_block_height and end_block_height:
            range_query += ' AND block_id >= ? AND block_id < ?'
            range_args += (start_block_height,end_block_height)

        query = 'SELECT block_id,ops_hash FROM snapshots' + range_query + ';'
        args = range_args

        rows = cls.db_query_execute(con, query, range_args, verbose=False)
        ret = {}
        block_min = None
        block_max = None

        for r in rows:
            ret[r['block_id']] = r['ops_hash']

            if block_min is None or block_min > r['block_id']:
                block_min = r['block_id']

            if block_max is None or block_max < r['block_id']:
                block_max = r['block_id']

        con.close()
        
        # sanity check
        if block_min is not None and block_max is not None:
            for i in range(block_min,block_max+1):
                oh = ret.get(i, None)

                assert oh is not None, 'Missing ops hash for {}'.format(i)
                assert isinstance(ret[i], (str,unicode)), 'ops hash for {} is type {}'.format(i, type(ret[i]))

        return ret
1055314
def canned_query(n,s):
    
    qobj = qmap[n]
    chain = qobj['chain']
    prefix = qobj['prefix']
    whr = chain2where(chain + [prefix], 'x')
    query = """
    SELECT * WHERE {{
    <{s}> {w}
    }}
    """.format(s=s, w=whr)
    bindings = run_sparql(query)
    rows = [ensure_prefixed(r['x']['value'], prefix) for r in bindings]
    return rows
97998
def _pull_query_results(resultset):
    '''
    
    '''
    _results = collections.defaultdict(lambda: {})
    for _header, _values in resultset.items():
        _header, _group_tags = _header
        if _group_tags:
            _results[_header][salt.utils.json.dumps(_group_tags)] = [_value for _value in _values]
        else:
            _results[_header] = [_value for _value in _values]
    return dict(sorted(_results.items()))
256276
def is_uri_to_be_filtered(uri, filter_list):
    """"""
    match = False
    if filter_list:
        for uri_filter in filter_list:
            if re.search(uri_filter, uri, flags=re.IGNORECASE):
                match = True
        return match
805398
def query(self, base, filterstr, attrlist=None):
		
		return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)
1296650
def match_pagination(ref_line):
    """"""
    pattern = ur'\(?\[?(\d{1,4})\]?\)?\.?\s*$'
    re_footer = re.compile(pattern, re.UNICODE)
    match = re_footer.match(ref_line)
    if match:
        return int(match.group(1))
    return None
624534
def _querystring(self):
        """"""

        kw = {}
        for key in self.KNOWN_QUERY_OPTIONS:
            val = getattr(self, key)
            if val is not None:
                kw[key] = val
        return kw
548415
def extract_table_names(query):
    
    # a good old fashioned regex. turns out this worked better than actually parsing the code
    tables_blocks = re.findall(r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)', query, re.IGNORECASE)
    tables = [tbl
              for block in tables_blocks
              for tbl in re.findall(r'\w+', block)]
    return set(tables)
829031
def match_uriinfo(cls, info):
        
        items = sorted(
            cls._entries.items(),
            key=lambda matcher_entries: matcher_entries[0].priority,
            reverse=True,
        )
        for matcher, value in items:
            if matcher.matches(info):
                return (matcher, info)

        return (None, [])
985511
def find_re(self, pattern):
        """"""
        # TODO: Reduce redundancy with RAFArchive
        pattern = re.compile(pattern, re.I)
        for k, v in six.iteritems(self.entries_full):
            if pattern.search(k):
                # Most recent version will be last
                yield v[-1]
1173593
def query(options, collection_name, num_to_skip, num_to_return,
          query, field_selector, opts, check_keys=False, ctx=None):
    """"""
    if ctx:
        return _query_compressed(options, collection_name, num_to_skip,
                                 num_to_return, query, field_selector,
                                 opts, check_keys, ctx)
    return _query_uncompressed(options, collection_name, num_to_skip,
                               num_to_return, query, field_selector, opts,
                               check_keys)
1275897
def get_block(self, namespace, offset, key):
        """"""
        cursor = self.cursor
        cursor.execute('SELECT data, flags FROM gauged_data '
                       'WHERE namespace = %s AND "offset" = %s AND key = %s',
                       (namespace, offset, key))
        row = cursor.fetchone()
        return (None, None) if row is None else row
1071660
def iter_query(query):
    """"""
    try:
        itr = click.open_file(query).readlines()
    except IOError:
        itr = [query]
    return itr
1269300
def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100):
    """"""
    results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x)
               for x in range(offset, count+1, limit)]
    if xml_query:
        return [el for res in results for el in res]
    else:
        pattern = _re.compile(r'^<\?xml.*?\n<records>\n|\n</records>$.*')
        return ('<?xml version="1.0" ?>\n<records>' +
                '\n'.join(pattern.sub('', res) for res in results) +
                '</records>')
96503
def query(self,query_string,toprint=False):
		""""""
		qq=SearchTerm(query_string)
		matchcount=0
		matches=[]
		for word in self.words():
			for match in word.search(qq):
				matches.append(match)
				matchcount+=1
				if "Word" in str(type(match)):
					matchstr=""
				else:
					matchstr=str(match)
				if toprint:
					word.om(makeminlength(str(matchcount),int(being.linelen/6))+"\t"+makeminlength(str(word),int(being.linelen))+"\t"+matchstr)
		return matches