Substitute template arguments in in_file from variables in d, write the
    result to out_fobj.
324390
def template_subs_file(in_file, out_fobj, d):
    
    with open(in_file, 'r') as in_fobj:
        for line in in_fobj:
            out_fobj.write(line.format(**d))
36893
def templates_in(path):
    """"""
    ext = '.cpp'
    return (
        Template(f[0:-len(ext)], load_file(os.path.join(path, f)))
        for f in os.listdir(path) if f.endswith(ext)
    )
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
434720
def _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir):
    
    with open(argfile, "w") as out_handle:
        if argfile.endswith(".json"):
            record_name, record_attrs = _get_record_attrs(out_keys)
            if record_name:
                if parallel in ["multi-batch"]:
                    recs = _nested_cwl_record(out, record_attrs, input_files)
                elif parallel in ["single-split", "multi-combined", "multi-parallel", "batch-single",
                                  "single-single"]:
                    recs = [_collapse_to_cwl_record_single(utils.to_single_data(xs), record_attrs, input_files)
                            for xs in out]
                else:
                    samples = [utils.to_single_data(xs) for xs in out]
                    recs = [_collapse_to_cwl_record(samples, record_attrs, input_files)]
                json.dump(_combine_cwl_records(recs, record_name, parallel),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
            elif parallel in ["single-split", "multi-combined", "batch-split"]:
                json.dump(_convert_to_cwl_json([utils.to_single_data(xs) for xs in out], fnargs, input_files),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
            else:
                json.dump(_convert_to_cwl_json(utils.to_single_data(utils.to_single_data(out)), fnargs, input_files),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
        else:
            yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
949934
def copy_templates(entry_point, py_entry_point, auto_write, output_dir):
    '''
    '''

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    scripts = []
    for f in os.listdir(bin_path()):
        ext = os.path.splitext(f)[-1]
        newline = NEWLINE_MAP.get(ext, '\n')
        template = bin_path(f)
        destination = output_dir + '/' + entry_point + ext
        scripts.append(destination)

        with io.open(template, 'r') as f:
            code = f.read()
        code = code.replace('{{entry_point}}', entry_point)
        code = code.replace('{{py_entry_point}}', py_entry_point)
        code = code.replace('{{auto_write}}', str(int(auto_write)))

        with io.open(destination, 'w', newline=newline) as f:
            f.write(code)

    return scripts
1352279
def out_filename(template, n_val, mode):
    """"""
    return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
201420
function substitute(str, variables) {

        // Based on Simple JavaScript Templating by
        // John Resig - http://ejohn.org/blog/javascript-micro-templating/ - MIT Licensed
        if (!cache[str]) {
            // Figure out if we're getting a template, or if we need to
            // load the template - and be sure to cache the result.
            try {
                /*jshint -W054 */
                cache[str] =  new Function("obj",
                    "var p=[],print=function(){p.push.apply(p,arguments);};" +

                    // Introduce the data as local variables using with(){}
                    "with(obj){p.push('" +

                    // Convert the template into pure JavaScript
                    str.replace(/[\r\t\n]/g, " ")
                    .split("<%").join("\t")
                    .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                    .replace(/\t=(.*?)%>/g, "',$1,'")
                    .split("\t").join("');")
                    .split("%>").join("p.push('")
                    .split("\r").join("\\'") +
                    "');}return p.join('');");
                /*jshint +W054 */
            } catch(e) {
                grunt.fail.fatal("Failed to compile template:\n" + str);
            }
        }

        return cache[str](variables || {});
    }
1353555
def sub_template(template,template_tag,substitution):
    '''
    '''
    template = template.replace(template_tag,substitution)
    return template
23898
def _replace(variables, match):
    
    expression = match.group(1)

    # Look-up chars and functions for the specified operator
    (prefix_char, separator_char, split_fn, escape_fn,
     format_fn) = operator_map.get(expression[0], defaults)

    replacements = []
    for key, modify_fn, explode in split_fn(expression):
        if key in variables:
            variable = modify_fn(variables[key])
            replacement = format_fn(
                explode, separator_char, escape_fn, key, variable)
            replacements.append(replacement)
    if not replacements:
        return ''
    return prefix_char + separator_char.join(replacements)
648543
def expand(template, variables=None):
    
    if variables is None:
        variables = {}
    return patterns.sub(functools.partial(_replace, variables), template)
1115272
def substitute(self, values={}, functions={}):
        
        try:
            res = self.compiled(values, functions)
        except Exception:  # Handle any exceptions thrown by compiled version.
            res = self.interpret(values, functions)

        return res
1166401
def _par_write(self, dirname):
        
        filename = dirname + '/' + 'template_parameters.csv'
        with open(filename, 'w') as parfile:
            for template in self.templates:
                for key in template.__dict__.keys():
                    if key not in ['st', 'event']:
                        parfile.write(key + ': ' +
                                      str(template.__dict__[key]) + ', ')
                parfile.write('\n')
        return self
584260
def apply_command_list_template(command_list, in_path, out_path, args):
    '''
    
    '''
    replacements = {
        '$IN': in_path,
        '$OUT': out_path,
    }

    # Add in positional arguments ($0, $1, etc)
    for i, arg in enumerate(args):
        replacements['$' + str(i)] = arg

    results = [replacements.get(arg, arg) for arg in command_list]

    # Returns list of truthy replaced arguments in command
    return [item for item in results if item]
625630
def _py_outvar(parameter, lparams, tab):
    
    if ("out" in parameter.direction and parameter.D > 0 and ":" in parameter.dimension and
        ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)):
        lparams.append("byref({}_o)".format(parameter.lname))
        blank = True if parameter.direction == "(inout)" else False
        return ("{0}_o = POINTER({1})()".format(parameter.lname, _py_ctype(parameter)), blank)
1057318
protected String substituteParametersInTemplate(final FunctionTemplate template, final Map<String, String> params) {
        String ret = template.getFiles().get("function.java");
        for (final Map.Entry<String, String> entry : params.entrySet()) {
            ret = ret.replace(String.format("$%s$", entry.getKey()), entry.getValue());
        }
        return ret;
    }
1174513
function compileTemplate(file, replacements, templateFileLog) {
	file = File.find(path.resolve(file));
	let content = file.read();
	let tags = content.match(new RegExp(tplTagRegExpStr, 'g'));
	if (tags && tags.length) {
		content = getCompiledContent(
			file,
			content.split(new RegExp(tplTagRegExpStr)),
			tags,
			replacements,
			templateFileLog
		);
		file.write(content);
	}
}
1189631
function doSubstituteBuildVars(file, buildVars) {
        var contents = fs.readFileSync(file, FILE_ENCODING);
        contents = contents.replace(/%%build:([^%]+)%%/g, function(matched, buildVarName) {
            return buildVars[buildVarName];
        });

        // Now do replacements specified by build directives
        contents = contents.replace(/\/\*\s?build:replaceWith\((.*?)\)\s?\*\/.*?\*\s?build:replaceEnd\s?\*\//g, "$1");

        fs.writeFileSync(file, contents, FILE_ENCODING);
    }