Filter BEL relations by prefix

    Args:
        prefix: completion string
        bel_fmt: short, medium, long BEL formats
        spec: BEL specification

    Returns:
        list: list of BEL relations that match prefix
354812
def relation_completions(
    completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int
) -> list:
    

    if bel_fmt == "short":
        relation_list = bel_spec["relations"]["list_short"]
    else:
        relation_list = bel_spec["relations"]["list_long"]

    matches = []
    for r in relation_list:
        if re.match(completion_text, r):
            matches.append(r)

    replace_list = []
    for match in matches:
        highlight = match.replace(completion_text, f"<em>{completion_text}</em>")
        replace_list.append(
            {
                "replacement": match,
                "label": match,
                "highlight": highlight,
                "type": "Relation",
            }
        )

    return replace_list[:size]
438728
def startswith(self, prefix, start=None, end=None):
        
        prefix = Bits(prefix)
        start, end = self._validate_slice(start, end)
        if end < start + prefix.len:
            return False
        end = start + prefix.len
        return self._slice(start, end) == prefix
679742
def _parse_prefix_query(self, query_str):
        
        sp = smart_parsing.PrefixSmartParser()
        query = sp.parse(query_str)
        return query
700416
def prefix(self, format="sparql"):
        ''' 
        '''

        lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
        lg.setLevel(self.log_level)

        _return_str = ""
        if format.lower() == "sparql":
            return "\n".join([ns._sparql_ for ns in self.namespaces])
        elif format.lower() in ["turtle", "ttl"]:
            return "\n".join([ns._ttl_ for ns in self.namespaces])
        elif format.lower() in ["rdf", "xml", "rdf/xml"]:
            return "<rdf:RDF %s>" % \
                    " ".join([ns._xml_ for ns in self.namespaces])
        else:
            raise NotImplementedError("'%s' is not a valid prefix type." %
                                      format)
1323388
def filter_short(terms):
    '''
    
    '''
    return [term for i, term in enumerate(terms) if 26**(len(term)) > i]
332355
def remove_prefix(text, prefix):
	
	null, prefix, rest = text.rpartition(prefix)
	return rest
1276024
def __extend_uri(prefixes, short):
    
    for prefix in prefixes:
        if short.startswith(prefix):
            return short.replace(prefix + ':', prefixes[prefix])
    return short
824203
def by_prefix(self,
                  prefix,
                  zipcode_type=ZipcodeType.Standard,
                  sort_by=SimpleZipcode.zipcode.name,
                  ascending=True,
                  returns=DEFAULT_LIMIT):
        
        return self.query(
            prefix=prefix,
            sort_by=sort_by, zipcode_type=zipcode_type,
            ascending=ascending, returns=returns,
        )
454157
def list_prefix(arg, opts, shell_opts):
    

    search_string = ''
    if type(arg) == list or type(arg) == tuple:
        search_string = ' '.join(arg)

    v = get_vrf(opts.get('vrf_rt'), default_var='default_list_vrf_rt', abort=True)

    if v.rt == 'all':
        vrf_text = 'any VRF'
        vrf_q = None
    else:
        vrf_text = vrf_format(v)
        vrf_q = {
            'operator': 'equals',
            'val1': 'vrf_rt',
            'val2': v.rt
        }
    print("Searching for prefixes in %s..." % vrf_text)

    col_def = {
            'added': { 'title': 'Added' },
            'alarm_priority': { 'title': 'Alarm Prio' },
            'authoritative_source': { 'title': 'Auth source' },
            'children': { 'title': 'Children' },
            'comment': { 'title': 'Comment' },
            'customer_id': { 'title': 'Customer ID' },
            'description': { 'title': 'Description' },
            'expires': { 'title': 'Expires' },
            'free_addresses': { 'title': 'Free addresses' },
            'monitor': { 'title': 'Monitor' },
            'last_modified': { 'title': 'Last mod' },
            'node': { 'title': 'Node' },
            'order_id': { 'title': 'Order ID' },
            'pool_name': { 'title': 'Pool name' },
            'prefix': { 'title': 'Prefix' },
            'status': { 'title': 'Status' },
            'tags': { 'title': '#' },
            'total_addresses': { 'title': 'Total addresses' },
            'type': { 'title': '' },
            'used_addresses': { 'title': 'Used addresses' },
            'vlan': { 'title': 'VLAN' },
            'vrf_rt': { 'title': 'VRF RT' },
            }
    # default columns
    columns = [ 'vrf_rt', 'prefix', 'type', 'tags', 'node', 'order_id', 'customer_id', 'description' ]

    # custom columns? prefer shell opts, then look in config file
    custom_columns = None
    if shell_opts.columns and len(shell_opts.columns) > 0:
        custom_columns = shell_opts.columns
    elif cfg.get('global', 'prefix_list_columns'):
        custom_columns = cfg.get('global', 'prefix_list_columns')

    # parse custom columns
    if custom_columns:
        # Clear out default columns, unless user whishes to append
        if custom_columns[0] != '+':
            columns = []

        # read in custom columns
        for col in list(csv.reader([custom_columns.lstrip('+') or ''], escapechar='\\'))[0]:
            col = col.strip()
            if col not in col_def:
                print("Invalid column:", col, file=sys.stderr)
                sys.exit(1)
            columns.append(col)

    offset = 0
    # small initial limit for "instant" result
    limit = 50
    prefix_str = ""
    while True:
        res = Prefix.smart_search(search_string, { 'parents_depth': -1,
            'include_neighbors': True, 'offset': offset, 'max_result': limit },
            vrf_q)

        if offset == 0: # first time in loop?
            if shell_opts.show_interpretation:
                print("Query interpretation:")
                _parse_interp_prefix(res['interpretation'])

            if res['error']:
                print("Query failed: %s" % res['error_message'])
                return

            if len(res['result']) == 0:
                print("No addresses matching '%s' found." % search_string)
                return

            # guess column width by looking at the initial result set
            for p in res['result']:
                for colname, col in col_def.items():
                    val = getattr(p, colname, '')
                    col['width'] = max(len(colname), col.get('width', 0),
                                       len(str(val)))

                # special handling of a few columns
                col_def['vrf_rt']['width'] = max(col_def['vrf_rt'].get('width', 8),
                                                 len(str(p.vrf.rt)))
                col_def['prefix']['width'] = max(col_def['prefix'].get('width', 0)-12,
                                                 p.indent * 2 + len(p.prefix)) + 12
                try:
                    col_def['pool_name']['width'] = max(col_def['pool_name'].get('width', 8),
                                                        len(str(p.pool.name)))
                except:
                    pass
            # override certain column widths
            col_def['type']['width'] = 1
            col_def['tags']['width'] = 2

            col_header_data = {}
            # build prefix formatting string
            for colname, col in [(k, col_def[k]) for k in columns]:
                prefix_str += "{%s:<%d}  " % (colname, col['width'])
                col_header_data[colname] = col['title']

            column_header = prefix_str.format(**col_header_data)
            print(column_header)
            print("".join("=" for i in range(len(column_header))))

        for p in res['result']:
            if p.display == False:
                continue

            col_data = {}
            try:
                for colname, col in col_def.items():
                    col_data[colname] = str(getattr(p, colname, None))

                # overwrite some columns due to special handling
                col_data['tags'] = '-'
                if len(p.tags) > 0:
                    col_data['tags'] = '#%d' % len(p.tags)

                try: 
                    col_data['pool_name'] = p.pool.name
                except:
                    pass

                col_data['prefix'] = "".join("  " for i in range(p.indent)) + p.display_prefix
                col_data['type'] = p.type[0].upper()
                col_data['vrf_rt'] = p.vrf.rt or '-'

                print(prefix_str.format(**col_data))

            except UnicodeEncodeError as e:
                print("\nCrazy encoding for prefix %s\n" % p.prefix, file=sys.stderr)

        if len(res['result']) < limit:
            break
        offset += limit

        # let consecutive limit be higher to tax the XML-RPC backend less
        limit = 200
1081297
def _find_common_prefix(self, node1, node2):
        """"""
        tokens1 = [item.strip() for item in node1.split(self.node_separator)]
        tokens2 = [item.strip() for item in node2.split(self.node_separator)]
        ret = []
        for token1, token2 in zip(tokens1, tokens2):
            if token1 == token2:
                ret.append(token1)
            else:
                break
        return self.node_separator.join(ret)
612204
def _parse_PREFIX(value):
        ""
        channel_modes, channel_chars = value.split(')')
        channel_modes = channel_modes[1:]
        return collections.OrderedDict(zip(channel_chars, channel_modes))
910380
def warn_prefix_values(trie):
    '''
    
    '''
    for current, _parent in trie.dfs():
        if current.has_value and current.longest_prefix is not None:
            LOGGER.warn(('pattern {} (value {}) is a superstring of pattern '
                         '{} (value {}) and will never be matched').format(
                             current.prefix, current.value,
                             current.longest_prefix.prefix, current.longest_prefix.value))
166898
def full_rule(self):
        
        return join(self.bp_prefix, self.rule, trailing_slash=self.rule.endswith('/'))
221734
public FunctionList prefix(final String prefix) {
        return filter(new Filter() {
            public boolean keep(Function m) {
                return m.getName().startsWith(prefix);
            }
        });
    }
251869
def get_completions(
    belstr: str,
    cursor_loc: int,
    bel_spec: BELSpec,
    bel_comp: str,
    bel_fmt: str,
    species_id: str,
    size: int,
):
    

    ast, errors = pparse.get_ast_dict(belstr)

    spans = pparse.collect_spans(ast)

    completion_text = ""
    completions = []
    function_help = []

    log.debug(f"Cursor location BELstr: {belstr}  Cursor idx: {cursor_loc}")
    cursor_results = cursor(belstr, ast, cursor_loc)
    log.debug(f"Cursor results: {cursor_results}")

    if not cursor_results:
        log.debug("Cursor results is empty")
        return (completion_text, completions, function_help, spans)

    completion_text = cursor_results.get("completion_text", "")

    replace_span = cursor_results["replace_span"]
    namespace = cursor_results.get("namespace", None)

    if "parent_function" in cursor_results:
        parent_function = cursor_results["parent_function"]
        function_help = bel_specification.get_function_help(
            cursor_results["parent_function"], bel_spec
        )

        args = cursor_results.get("args", [])
        arg_idx = cursor_results.get("arg_idx")

        replace_list = arg_completions(
            completion_text,
            parent_function,
            args,
            arg_idx,
            bel_spec,
            bel_fmt,
            species_id,
            namespace,
            size,
        )
    elif cursor_results["type"] == "Function":
        function_list = None
        replace_list = function_completions(
            completion_text, bel_spec, function_list, bel_fmt, size
        )
    elif cursor_results["type"] == "Relation":
        replace_list = relation_completions(completion_text, bel_spec, bel_fmt, size)

    completions.extend(
        add_completions(replace_list, belstr, replace_span, completion_text)
    )

    return completion_text, completions, function_help, spans
847199
def getPrefixFor(self, portal_type):
        
        prefix = [p for p in self.getIDFormatting() if p['portal_type'] == portal_type]
        if prefix:
            return prefix[0]['prefix']
        else:
            return portal_type
345426
def _strip_prefix(self, message):
        

        if not hasattr(self, "name_regex"):
            """
            regex example:
            ^(((BotA|BotB)[,:]?\s+)|%)(.+)$
            
            names = [BotA, BotB]
            prefix = %
            """

            names = self.config['names']
            prefix = self.config['prefix']

            name_regex_str = r'^(?:(?:(%s)[,:]?\s+)|%s)(.+)$' % (re.escape("|".join(names)), prefix)
            self.name_regex = re.compile(name_regex_str, re.IGNORECASE)

        search = self.name_regex.search(message)
        if search:
            return search.groups()[1]

        return None