The format template interpetation engine.  See the comment at the
        beginning of this module for the how we interpret format
        specifications such as %c, %C, and so on.
971191
def template_engine(self, entry, startnode):
        

        # print("-----")
        # print(startnode)
        # print(entry[0])
        # print('======')

        startnode_start = len(self.f.getvalue())
        start = startnode_start

        fmt = entry[0]
        arg = 1
        i = 0
        lastC = -1
        recurse_node = False

        m = escape.search(fmt)
        while m:
            i = m.end()
            self.write(m.group('prefix'))

            typ = m.group('type') or '{'
            node = startnode
            try:
                if m.group('child'):
                    node = node[int(m.group('child'))]
                    node.parent = startnode
            except:
                print(node.__dict__)
                raise

            if typ == '%':
                start = len(self.f.getvalue())
                self.write('%')
                self.set_pos_info(node, start, len(self.f.getvalue()))

            elif typ == '+': self.indent_more()
            elif typ == '-': self.indent_less()
            elif typ == '|': self.write(self.indent)
            # no longer used, since BUILD_TUPLE_n is pretty printed:
            elif typ == 'r': recurse_node = True
            elif typ == ',':
                if lastC == 1:
                    self.write(',')
            elif typ == 'b':
                finish = len(self.f.getvalue())
                self.set_pos_info(node[entry[arg]], start, finish)
                arg += 1
            elif typ == 'c':
                start = len(self.f.getvalue())

                index = entry[arg]
                if isinstance(index, tuple):
                    assert node[index[0]] == index[1], (
                        "at %s[%d], expected %s node; got %s" % (
                            node.kind, arg, node[index[0]].kind, index[1])
                        )
                    index = index[0]
                assert isinstance(index, int), (
                    "at %s[%d], %s should be int or tuple" % (
                        node.kind, arg, type(index)))
                self.preorder(node[index])

                finish = len(self.f.getvalue())
                self.set_pos_info(node, start, finish)
                arg += 1
            elif typ == 'p':
                p = self.prec
                (index, self.prec) = entry[arg]
                node[index].parent = node
                start = len(self.f.getvalue())
                self.preorder(node[index])
                self.set_pos_info(node, start, len(self.f.getvalue()))
                self.prec = p
                arg += 1
            elif typ == 'C':
                low, high, sep = entry[arg]
                lastC = remaining = len(node[low:high])
                start = len(self.f.getvalue())
                for subnode in node[low:high]:
                    self.preorder(subnode)
                    remaining -= 1
                    if remaining > 0:
                        self.write(sep)

                self.set_pos_info(node, start, len(self.f.getvalue()))
                arg += 1
            elif typ == 'D':
                low, high, sep = entry[arg]
                lastC = remaining = len(node[low:high])
                for subnode in node[low:high]:
                    remaining -= 1
                    if len(subnode) > 0:
                        self.preorder(subnode)
                        if remaining > 0:
                            self.write(sep)
                            pass
                        pass
                    pass
                arg += 1
            elif typ == 'x':
                src, dest = entry[arg]
                for d in dest:
                    self.set_pos_info_recurse(node[d], node[src].start, node[src].finish)
                    pass
                arg += 1
            elif typ == 'P':
                p = self.prec
                low, high, sep, self.prec = entry[arg]
                lastC = remaining = len(node[low:high])
                start = self.last_finish
                for subnode in node[low:high]:
                    self.preorder(subnode)
                    remaining -= 1
                    if remaining > 0:
                        self.write(sep)
                self.prec = p
                arg += 1

            elif typ == '{':
                d = node.__dict__
                expr = m.group('expr')

                # Line mapping stuff
                if (hasattr(node, 'linestart') and node.linestart
                    and hasattr(node, 'current_line_number')):
                    self.source_linemap[self.current_line_number] = node.linestart
                # Additional fragment-position stuff
                try:
                    start = len(self.f.getvalue())
                    self.write(eval(expr, d, d))
                    self.set_pos_info(node, start, len(self.f.getvalue()))
                except:
                    print(node)
                    raise
            m = escape.search(fmt, i)
            pass

        self.write(fmt[i:])
        fin = len(self.f.getvalue())
        if recurse_node:
            self.set_pos_info_recurse(startnode, startnode_start, fin)
        else:
            self.set_pos_info(startnode, startnode_start, fin)

        # FIXME rocky: figure out how to get these casess to be table driven.
        # 2. subroutine calls. It the last op is the call and for purposes of printing
        # we don't need to print anything special there. However it encompases the
        # entire string of the node fn(...)
        if startnode.kind == 'call':
            last_node = startnode[-1]
            self.set_pos_info(last_node, startnode_start, self.last_finish)
        return
1347694
function compile(format) {
  /* istanbul ignore if */
  if (typeof format !== 'string') {
    throw new TypeError('argument format must be a string');
  }
  const fmt = format.replace(/"/g, '\\"');
  /* eslint prefer-template:0 */
  const js = '  return "'
    + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, (_, name, arg) => {
      const str = '"\n    + (tokens["' + name + '"](ctx, ';
      return str + String(JSON.stringify(
        arg,
      )) + ') || "-") + "';
    }) + '";';
  /* eslint no-new-func:0 */
  return new Function('tokens, ctx', js);
}
1028164
def input_format(&block)
      case
      when block && !@input_format_block
        @input_format_block = block
      when !block && @input_format_block
        return @input_format ||= Apipie::Params::Description.define(&@input_format_block)
      when block && @input_format_block
        raise "The input_format has already been defined in #{self.class}"
      when !block && !@input_format_block
        if superclass.respond_to? :input_format
          superclass.input_format
        else
          raise "The input_format has not been defined yet in #{self.class}"
        end
      end
    end
1285324
def format(self, format_spec='f'):
        
        """
        if format_spec == '' or format_spec == 'f':
            cpf = CPF.clean(self._cpf)
            return '{0}.{1}.{2}-{3}'.format(cpf[0:3], cpf[3:6], cpf[6:9], cpf[9:11])
        if format_spec == 'r':
            return self._cpf
        raise ValueError(
            "Unknown format code '{0}' for object of type '{1}'".format(format_spec, CPF.__name__))
656337
def _convert_template_option(template):
    '''
    '''

    option = {}
    extraction_method = template.get('extraction_method')
    if extraction_method == 'guess':
        option['guess'] = True
    elif extraction_method == 'lattice':
        option['lattice'] = True
    elif extraction_method == 'stream':
        option['stream'] = True

    option['pages'] = template.get('page')
    option['area'] = [round(template['y1'], 3), round(template['x1'], 3), round(template['y2'], 3), round(template['x2'], 3)]

    return option
21677
def codegen(cc):
    

    import inspect

    def format_desc(obj, indent):
        linelen = 75 - indent
        if isinstance(obj, six.string_types):
            raw = obj
        else:
            try:
                raw = obj.qualifiers['description'].value
            except KeyError:
                return ''
        txt = ''
        beg = 0
        end = 0
        while beg < len(raw):
            beg = end
            end += linelen
            while beg < len(raw) and raw[beg].isspace():
                beg = beg+1
            while end < len(raw) and end > beg and not raw[end].isspace():
                end = end-1
            if beg == end: # a long URL
                while end < len(raw) and not raw[end].isspace():
                    end += 1
            line = raw[beg:end]
            line = line.replace('\n', ' ')
            line = line.replace('\r', '')
            txt += '\n%s%s'% (''.ljust(indent), line)
        return txt

    #################
    def map_value(obj, val):
        rv = str(val)
        if 'ValueMap' not in obj.qualifiers:
            return rv
        if 'Values' not in obj.qualifiers:
            return rv
        vals = [str(x) for x in obj.qualifiers['Values'].value]
        maps = [str(x) for x in obj.qualifiers['ValueMap'].value]
        d = dict(zip(maps, vals))
        try:
            tmp = d[str(val)]
            rv = ''
            for ch in tmp:
                rv += ch.isalnum() and ch or '_'
        except KeyError:
            pass
        return rv

    #################
    def type_hint(obj, method_name=None):
        if hasattr(obj, 'type'):
            tx = obj.type
            if 'embeddedinstance' in obj.qualifiers:
                tx = "pywbem.CIMInstance(classname='%s', ...)" % \
                        obj.qualifiers['embeddedinstance'].value
            elif tx == 'reference':
                tx = "pywbem.CIMInstanceName(classname='%s', ...)" % \
                        obj.reference_class
        else:
            tx = obj.return_type
        if hasattr(obj, 'value') and obj.value is not None:
            defval = str(obj.value)
        else:
            defval = ''
        if not tx.startswith('pywbem.'):
            if tx == 'boolean':
                tx = 'bool(%s)' % defval
            elif tx == 'datetime':
                tx = 'pywbem.CIMDateTime()'
            elif tx == 'string':
                tx = "''"
            else:
                tx = 'pywbem.%s(%s)' % (tx.capitalize(), defval)
        if 'valuemap' in obj.qualifiers:
            if defval:
                defval = map_value(obj, defval)
            else:
                defval = '<VAL>'
            tx = 'self.Values.%s%s.%s' % \
                    (method_name and '%s.'%method_name or '',
                     obj.name, defval)
        if hasattr(obj, 'is_array') and obj.is_array:
            tx = '[%s,]' % tx
        return tx
    #################
    def type_str(obj, method_name=None):
        if hasattr(obj, 'type'):
            tx = obj.type
            if 'embeddedinstance' in obj.qualifiers:
                return "pywbem.CIMInstance(classname='%s', ...)" % \
                        obj.qualifiers['embeddedinstance'].value
            elif tx == 'reference':
                return "REF (pywbem.CIMInstanceName(classname='%s', ...)" % \
                        obj.reference_class
        else:
            tx = obj.return_type
        if tx == 'boolean':
            tx = 'bool'
        elif tx == 'datetime':
            tx = 'pywbem.CIMDateTime'
        elif tx == 'string':
            tx = 'unicode'
        else:
            tx = 'pywbem.%s' % tx.capitalize()
        if hasattr(obj, 'is_array') and obj.is_array:
            tx = '[%s,]' % tx
        if 'valuemap' in obj.qualifiers:
            tx += ' self.Values.%s%s' % \
                    (method_name and '%s.' % method_name or '', obj.name)
        return tx
    #################
    def is_required(obj):
        if 'required' in obj.qualifiers and obj.qualifiers['required'].value:
            return '(Required)'
        return ''
    #################
    def build_val_map(obj):
        vm = obj.qualifiers['valuemap'].value
        if 'values' in obj.qualifiers:
            vals = obj.qualifiers['values'].value
        else:
            vals = vm
        tmap = zip(vals, vm)
        map = []
        for t in tmap:
            nname = ''
            for ch in t[0]:
                if ch.isalnum():
                    nname += ch
                else:
                    nname += '_'
            if hasattr(obj, 'return_type'):
                tp = obj.return_type
            else:
                tp = obj.type
            if tp == 'string':
                val = "'%s'" % t[1]
            else:
                try:
                    int(t[1])
                    val = 'pywbem.%s(%s)' % (tp.capitalize(), t[1])
                except ValueError:
                    val = t[1]
                    nname = "# "+nname
            map.append((nname, val))
        return map

    valuemaps = {}

    for obj in cc.properties.values() + cc.methods.values():
        if 'valuemap' in obj.qualifiers:
            valuemaps[obj.name] = {'<vms>':build_val_map(obj)}

    for meth in cc.methods.values():
        for parm in meth.parameters.values():
            if 'valuemap' in parm.qualifiers:
                if meth.name not in valuemaps:
                    valuemaps[meth.name] = {}
                valuemaps[meth.name][parm.name] = build_val_map(parm)

    mappings = {'classname':cc.classname,
                'classname_l':cc.classname.lower()}
    isAssoc = 'association' in cc.qualifiers

    code = '''"""Python Provider for %(classname)s

Instruments the CIM class %(classname)s

"""

import pywbem

class %(classname)sProvider(pywbem.CIMProvider):
    """Instrument the CIM class %(classname)s \n''' % mappings
    code += format_desc(cc, 4)
    code += '''
    """'''


    args = inspect.getargspec(CIMProvider.get_instance)[0]
    args = ', '.join(args)
    code += '''

    def __init__ (self, env):
        logger = env.get_logger()
        logger.log_debug('Initializing provider %%s from %%s' \\
                %% (self.__class__.__name__, __file__))
        # If you will be filtering instances yourself according to
        # property_list, role, result_role, and result_class_name
        # parameters, set self.filter_results to False
        # self.filter_results = False

    def get_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.get_instance()' \\
                %% self.__class__.__name__)
        ''' % (args, CIMProvider.get_instance.__doc__)
    keyProps = [p for p in cc.properties.values() \
                if 'key' in p.qualifiers]
    code += '''
        ux = model.update_existing

        # TODO fetch system resource matching the following keys:'''
    for kp in keyProps:
        code += '''
        #   model['%s']''' % kp.name
    code += '\n'
    props = cc.properties.values()
    props.sort()
    for prop in props:
        if 'key' in prop.qualifiers:
            continue
        #line = "#ux(%s=%s) # TODO (type = %s) %s" % \
        #        (prop.name, type_hint(prop), type_str(prop), is_required(prop))
        line = "#ux(%s=%s) # TODO %s" % \
                (prop.name, type_hint(prop), is_required(prop))
        code += '''
        %s''' % line

    args = inspect.getargspec(CIMProvider.enum_instances)[0]
    args = ', '.join(args)
    code += '''
        return model

    def enum_instances(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.enum_instances()' \\
                %% self.__class__.__name__)

        while False: # TODO more instances?
            # TODO fetch system resource
            # Key properties''' % (args, CIMProvider.enum_instances.__doc__)
    for kp in keyProps:
        if kp.name == 'CreationClassName':
            line = "model['%s'] = '%s'" % (kp.name, cc.classname)
        else:
            line = "#model['%s'] = # TODO (type = %s)" % \
                    (kp.name, type_str(kp))
        code += '''
            %s''' % line
    code += '''
            if keys_only:
                yield model
            else:
                try:
                    yield self.get_instance(env, model, cim_class)
                except pywbem.CIMError as exc:
                    num, msg = exc.args
                    if num not in (pywbem.CIM_ERR_NOT_FOUND,
                                   pywbem.CIM_ERR_ACCESS_DENIED):
                        raise\n'''

    args = inspect.getargspec(CIMProvider.set_instance)[0]
    args = ', '.join(args)
    code += '''
    def set_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.set_instance()' \\
                %% self.__class__.__name__)
        # TODO create or modify the instance
        raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
        return instance''' % (args, CIMProvider.set_instance.__doc__)

    args = inspect.getargspec(CIMProvider.delete_instance)[0]
    args = ', '.join(args)
    code += '''

    def delete_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.delete_instance()' \\
                %% self.__class__.__name__)

        # TODO delete the resource
        raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
        ''' % (args, CIMProvider.delete_instance.__doc__)

    for method in cc.methods.values():
        inParms = [p for p in method.parameters.values() if \
                    'in' in p.qualifiers and p.qualifiers['in'].value]
        outParms = [p for p in method.parameters.values() if \
                    'out' in p.qualifiers and p.qualifiers['out'].value]
        code += '''
    def cim_method_%s(self, env, object_name, method''' % method.name.lower()
        for p in inParms:
            code += ''',\n%sparam_%s''' % (''.rjust(len(method.name)+20),
                                           p.name.lower())
        code += '''):
        """Implements %s.%s()\n''' % (cc.classname, method.name)
        code += format_desc(method, 8)

        code += '''
        Keyword arguments:
        env -- Provider Environment (pycimmb.ProviderEnvironment)
        object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
            specifying the object on which the method %s()
            should be invoked.
        method -- A pywbem.CIMMethod representing the method meta-data''' \
                % method.name

        for p in inParms:
            code += '''
        param_%s --  The input parameter %s (type %s) %s''' \
                    % (p.name.lower(), p.name, type_str(p, method.name),
                       is_required(p))
            code += format_desc(p, 12)

        code += '''

        Returns a two-tuple containing the return value (type %s)
        and a dictionary with the out-parameters

        Output parameters:''' % type_str(method)

        if not outParms:
            code += ' none'
        else:
            for p in outParms:
                code += '''
        %s -- (type %s) %s''' % (p.name, type_str(p, method.name),
                                 is_required(p))
                code += format_desc(p, 12)

        code += '''

        Possible Errors:
        CIM_ERR_ACCESS_DENIED
        CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
            unrecognized or otherwise incorrect parameters)
        CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
            exist in the specified namespace)
        CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
            the invocation request)
        CIM_ERR_FAILED (some other unspecified error occurred)

        """

        logger = env.get_logger()
        logger.log_debug('Entering %%s.cim_method_%s()' \\
                %% self.__class__.__name__)

        # TODO do something
        raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
        out_params = {}''' % method.name.lower()

        for p in outParms:
            code += '''
        #out_params['%s'] = %s # TODO''' % \
                (p.name.lower(), type_hint(p, method.name))

        code += '''
        rval = None # TODO (type %s)
        return (rval, out_params)
        ''' % type_str(method)

    if isAssoc:
        args = inspect.getargspec(CIMProvider.references)[0]
        args = format_desc(', '.join(args), 19).strip()
        code += '''
    def references(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.references()' \\
                %% self.__class__.__name__)
        ch = env.get_cimom_handle()
        # This is a common pattern.  YMMV''' % \
                (args, CIMProvider.references.__doc__)
        refprops = []
        for prop in cc.properties.values():
            if prop.reference_class is not None:
                refprops.append((prop.name, prop.reference_class))
        for refprop in refprops:
            code += '''
        if (not role or role.lower() == '%(refpropnamel)s') and \\
           pywbem.is_subclass(ch, object_name.namespace,
                       sub=object_name.classname,
                       super='%(rolecname)s'):
            model['%(refpropname)s'] = object_name
            yield model # TODO: Add other REF properties.
                        # Yield association instances where
                        # object_name is %(refpropnamel)s.
                        # Only appropriate if object_name.classname
                        # is '%(rolecname)s' or a subclass.\n''' \
                               % {'refpropname':refprop[0],
                                  'refpropnamel':refprop[0].lower(),
                                  'rolecname':refprop[1]}

    if valuemaps:
        code += '''
    class Values(object):'''
        for group, maps in valuemaps.items():
            code += '''
        class %s(object):''' % group
            if '<vms>' in maps:
                for value, vm in maps['<vms>']:
                    if value in maps:
                        value = value+'_'
                    code += '''
            %s = %s''' % (value, vm)
            for pname, vms in maps.items():
                if pname == '<vms>':
                    continue
                code += '''
            class %s(object):''' % pname
                for value, vm in vms:
                    code += '''
                %s = %s''' % (value, vm)
            code += '\n'

    code += '''
## end of class %(classname)sProvider

def get_providers(env):
    %(classname_l)s_prov = %(classname)sProvider(env)
    return {'%(classname)s': %(classname_l)s_prov}
''' % mappings

    owtypes = ['1', 'Instance']
    pegtypes = ['2', 'Instance']
    if isAssoc:
        owtypes[0] += ',3'
        owtypes[1] += ', Associator'
        pegtypes[0] += ',3'
        pegtypes[1] += ', Associator'
    if cc.methods:
        owtypes[0] += ',6'
        owtypes[1] += ', Method'
        pegtypes[0] += ',5'
        pegtypes[1] += ', Method'
    mof = '''
// OpenWBEM Provider registration for %(classname)s
instance of OpenWBEM_PyProviderRegistration
{
    InstanceID = "<org:product:%(classname)s:unique_id>"; // TODO
    NamespaceNames = {"root/cimv2"}; // TODO
    ClassName = "%(classname)s";
    ProviderTypes = {%(owtypeNums)s};  // %(owtypeStrs)s
    ModulePath = "/usr/lib/pycim/%(classname)sProvider.py";  // TODO
};

// Pegasus Provider registration for %(classname)s
instance of PG_ProviderModule
{
    Name = "/usr/lib/pycim/%(classname)sProvider.py";
    InterfaceType = "Python";
    InterfaceVersion = "1.0.0";
    Location = "/usr/lib/pycim/%(classname)sProvider.py";
    UserContext = 2; // Requestor
    Vendor = "TODO"; // TODO
    Version = "1.0";
};
instance of PG_Provider
{
    Name = "%(classname)s";
    ProviderModuleName = "/usr/lib/pycim/%(classname)sProvider.py";
};
instance of PG_ProviderCapabilities
{
    CapabilityID = "%(classname)s";
    ProviderModuleName = "/usr/lib/pycim/%(classname)sProvider.py";
    ProviderName = "%(classname)s";
    ClassName = "%(classname)s";
    Namespaces = {"root/cimv2"}; // TODO
    ProviderType = {%(pegtypeNum)s}; // %(pegtypeStr)s
};\n''' % {'classname': cc.classname,
           'owtypeNums': owtypes[0],
           'owtypeStrs': owtypes[1],
           'pegtypeNum': pegtypes[0],
           'pegtypeStr': pegtypes[1]}


    return code, mof
1235739
def format_template(template, content):
    """"""

    import pystache
    result = u""
    if True:  # try:
        result = pystache.render(template, content, string_encoding='utf-8')
    # except (ValueError, KeyError) as e:
    #    print("Templating error: %s %s" % (e, type(e)))

    # pprint(result)
    return result
640618
def _generate_code(self, source):
        

        if not isinstance(source, str_class):
            raise PybarsError("Template source must be a unicode string")

        tree, (position, _) = self._handlebars(source).apply('template')

        self.clean_whitespace(tree)

        if debug:
            print('\nAST')
            print('---')
            print(tree)
            print('')

        if position < len(source):
            line_num = source.count('\n') + 1
            beginning_of_line = source.rfind('\n', 0, position)
            if beginning_of_line == -1:
                char_num = position
            else:
                char_num = position - beginning_of_line
            word = self._extract_word(source, position)
            raise PybarsError("Error at character %s of line %s near %s" % (char_num, line_num, word))

        # Ensure the builder is in a clean state - kinda gross
        self._compiler.globals['builder']._reset()

        output = self._compiler(tree).apply('compile')[0]
        return output
87195
def compiled(template, delimiters=DEFAULT_DELIMITERS):
    
    re_tag = delimiters_to_re(delimiters)

    # variable to save states
    tokens = []
    index = 0
    sections = []
    tokens_stack = []

    # root token
    root = Root('root')
    root.filters = copy.copy(filters)

    m = re_tag.search(template, index)
    while m is not None:
        token = None
        last_literal = None
        strip_space = False

        if m.start() > index:
            last_literal = Literal('str', template[index:m.start()], root=root)
            tokens.append(last_literal)

        # parse token
        prefix, name, suffix = m.groups()

        if prefix == '=' and suffix == '=':
            # {{=| |=}} to change delimiters
            delimiters = re.split(r'\s+', name)
            if len(delimiters) != 2:
                raise SyntaxError('Invalid new delimiter definition: ' + m.group())
            re_tag = delimiters_to_re(delimiters)
            strip_space = True

        elif prefix == '{' and suffix == '}':
            # {{{ variable }}}
            token = Variable(name, name, root=root)

        elif prefix == '' and suffix == '':
            # {{ name }}
            token = Variable(name, name, root=root)
            token.escape = True

        elif suffix != '' and suffix != None:
            raise SyntaxError('Invalid token: ' + m.group())

        elif prefix == '&':
            # {{& escaped variable }}
            token = Variable(name, name, root=root)

        elif prefix == '!':
            # {{! comment }}
            token = Comment(name, root=root)
            if len(sections) <= 0:
                # considered as standalone only outside sections
                strip_space = True

        elif prefix == '>':
            # {{> partial}}
            token = Partial(name, name, root=root)
            strip_space = True

            pos = is_standalone(template, m.start(), m.end())
            if pos:
                token.indent = len(template[pos[0]:m.start()])

        elif prefix == '#' or prefix == '^':
            # {{# section }} or # {{^ inverted }}

            # strip filter
            sec_name = name.split('|')[0].strip()
            token = Section(sec_name, name, root=root) if prefix == '#' else Inverted(name, name, root=root)
            token.delimiter = delimiters
            tokens.append(token)

            # save the tokens onto stack
            token = None
            tokens_stack.append(tokens)
            tokens = []

            sections.append((sec_name, prefix, m.end()))
            strip_space = True

        elif prefix == '/':
            tag_name, sec_type, text_end = sections.pop()
            if tag_name != name:
                raise SyntaxError("unclosed tag: '" + tag_name + "' Got:" + m.group())

            children = tokens
            tokens = tokens_stack.pop()

            tokens[-1].text = template[text_end:m.start()]
            tokens[-1].children = children
            strip_space = True

        else:
            raise SyntaxError('Unknown tag: ' + m.group())

        if token is not None:
            tokens.append(token)

        index = m.end()
        if strip_space:
            pos = is_standalone(template, m.start(), m.end())
            if pos:
                index = pos[1]
                if last_literal: last_literal.value = last_literal.value.rstrip(spaces_not_newline)

        m = re_tag.search(template, index)

    tokens.append(Literal('str', template[index:]))
    root.children = tokens
    return root
1353464
private void processSchemaComment() {
        // Removing DOCTYPE:
        burnCharacters(syntax.getDocumentTypeOpening().length());
        int tagsOpened = 1;
        while (templateReader.hasNextCharacter()) {
            final char character = templateReader.nextCharacter();
            // Schema comment can define new entities, see http://www.w3schools.com/xml/xml_dtd.asp
            if (character == syntax.getTagOpening()) {
                tagsOpened++;
            } else if (character == syntax.getTagClosing()) {
                if (--tagsOpened == 0) {
                    break;
                }
            }
        }
    }
1029163
def format_help(self, ctx, formatter):
        
        self.format_usage(ctx, formatter)
        self.format_help_text(ctx, formatter)
        self.format_options(ctx, formatter)
        self.format_epilog(ctx, formatter)
222709
function messageFormat (type, inspect) {
  var msg = this.detailed
    ? 'expect %s `%s`, but %s `%s` given'
    : 'expect `%s`, but `%s` given'
  return this.detailed
    ? util.format(msg, type.expected, inspect.expected, type.actual, inspect.actual)
    : util.format(msg, type.expected, type.actual)
}
909315
def parse_format_specifier(specification):
    
    m = _parse_format_specifier_regex.match(specification)
    if m is None:
        raise ValueError(
            "Invalid format specifier: {!r}".format(specification))
    format_dict = m.groupdict('')

    # Convert zero-padding into fill and alignment.
    zeropad = format_dict.pop('zeropad')
    if zeropad:
        # If zero padding is requested, fill and align fields should be absent.
        if format_dict['align']:
            raise ValueError(
                "Invalid format specifier: {!r}".format(specification))
        # Impossible to have 'fill' without 'align'.
        assert not format_dict['fill']
        format_dict['align'] = '='
        format_dict['fill'] = '0'

    # Default alignment is right-aligned.
    if not format_dict['align']:
        format_dict['align'] = '>'

    # Default fill character is space.
    if not format_dict['fill']:
        format_dict['fill'] = ' '

    # Default sign is '-'.
    if not format_dict['sign']:
        format_dict['sign'] = '-'

    # Convert minimum width to an int; default is zero.
    format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')

    # Convert precision to an int, or `None` if no precision given.
    if format_dict['precision']:
        format_dict['precision'] = int(format_dict['precision'][1:])
    else:
        format_dict['precision'] = None

    # If no rounding mode is given, assume 'N'.
    if not format_dict['rounding']:
        format_dict['rounding'] = 'N'

    return format_dict
411214
def format_template_file(filename, content):
    """"""

    with open(filename, 'r') as f:
        template = f.read()
        if type(template) != str:
            template = template.decode('utf-8')

    return format_template(template, content)
393217
def determine_template(options)
        keys = options.has_key?(:locals) ? options[:locals].keys : []

        if options.key?(:body)
          Template::Text.new(options[:body])
        elsif options.key?(:plain)
          Template::Text.new(options[:plain])
        elsif options.key?(:html)
          Template::HTML.new(options[:html], formats.first)
        elsif options.key?(:file)
          if File.exist?(options[:file])
            Template::RawFile.new(options[:file])
          else
            ActiveSupport::Deprecation.warn "render file: should be given the absolute path to a file"
            @lookup_context.with_fallbacks.find_template(options[:file], nil, false, keys, @details)
          end
        elsif options.key?(:inline)
          handler = Template.handler_for_extension(options[:type] || "erb")
          format = if handler.respond_to?(:default_format)
            handler.default_format
          else
            @lookup_context.formats.first
          end
          Template::Inline.new(options[:inline], "inline template", handler, locals: keys, format: format)
        elsif options.key?(:template)
          if options[:template].respond_to?(:render)
            options[:template]
          else
            @lookup_context.find_template(options[:template], options[:prefixes], false, keys, @details)
          end
        else
          raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :html or :body option."
        end
      end
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
158314
def _FormatMessage(template, parameters):
  
  def GetParameter(m):
    try:
      return parameters[int(m.group(0)[1:])]
    except IndexError:
      return INVALID_EXPRESSION_INDEX

  parts = template.split('$$')
  return '$'.join(re.sub(r'\$\d+', GetParameter, part) for part in parts)