Parse 'sfx.py:percent' into {'suffix':'sfx', 'extension':'py', 'format_name':'percent'}
5755
def long_form_one_format(jupytext_format, metadata=None, update=None):
    """"""
    if isinstance(jupytext_format, dict):
        if update:
            jupytext_format.update(update)
        return validate_one_format(jupytext_format)

    if not jupytext_format:
        return {}

    common_name_to_ext = {'notebook': 'ipynb',
                          'rmarkdown': 'Rmd',
                          'markdown': 'md',
                          'c++': 'cpp'}
    if jupytext_format.lower() in common_name_to_ext:
        jupytext_format = common_name_to_ext[jupytext_format.lower()]

    fmt = {}

    if jupytext_format.rfind('/') > 0:
        fmt['prefix'], jupytext_format = jupytext_format.rsplit('/', 1)

    if jupytext_format.rfind(':') >= 0:
        ext, fmt['format_name'] = jupytext_format.rsplit(':', 1)
    else:
        ext = jupytext_format

    if ext.rfind('.') > 0:
        fmt['suffix'], ext = os.path.splitext(ext)

    if not ext.startswith('.'):
        ext = '.' + ext

    if ext == '.auto':
        ext = auto_ext_from_metadata(metadata) if metadata is not None else '.auto'
        if not ext:
            raise JupytextFormatError("No language information in this notebook. Please replace 'auto' with "
                                      "an actual script extension.")

    fmt['extension'] = ext
    if update:
        fmt.update(update)
    return validate_one_format(fmt)
1152456
def format(self):
        

        values = {}
        title = "Description"
        description = self.command.description + "\n\n" + self.get_ending_note() if not self.is_cog() else inspect.getdoc(self.command)
        sections = []

        if isinstance(self.command, Command):
                description = self.command.short_doc
                sections = [{"name": "Usage", "value": self.get_command_signature()},
                            {"name": "More Info", "value": self.command.help.replace(self.command.short_doc, "").format(prefix=self.clean_prefix),
                             "inline": False}]

        def category(tup):
            cog = tup[1].cog_name
            return cog + ':' if cog is not None else '\u200bNo Category:'

        if self.is_bot():
            title = self.bot.user.display_name + " Help"
            data = sorted(self.filter_command_list(), key=category)
            for category, commands in itertools.groupby(data, key=category):
                section = {}
                commands = list(commands)
                if len(commands) > 0:
                    section['name'] = category
                section['value'] = self.add_commands(commands)
                section['inline'] = False
                sections.append(section)
        elif not sections or self.has_subcommands():
            section = {"name": "Commands:", "inline": False, "value": self.add_commands(self.filter_command_list())}
            sections.append(section)

        values['title'] = title
        values['description'] = description
        values['sections'] = sections
        return values
745518
def format(self):
        '''
        '''
        c = n = ''
        if not self.both:
            c = ' (code only)'
        if self.leng:
            n = ' (%s)' % _nameof(self.leng)
        return _kwds(base=self.base, item=self.item, leng=n,
                     code=c,         kind=self.kind)
1225930
def _value_format(self, value):
        
        return '%s: %s' % (
            self.area_names.get(self.adapt_code(value[0]), '?'),
            self._y_format(value[1])
        )
6907
def to_s
      str = ''
      if @width > 0
        fmt = @width.truncate == @width ? '%d' : '%.2f'
        str << format(fmt, @width)
        str << '%' if @flag == PercentGeometry
      end

      str << 'x' if (@width > 0 && @flag != PercentGeometry) || (@height > 0)

      if @height > 0
        fmt = @height.truncate == @height ? '%d' : '%.2f'
        str << format(fmt, @height)
        str << '%' if @flag == PercentGeometry
      end
      str << format('%+d%+d', @x, @y) if @x != 0 || @y != 0
      str << FLAGS[@flag.to_i] if @flag != PercentGeometry
      str
    end
1197134
def validate_format_percentage(name, value)
      DataTypeValidator.validate name, Float, value, lambda { |arg| arg >= 0.0 && arg <= 1.0}
    end
235524
def format_from_extension(fname):
    
    _base, ext = os.path.splitext(fname)
    if not ext:
        return None
    try:
        format = known_extensions[ext.replace('.', '')]
    except KeyError:
        format = None
    return format
1295572
def script_to_hex(script):
    
    hex_script = ''
    parts = script.split(' ')
    for part in parts:
        if part[0:3] == 'OP_':
            try:
                hex_script += '%0.2x' % eval(part)
            except:
                raise Exception('Invalid opcode: %s' % part)
        elif isinstance(part, (int)):
            hex_script += '%0.2x' % part
        elif is_hex(part):
            hex_script += '%0.2x' % count_bytes(part) + part
        else:
            raise Exception('Invalid script - only opcodes and hex characters allowed.')
    return hex_script
1004315
def parse(self, fd):
        """"""

        def resolve_args(args):
            # FIXME break this out, it's in common with the templating stuff elsewhere
            root = self.sections[0]
            val_dict = dict(('<' + t + '>', u) for (t, u) in root.get_variables().items())
            resolved_args = []
            for arg in args:
                for subst, value in val_dict.items():
                    arg = arg.replace(subst, value)
                resolved_args.append(arg)
            return resolved_args

        def handle_section_defn(keyword, parts):
            if keyword == '@HostAttrs':
                if len(parts) != 1:
                    raise ParserException('usage: @HostAttrs <hostname>')
                if self.sections[0].has_pending_with():
                    raise ParserException('@with not supported with @HostAttrs')
                self.sections.append(HostAttrs(parts[0]))
                return True
            if keyword == 'Host':
                if len(parts) != 1:
                    raise ParserException('usage: Host <hostname>')
                self.sections.append(Host(parts[0], self.sections[0].pop_pending_with()))
                return True

        def handle_vardef(root, keyword, parts):
            if keyword == '@with':
                root.add_pending_with(parts)
                return True

        def handle_set_args(_, parts):
            if len(parts) == 0:
                raise ParserException('usage: @args arg-name ...')
            if not self.is_include():
                return
            if self._args is None or len(self._args) != len(parts):
                raise ParserException('required arguments not passed to include {url} ({parts})'.format(
                    url=self._url,
                    parts=', '.join(parts))
                )
            root = self.sections[0]
            for key, value in zip(parts, self._args):
                root.set_value(key, value)

        def handle_set_value(_, parts):
            if len(parts) != 2:
                raise ParserException('usage: @set <key> <value>')
            root = self.sections[0]
            root.set_value(*resolve_args(parts))

        def handle_add_type(section, parts):
            if len(parts) != 1:
                raise ParserException('usage: @is <HostAttrName>')
            section.add_type(parts[0])

        def handle_via(section, parts):
            if len(parts) != 1:
                raise ParserException('usage: @via <Hostname>')
            section.add_line(
                'ProxyCommand',
                ('ssh {args} nc %h %p 2> /dev/null'.format(args=pipes.quote(resolve_args(parts)[0])), )
            )

        def handle_identity(section, parts):
            if len(parts) != 1:
                raise ParserException('usage: @identity <name>')
            section.add_identity(resolve_args(parts)[0])

        def handle_include(_, parts):
            if len(parts) == 0:
                raise ParserException('usage: @include <https://...|/path/to/file.sedge> [arg ...]')
            url = parts[0]
            parsed_url = urllib.parse.urlparse(url)
            if parsed_url.scheme == 'https':
                req = requests.get(url, verify=self._verify_ssl)
                text = req.text
            elif parsed_url.scheme == 'file':
                with open(parsed_url.path) as fd:
                    text = fd.read()
            elif parsed_url.scheme == '':
                path = os.path.expanduser(url)
                with open(path) as fd:
                    text = fd.read()
            else:
                raise SecurityException('error: @includes may only use paths or https:// or file:// URLs')

            subconfig = SedgeEngine(
                self._key_library,
                StringIO(text),
                self._verify_ssl,
                url=url,
                args=resolve_args(parts[1:]),
                parent_keydefs=self.keydefs,
                via_include=True)
            self.includes.append((url, subconfig))

        def handle_keydef(_, parts):
            if len(parts) < 2:
                raise ParserException('usage: @key <name> [fingerprint]...')
            name = parts[0]
            fingerprints = parts[1:]
            self.keydefs[name] = fingerprints

        def handle_keyword(section, keyword, parts):
            handlers = {
                '@set': handle_set_value,
                '@args': handle_set_args,
                '@is': handle_add_type,
                '@via': handle_via,
                '@include': handle_include,
                '@key': handle_keydef,
                '@identity': handle_identity
            }
            if keyword in handlers:
                handlers[keyword](section, parts)
                return True

        for line in (t.strip() for t in fd):
            if line.startswith('#') or line == '':
                continue
            keyword, parts = SedgeEngine.parse_config_line(line)
            if handle_section_defn(keyword, parts):
                continue
            if handle_vardef(self.sections[0], keyword, parts):
                continue
            current_section = self.sections[-1]
            if handle_keyword(current_section, keyword, parts):
                continue
            if keyword.startswith('@'):
                raise ParserException("unknown expansion keyword {}".format(keyword))
            # use other rather than parts to avoid messing up user
            # whitespace; we don't handle quotes in here as we don't
            # need to
            current_section.add_line(keyword, parts)
52060
def percentage(value: str) -> float:
    
    try:
        fvalue = float(value)
        assert 0 <= fvalue <= 100
    except (AssertionError, TypeError, ValueError):
        raise ArgumentTypeError(
            "{!r} is an invalid percentage value".format(value))
    return fvalue
749590
function _calcExtension(filename, currentExt) {
	// simply return the rightmost extension
	var ext = filename.split('.').slice(-1);
	if (ext=='tem' || ext=='html')
		// revert to html if no better option.
		// The html check is here to rename 'tem.html' to '.hubla' if 'hubla' has been set as the new default extension
		return _config.DEF_EXTENSION;
	return ext;
}
141134
def parse_value(self, frmtcode, buff, start, end):
        '''
            
        '''
        
        frmttype = self.util._formatmap[frmtcode]
        if(frmtcode == FormatType.FLOAT_32.value.code):  # @UndefinedVariable
            return self.parse_float32(buff, start, end)
        elif(frmtcode == FormatType.FLOAT_64.value.code):  # @UndefinedVariable
            return self.parse_float64(buff, start, end)
        if frmttype.value.idx <= FormatType.FIXSTR.value.idx:  # @UndefinedVariable  
            return self.parse_str(buff, start, end)
        elif frmttype.value.idx <= FormatType.INT_64.value.idx:  # @UndefinedVariable
            return self.parse_int(buff, start, end)
        elif frmttype.value.idx <= FormatType.UINT_64.value.idx:  # @UndefinedVariable
            return self.parse_uint(buff, start, end)
626490
def format_endpoint(schema, addr, port, api_version):
    
    return '{}://{}:{}/{}/'.format(schema, addr, port,
                                   get_api_suffix(api_version))
216403
def split_by_extensions(filename):
        
        parts = filename.split('.')
        idx = len(parts) - 1
        while FileFormat.is_file_format(parts[idx]):
            parts[idx] = FileFormat(parts[idx])
            idx -= 1
        return ['.'.join(parts[:idx + 1])] + parts[idx + 1:]
810715
def _format_exe_info(py_len, exeinfo, format, indlevel):
    """"""
    ret = []
    ind = " " * indlevel * NIND if format.startswith("text") else ""
    if format == "markdown-list":
        for si in exeinfo:
            ret.append("  - `{0!s}`: {1!s}".format(si.filename, si.description))
    if format == "rest-list":
        for si in exeinfo:
            ret.append("* ``{0!s}``: {1!s}".format(si.filename, si.description))
    elif format == "markdown-table":
        mask = "%-{0:d}s | %s".format(py_len+2 )
        ret.append(mask % ("Script name", "Purpose"))
        ret.append("-" * (py_len + 3) + "|" + "-" * 10)
        for si in exeinfo:
            ret.append(mask % ("`{0!s}`".format(si.filename), si.description))
    elif format == "text":
        sbc = 1  # spaces between columns
        for si in exeinfo:
            ss = textwrap.wrap(si.description, 79 - py_len - sbc - indlevel*NIND)
            for i, s in enumerate(ss):
                if i == 0:
                    filecolumn = si.filename + " " + ("." * (py_len - len(si.filename)))
                else:
                    filecolumn = " " * (py_len + 1)

                ret.append("{}{}{}{}".format(ind, filecolumn, " "*sbc, s))
    ret.append("")
    return ret
1217208
def as_percent(self, precision=2, *args, **kwargs):
        
        f = Formatter(as_percent(precision), args, kwargs)
        return self._add_formatter(f)
109653
def as_percent(self, percent):
        
        if not self:
            return self.wrap_str()

        length = len(self)
        # Using mod 100, to provide some kind of "auto reset". 0 is 0 though.
        percentmod = (int(percent) % 100) or min(percent, 100)
        index = int((length / 100) * percentmod)
        try:
            barstr = str(self[index])
        except IndexError:
            barstr = self[-1]

        return self.wrap_str(barstr)