Return a prefix based on options passed from command line

        Used by add_prefix() and add_prefix_from_pool() to avoid duplicate
        parsing
350801
def _prefix_from_opts(opts):
    
    p = Prefix()
    p.prefix = opts.get('prefix')
    p.type = opts.get('type')
    p.description = opts.get('description')
    p.node = opts.get('node')
    p.country = opts.get('country')
    p.order_id = opts.get('order_id')
    p.customer_id = opts.get('customer_id')
    p.alarm_priority = opts.get('alarm_priority')
    p.comment = opts.get('comment')
    p.monitor = _str_to_bool(opts.get('monitor'))
    p.vlan = opts.get('vlan')
    p.status = opts.get('status') or 'assigned' # default to assigned
    p.tags = list(csv.reader([opts.get('tags', '')], escapechar='\\'))[0]
    p.expires = opts.get('expires')
    return p
319209
def _parent_prefix(prefix):
    
    def run(algs):
        for alg in algs:
            vcs = alg.get("variantcaller")
            if vcs:
                if isinstance(vcs, dict):
                    vcs = reduce(operator.add, vcs.values())
                if not isinstance(vcs, (list, tuple)):
                    vcs = [vcs]
                return any(vc.startswith(prefix) for vc in vcs if vc)
    return run
403147
def get_pool(arg = None, opts = None, abort = False):
    
    # yep, global variables are evil
    global pool

    try:
        pool = Pool.list({ 'name': arg })[0]
    except IndexError:
        if abort:
            print("Pool '%s' not found." % str(arg), file=sys.stderr)
            sys.exit(1)
        else:
            pool = None

    return pool
851068
def grow_pool(arg, opts, shell_opts):
    
    if not pool:
        print("No pool with name '%s' found." % arg, file=sys.stderr)
        sys.exit(1)

    if not 'add' in opts:
        print("Please supply a prefix to add to pool '%s'" % pool.name, file=sys.stderr)
        sys.exit(1)

    # Figure out VRF.
    # If pool already has a member prefix, implied_vrf will be set. Look for new
    # prefix to add in the same vrf as implied_vrf.
    # If pool has no members, then use get_vrf() to get vrf to search in for
    # prefix to add.
    if pool.vrf is not None:
        v = pool.vrf
    else:
        v = get_vrf(opts.get('vrf_rt'), abort=True)

    q = { 'prefix': opts['add'] }
    if v.rt != 'all':
        q['vrf_rt'] = v.rt

    res = Prefix.list(q)

    if len(res) == 0:
        print("No prefix found matching %s in %s." % (opts['add'], vrf_format(v)), file=sys.stderr)
        sys.exit(1)
    elif res[0].pool:
        if res[0].pool == pool:
            print("Prefix %s in %s is already assigned to that pool." % (opts['add'], vrf_format(v)), file=sys.stderr)
        else:
            print("Prefix %s in %s is already assigned to a different pool ('%s')." % (opts['add'], vrf_format(v), res[0].pool.name), file=sys.stderr)
        sys.exit(1)

    res[0].pool = pool
    res[0].save()
    print("Prefix %s in %s added to pool '%s'." % (res[0].prefix, vrf_format(v), pool.name))
758246
def _input_parser_generator(self):
        
        prefix = ''
        retry = False
        flush = False

        while True:
            flush = False

            if retry:
                retry = False
            else:
                # Get next character.
                c = yield

                if c == _Flush:
                    flush = True
                else:
                    prefix += c

            # If we have some data, check for matches.
            if prefix:
                is_prefix_of_longer_match = _IS_PREFIX_OF_LONGER_MATCH_CACHE[prefix]
                match = self._get_match(prefix)

                # Exact matches found, call handlers..
                if (flush or not is_prefix_of_longer_match) and match:
                    self._call_handler(match, prefix)
                    prefix = ''

                # No exact match found.
                elif (flush or not is_prefix_of_longer_match) and not match:
                    found = False
                    retry = True

                    # Loop over the input, try the longest match first and
                    # shift.
                    for i in range(len(prefix), 0, -1):
                        match= self._get_match(prefix[:i])
                        if match:
                            self._call_handler(match, prefix[:i])
                            prefix = prefix[i:]
                            found = True

                    if not found:
                        self._call_handler(prefix[0], prefix[0])
                        prefix = prefix[1:]
97395
def resolve_ctx(cli, prog_name, args):
    
    ctx = cli.make_context(prog_name, args, resilient_parsing=True)
    args = ctx.protected_args + ctx.args
    while args:
        if isinstance(ctx.command, MultiCommand):
            if not ctx.command.chain:
                cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
                if cmd is None:
                    return ctx
                ctx = cmd.make_context(cmd_name, args, parent=ctx,
                                       resilient_parsing=True)
                args = ctx.protected_args + ctx.args
            else:
                # Walk chained subcommand contexts saving the last one.
                while args:
                    cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
                    if cmd is None:
                        return ctx
                    sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,
                                               allow_extra_args=True,
                                               allow_interspersed_args=False,
                                               resilient_parsing=True)
                    args = sub_ctx.args
                ctx = sub_ctx
                args = sub_ctx.protected_args + sub_ctx.args
        else:
            break
    return ctx
814472
def parse_prefix(identifier):
    
    pf, id = (), identifier
    if "|" in identifier:
        pf, id = tuple(identifier.split('|')[:-1]), identifier.split('|')[-1]

    return pf, id
183824
def make_prefix(api_version, manipulator, auth_type):
    """"""
    prefix = "%s_%s" % (api_version, manipulator)
    if (auth_type and auth_type != 'none'):
        prefix += '_' + auth_type
    return prefix
997131
def conda_prefix():
    """"""
    try:
        out = subprocess.check_output(['conda', 'info', '--json'])
        return json.loads(out.decode())["default_prefix"]
    except (subprocess.CalledProcessError, json.JSONDecodeError, OSError):
        return False
472952
def pop_prefix(string: str):
        
        result = string.split(Naming.TYPE_PREFIX)
        if len(result) == 1:
            result = string.split(Naming.RESOURCE_PREFIX)
            if len(result) == 1:
                raise IndexError()
        return result
1310338
def pop_kwargs_with_prefix(prefix: str, kwargs: dict) -> dict:
    
    keys = [key for key in kwargs if key.startswith(prefix)]
    return {key[len(prefix):]: kwargs.pop(key) for key in keys}
573120
def get_prefix():
  

  name = os.environ.get('NCLUSTER_PREFIX', DEFAULT_PREFIX)
  if name != DEFAULT_PREFIX:
    validate_prefix(name)
  return name
294656
def get_stripped_prefix(source, prefix):
    
    cut = len(prefix)
    return {
        k[cut:]: v for k, v in source.items()
        if k.startswith(prefix)
    }
991628
def sys_prefix(self):
        

        command = [self.python, "-c" "import sys; print(sys.prefix)"]
        c = vistir.misc.run(command, return_object=True, block=True, nospin=True, write_to_stdout=False)
        sys_prefix = vistir.compat.Path(vistir.misc.to_text(c.out).strip()).as_posix()
        return sys_prefix
303973
def lchop(string, prefix):
    
    if string.startswith(prefix):
        return string[len(prefix):]
    return string
815914
def get_prefixes(self, ns_uri):
        """"""
        ni = self.__lookup_uri(ns_uri)
        return ni.prefixes.copy()
1034668
def _compile_prefixes(self):
        '''
        
        '''
        self.compiled_prefixes = {}
        for dev_os, os_config in self.config.items():
            if not os_config:
                continue
            self.compiled_prefixes[dev_os] = []
            for prefix in os_config.get('prefixes', []):
                values = prefix.get('values', {})
                line = prefix.get('line', '')
                if prefix.get('__python_fun__'):
                    self.compiled_prefixes[dev_os].append({
                        '__python_fun__': prefix['__python_fun__'],
                        '__python_mod__': prefix['__python_mod__']
                    })
                    continue  # if python profiler defined for this prefix,
                    # no need to go further, but jump to the next prefix
                # Add 'pri' and 'message' to the line, and values
                line = '{{pri}}{}{{message}}'.format(line)
                # PRI https://tools.ietf.org/html/rfc5424#section-6.2.1
                values['pri'] = r'\<(\d+)\>'
                values['message'] = '(.*)'
                # We will now figure out which position each value is in so we can use it with the match statement
                position = {}
                for key in values.keys():
                    position[line.find('{' + key + '}')] = key
                sorted_position = {}
                for i, elem in enumerate(sorted(position.items())):
                    sorted_position[elem[1]] = i + 1
                # Escape the line, then remove the escape for the curly bracets so they can be used when formatting
                escaped = re.escape(line).replace(r'\{', '{').replace(r'\}', '}')
                # Replace a whitespace with \s+
                escaped = escaped.replace(r'\ ', r'\s+')
                self.compiled_prefixes[dev_os].append({
                    'prefix': re.compile(escaped.format(**values)),
                    'prefix_positions': sorted_position,
                    'raw_prefix': escaped.format(**values),
                    'values': values
                })