Generate entries from TypoScript
423336
public function generateEntriesFromTypoScript()
    {
        $urlEntries = $this->pluginConfig['urlEntries'];
        foreach ($urlEntries as $urlEntry) {
            if (!empty($urlEntry['active'])) {
                $this->mapToEntries($urlEntry);
            }
        }
    }
888647
def generate_enums(outf, enums, msgs):
    """"""

    print("Generating Enums")

    for enum in enums:
        t.write(outf, """
${formatted_description}public enum ${swift_name}: ${raw_value_type}, Enum {
${{entry:${formatted_description}\tcase ${swift_name} = ${value}\n}}
}

extension ${swift_name} {
    public static var typeName = "${name}"
    public static var typeDescription = "${entity_description}"
    public static var typeDebugDescription: String {
        let cases = "\\n\\t".join(allMembers.map { $0.debugDescription })
        return "Enum \(typeName): \(typeDescription)\\nMembers:\\n\\t\(cases)"
    }
    public static var allMembers = [${all_entities}]
    public static var membersInfo = [${entities_info}]
}

""", enum)
1357365
def generate_example_input(inptype,     # type: Any
                           default      # type: Optional[Any]
                          ):  # type: (...) -> Tuple[Any, Text]
    """"""
    example = None
    comment = u""
    defaults = {u'null': 'null',
                u'Any': 'null',
                u'boolean': False,
                u'int': 0,
                u'long': 0,
                u'float': 0.1,
                u'double': 0.1,
                u'string': 'a_string',
                u'File': yaml.comments.CommentedMap([
                    ('class', 'File'), ('path', 'a/file/path')]),
                u'Directory': yaml.comments.CommentedMap([
                    ('class', 'Directory'), ('path', 'a/directory/path')])
               }  # type: Dict[Text, Any]
    if isinstance(inptype, collections.MutableSequence):
        optional = False
        if 'null' in inptype:
            inptype.remove('null')
            optional = True
        if len(inptype) == 1:
            example, comment = generate_example_input(inptype[0], default)
            if optional:
                if comment:
                    comment = u"{} (optional)".format(comment)
                else:
                    comment = u"optional"
        else:
            example = yaml.comments.CommentedSeq()
            for index, entry in enumerate(inptype):
                value, e_comment = generate_example_input(entry, default)
                example.append(value)
                example.yaml_add_eol_comment(e_comment, index)
            if optional:
                comment = u"optional"
    elif isinstance(inptype, collections.Mapping) and 'type' in inptype:
        if inptype['type'] == 'array':
            if len(inptype['items']) == 1 and 'type' in inptype['items'][0] \
                    and inptype['items'][0]['type'] == 'enum':
                # array of just an enum then list all the options
                example = inptype['items'][0]['symbols']
                if 'name' in inptype['items'][0]:
                    comment = u'array of type "{}".'.format(inptype['items'][0]['name'])
            else:
                value, comment = generate_example_input(inptype['items'], None)
                comment = u"array of " + comment
                if len(inptype['items']) == 1:
                    example = [value]
                else:
                    example = value
            if default is not None:
                example = default
        elif inptype['type'] == 'enum':
            if default is not None:
                example = default
            elif 'default' in inptype:
                example = inptype['default']
            elif len(inptype['symbols']) == 1:
                example = inptype['symbols'][0]
            else:
                example = '{}_enum_value'.format(inptype.get('name', 'valid'))
            comment = u'enum; valid values: "{}"'.format(
                '", "'.join(inptype['symbols']))
        elif inptype['type'] == 'record':
            example = yaml.comments.CommentedMap()
            if 'name' in inptype:
                comment = u'"{}" record type.'.format(inptype['name'])
            for field in inptype['fields']:
                value, f_comment = generate_example_input(field['type'], None)
                example.insert(0, shortname(field['name']), value, f_comment)
        elif 'default' in inptype:
            example = inptype['default']
            comment = u'default value of type "{}".'.format(inptype['type'])
        else:
            example = defaults.get(inptype['type'], Text(inptype))
            comment = u'type "{}".'.format(inptype['type'])
    else:
        if not default:
            example = defaults.get(Text(inptype), Text(inptype))
            comment = u'type "{}"'.format(inptype)
        else:
            example = default
            comment = u'default value of type "{}".'.format(inptype)
    return example, comment
422554
def transform_source(text):
    '''
    '''

    loop_keyword = 'repeat'

    nb = text.count(loop_keyword)
    if nb == 0:
        return text

    var_names = get_unique_variable_names(text, nb)

    toks = tokenize.generate_tokens(StringIO(text).readline)
    result = []
    replacing_keyword = False
    for toktype, tokvalue, _, _, _ in toks:
        if toktype == tokenize.NAME and tokvalue == loop_keyword:
            result.extend([
                (tokenize.NAME, 'for'),
                (tokenize.NAME, var_names.pop()),
                (tokenize.NAME, 'in'),
                (tokenize.NAME, 'range'),
                (tokenize.OP, '(')
            ])
            replacing_keyword = True
        elif replacing_keyword and tokvalue == ':':
            result.extend([
                (tokenize.OP, ')'),
                (tokenize.OP, ':')
            ])
            replacing_keyword = False
        else:
            result.append((toktype, tokvalue))
    return tokenize.untokenize(result)
151565
function generateSnippet (config) {
    const apiKey = config.b || 'default_public';
    const username = config.c;
    const serverURL = config.d || 'https://{user}.carto.com';
    const vizSpec = config.e || '';
    const center = config.f || { lat: 0, lng: 0 };
    const zoom = config.g || 10;
    const basemap = BASEMAPS[config.h] || 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json';

    const source = config.i === sourceTypes.DATASET
        ? `new carto.source.Dataset("${config.a}")`
        : `new carto.source.SQL(\`${config.a}\`)`;

    return `<!DOCTYPE html>
<html>
<head>
<title>Exported map | CARTO VL</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<script src="http://libs.cartocdn.com/carto-vl/v${carto.version}/carto-vl.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js"></script>
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css" rel="stylesheet" />
<style>
    html, body {
        margin: 0;
    }
    #map {
        position: absolute;
        width: 100%;
        height: 100%;
    }
</style>
</head>
<body>
<div id="map"></div>
<script>
    const map = new mapboxgl.Map({
        container: 'map',
        style: '${basemap}',
        center: [${center.lng}, ${center.lat}],
        zoom: ${zoom}
    });

    carto.setDefaultConfig({
        serverURL: '${serverURL}'
    });

    carto.setDefaultAuth({
        username: '${username}',
        apiKey: '${apiKey}'
    });


    const source = ${source};
    const viz = new carto.Viz(\`
        ${vizSpec}
    \`);
    const layer = new carto.Layer('layer', source, viz);

    layer.addTo(map, 'watername_ocean');
</script>
</body>
</html>
`;
}
43560
def gen_scripts(
    file_name, file_name_ext, obj_name, obj_ext_name, output, output_ext,
    field=1, notexplicit=None, ascii_props=False, append=False, prefix=""
):
    """"""

    obj = {}
    obj2 = {}
    aliases = {}
    with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, 'PropertyValueAliases.txt'), 'r', 'utf-8') as uf:
        for line in uf:
            if line.startswith('sc ;'):
                values = line.split(';')
                aliases[format_name(values[1].strip())] = format_name(values[2].strip())

    with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, file_name_ext), 'r', 'utf-8') as uf:
        for line in uf:
            if not line.startswith('#'):
                data = line.split('#')[0].split(';')
                if len(data) < 2:
                    continue
                exts = [aliases[format_name(n)] for n in data[1].strip().split(' ')]
                span = create_span([int(i, 16) for i in data[0].strip().split('..')], is_bytes=ascii_props)
                for ext in exts:
                    if ext not in obj2:
                        obj2[ext] = []
                    if span is None:
                        continue

                    obj2[ext].extend(span)

    with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, file_name), 'r', 'utf-8') as uf:
        for line in uf:
            if not line.startswith('#'):
                data = line.split('#')[0].split(';')
                if len(data) < 2:
                    continue
                span = create_span([int(i, 16) for i in data[0].strip().split('..')], is_bytes=ascii_props)
                name = format_name(data[1])
                if name not in obj:
                    obj[name] = []
                if name not in obj2:
                    obj2[name] = []

                if span is None:
                    continue

                obj[name].extend(span)
                obj2[name].extend(span)

    for name in list(obj.keys()):
        s = set(obj[name])
        obj[name] = sorted(s)

    for name in list(obj2.keys()):
        s = set(obj2[name])
        obj2[name] = sorted(s)

    if notexplicit:
        not_explicitly_defined(obj, notexplicit, is_bytes=ascii_props)
        not_explicitly_defined(obj2, notexplicit, is_bytes=ascii_props)

    # Convert characters values to ranges
    char2range(obj, is_bytes=ascii_props)
    char2range(obj2, is_bytes=ascii_props)

    with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
        if not append:
            f.write(HEADER)
        # Write out the Unicode properties
        f.write('%s_%s = {\n' % (prefix, obj_name))
        count = len(obj) - 1
        i = 0
        for k1, v1 in sorted(obj.items()):
            f.write('    "%s": "%s"' % (k1, v1))
            if i == count:
                f.write('\n}\n')
            else:
                f.write(',\n')
            i += 1

    with codecs.open(output_ext, 'a' if append else 'w', 'utf-8') as f:
        if not append:
            f.write(HEADER)
        # Write out the Unicode properties
        f.write('%s_%s = {\n' % (prefix, obj_ext_name))
        count = len(obj2) - 1
        i = 0
        for k1, v1 in sorted(obj2.items()):
            f.write('    "%s": "%s"' % (k1, v1))
            if i == count:
                f.write('\n}\n')
            else:
                f.write(',\n')
            i += 1
637659
def generate(self, more_content=None, all_members=False):
        # type: (Any, str, bool, bool) -> None
        
        directive = getattr(self, 'directivetype', self.objtype)

        # parse components out of name
        (file, _, namepath) = self.name.rpartition(':')
        (contract_name, _, fullname) = namepath.partition('.')
        (name, _, paramtypes) = fullname.partition('(')

        # normalize components
        name = name.strip() or None

        if directive in ('contract', 'interface', 'library') and name is None:
            name = contract_name
            contract_name = None

        paramtypes = ','.join(ptype.strip() for ptype in paramtypes.split(','))
        paramtypes = re.sub(r'\s+', ' ', paramtypes)
        if paramtypes.endswith(')'):
            paramtypes = paramtypes[:-1]

        # build query
        expressions = [
            SolidityObject.objtype == directive,
            SolidityObject.name == name,
        ]

        if file:
            expressions.append(SolidityObject.file == file)
        if contract_name:
            expressions.append(SolidityObject.contract_name == contract_name)
        if paramtypes:
            expressions.append(SolidityObject.paramtypes == paramtypes)

        # get associated object
        query = SolidityObject.select().where(*expressions)
        sol_objects = tuple(query)
        if len(sol_objects) == 0:
            logger.warning('{} {} could not be found via query:\n{}'.format(
                directive, self.name, ',\n'.join(
                    '  ' + str(expr.lhs.column_name) +
                    str(expr.op) + ('' if expr.rhs is None else expr.rhs)
                    for expr in expressions
                )))
            return
        elif len(sol_objects) > 1:
            logger.warning('multiple candidates for {} {} found:\n{}'.format(
                directive, self.name,
                '\n'.join('  ' + obj.signature for obj in sol_objects)))

        self.object = sol_objects[0]

        # begin rendering output
        sourcename = self.get_sourcename()

        # make sure that the result starts with an empty line.  This is
        # necessary for some situations where another directive preprocesses
        # reST and no starting newline is present
        self.add_line('', sourcename)

        # generate the directive header and options, if applicable
        self.add_directive_header()

        # make sure content is indented
        # TODO: consider adding a source unit directive
        self.indent += self.content_indent

        # add all content (from docstrings, attribute docs etc.)
        self.add_content(more_content)

        # document members, if possible
        if directive in ('contract', 'interface', 'library'):
            self.add_line('', sourcename)
            self.document_members(all_members)
430684
def generate_input_template(tool):
    # type: (Process) -> Dict[Text, Any]
    """"""
    template = yaml.comments.CommentedMap()
    for inp in realize_input_schema(tool.tool["inputs"], tool.schemaDefs):
        name = shortname(inp["id"])
        value, comment = generate_example_input(
            inp['type'], inp.get('default', None))
        template.insert(0, name, value, comment)
    return template
1329803
def gen_text(env: TextIOBase, package: str, tmpl: str):
    """"""
    if env:
        env_args = json_datetime.load(env)
    else:
        env_args = {}
    jinja_env = template.setup(package)
    echo(jinja_env.get_template(tmpl).render(**env_args))
657095
function generatedJsFiles(what) {
        var ret = [];
        if ((!what || what === 'templates') && cog.getOption('template')) {
            ret.push({src: null, dst: cog.getOption('template')});
        }
        if (cog.getOption('compile_typescript')) {
            var src = srcTypescriptFiles();
            for (var i = 0; i < src.length; i++) {
                if (src[i].src.substr(-3) === '.ts') {
                    src[i].dst = src[i].src.substr(0, src[i].src.length - 3) + '.js';
                    ret.push(src[i]);
                }
            }
        }
        return ret;
    }
335982
def oftype(self, typ):
        ''''''
        for key, val in self.items():
            if val.type == typ:
                yield key
132294
def synthesize(self, modules, use_string, x64, native):
        """"""
        # code_opts = CodeOpts(
        #     str.lower, None if use_string else hash_func,
        #     'reloc_delta', '->',
        #     True)
        # gen_opts = GenOpts('defs', transformed)
        print(hash_func)
        groups = group_by(modules, ends_with_punctuation)
        sources = self.make_source(groups, self.database)
        if sources:
            return stylify_files(
                {'defs.h': sources[0], 'init.c': sources[1]}
            )
        else:
            return ''
422104
def machine_listings_to_file_entries(listings: Iterable[dict]) -> \
        Iterable[FileEntry]:
    ''''''
    for listing in listings:
        yield FileEntry(
            listing['name'],
            type=listing.get('type'),
            size=listing.get('size'),
            date=listing.get('modify')
        )
1061229
function generate(file, template, context, minifyResult) {
  let string = template.render(context, {
    'styles.css': templates.styles,
    'embed.js': templates.embedJs
  });
  if (minifyResult) {
    string = minify(string, {
      caseSensitive: true,
      collapseWhitespace: true,
      html5: true,
      minifyCSS: true,
      minifyJS: true,
      removeComments: true,
      removeAttributeQuotes: true
    });
  };
  writeFile(path.join(context.config.destRoot, file), string);
}
239473
def generate_term(self, **kwargs):
        """"""
        term_map = kwargs.pop('term_map')
        if hasattr(term_map, "termType") and\
            term_map.termType == NS_MGR.rr.BlankNode.rdflib:
            return rdflib.BNode()
        if not hasattr(term_map, 'datatype'):
            term_map.datatype = NS_MGR.xsd.anyURI.rdflib
        if hasattr(term_map, "template") and term_map.template is not None:
            template_vars = kwargs
            template_vars.update(self.constants)
            # Call any functions to generate values
            for key, value in template_vars.items():
                if hasattr(value, "__call__"):
                    template_vars[key] = value()
            raw_value = term_map.template.format(**template_vars)
            if term_map.datatype == NS_MGR.xsd.anyURI.rdflib:
                return rdflib.URIRef(raw_value)
            return rdflib.Literal(raw_value,
                                  datatype=term_map.datatype)
        if term_map.reference is not None:
            # Each child will have different mechanisms for referencing the
            # source based
            return self.__generate_reference__(term_map, **kwargs)
843891
def gen(name, data):
        """"""
        return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join(
            '%s:%s' % (attr, value) for attr, value in data.items()))
408707
function generateJS( data ) {
			var preparedData = prepareValues( data );
			var content = JSON.stringify( preparedData, null, options.indention );

			var output = outputPattern.js.replace( "{{name}}", options.name ).replace( "{{vars}}", content );
			return options.singlequote ? output.replace( /"/g, "'" ) : output;
		}