Given a graphql`` tagged template literal, replace it with the appropriate
runtime artifact.
170527
function compileGraphQLTag(
  t: $FlowFixMe,
  path: Object,
  state: BabelState,
  ast: DocumentNode,
): void {
  if (ast.definitions.length !== 1) {
    throw new Error(
      'BabelPluginRelay: Expected exactly one definition per graphql tag.',
    );
  }
  const definition = ast.definitions[0];
  if (
    definition.kind !== 'FragmentDefinition' &&
    definition.kind !== 'OperationDefinition'
  ) {
    throw new Error(
      'BabelPluginRelay: Expected a fragment, mutation, query, or ' +
        'subscription, got `' +
        definition.kind +
        '`.',
    );
  }
  return replaceMemoized(t, path, createAST(t, state, path, definition));
}
480859
def _fix_tagging(value, params):
    

    _tag_type_to_explicit_implicit(params)

    retag = False
    if 'implicit' not in params:
        if value.implicit is not False:
            retag = True
    else:
        if isinstance(params['implicit'], tuple):
            class_, tag = params['implicit']
        else:
            tag = params['implicit']
            class_ = 'context'
        if value.implicit is False:
            retag = True
        elif value.class_ != CLASS_NAME_TO_NUM_MAP[class_] or value.tag != tag:
            retag = True

    if params.get('explicit') != value.explicit:
        retag = True

    if retag:
        return value.retag(params)
    return value
1117946
def _build_new_template(self, stack, parameters):
        
        log_lines = ["New template parameters:"]
        for param in sorted(parameters,
                            key=lambda param: param['ParameterKey']):
            log_lines.append("%s = %s" % (param['ParameterKey'],
                                          param['ParameterValue']))

        log_lines.append("\nNew template contents:")
        log_lines.append("".join(stack))
        return log_lines
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
476930
function tagReplace(original, tag, value) {
  var fullTag = `[[${  tag  }]]`;
  return original.split(fullTag).join(value ? value : '');
}
532426
def _get_template(querystring_key, mapping):
    """"""
    default = None
    try:
        template_and_keys = mapping.items()
    except AttributeError:
        template_and_keys = mapping
    for template, key in template_and_keys:
        if key is None:
            key = PAGE_LABEL
            default = template
        if key == querystring_key:
            return template
    return default
430316
function filterArgs(defaultArgs, opt) {
  opt = opt || {};
  const packValueToNonNull = value => (0, _assign2.default)({}, value, { type: new _graphql.GraphQLNonNull(value.type) });
  return (0, _entries2.default)(defaultArgs).filter(_ref => {
    var _ref2 = (0, _slicedToArray3.default)(_ref, 2);

    let arg = _ref2[0];
    let value = _ref2[1];

    if (opt.onlyId && arg !== 'id' && arg !== 'ids') return false;
    if (opt.id && (arg === 'id' || arg === 'ids')) return false;
    if (opt.plural && !value.onlyPlural && _pluralize2.default.plural(arg) === arg) return false;
    return true;
  }).map(_ref3 => {
    var _ref4 = (0, _slicedToArray3.default)(_ref3, 2);

    let arg = _ref4[0];
    let value = _ref4[1];

    let newValue = (0, _assign2.default)({}, value);
    if ((arg === 'id' || arg === 'ids') && opt.idRequired) newValue = packValueToNonNull(newValue);
    if (!opt.required && newValue.required && !newValue.context) newValue = packValueToNonNull(newValue);
    return [arg, newValue];
  }).reduce((args, _ref5) => {
    var _ref6 = (0, _slicedToArray3.default)(_ref5, 2);

    let arg = _ref6[0];
    let value = _ref6[1];

    return (0, _assign2.default)(args, { [arg]: value });
  }, {});
}
874627
def parse(cls, parser, token):
        
        # Process the template line.
        tag_name, args, kwargs = parse_token_kwargs(
            parser, token,
            allowed_kwargs=cls.allowed_kwargs,
            compile_args=False,  # Only overrule here, keep at render() phase.
            compile_kwargs=cls.compile_kwargs
        )

        # remove "for" keyword, so all other args can be resolved in render().
        if args[0] == 'for':
            args.pop(0)

        # And apply the compilation afterwards
        for i in range(len(args)):
            args[i] = parser.compile_filter(args[i])

        cls.validate_args(tag_name, *args, **kwargs)
        return cls(tag_name, *args, **kwargs)
994237
def __render_tag(info, state):
    
    new_contexts, context_match = get_tag_context(info['tag_key'], state)
    replacement = ''

    if context_match or context_match == 0:
        replacement = context_match
    elif info['tag_key'] == '.':
        replacement = state.context()
    else:
        replacement = ''

    # Call all callables / methods / lambdas / functions
    if replacement and callable(replacement):
        replacement = make_unicode(replacement())

        state.push_tags(state.default_tags)
        replacement = __render(template=replacement, state=state)
        state.pop_tags()

    for i in xrange(new_contexts): state.context.pop()

    if state.escape():
        return html_escape(replacement)
    return replacement
555321
private Template parseFix(Document dc, String tagname) {
        Template fix;
        NodeList prefixElementList = dc.getElementsByTagNameNS(SCHEMA_LOCATION, tagname);
        if (prefixElementList.getLength() > 0) {
            fix = parseTemplate(prefixElementList.item(0));
        } else {
            fix = new Template();
        }
        return fix;
    }
102188
@Override
  public Fix replace(ExpressionTemplateMatch match) {
    Inliner inliner = match.createInliner();
    Context context = inliner.getContext();
    if (annotations().containsKey(UseImportPolicy.class)) {
      ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value());
    } else {
      ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
    }
    int prec = getPrecedence(match.getLocation(), context);
    SuggestedFix.Builder fix = SuggestedFix.builder();
    try {
      StringWriter writer = new StringWriter();
      pretty(inliner.getContext(), writer).printExpr(expression().inline(inliner), prec);
      fix.replace(match.getLocation(), writer.toString());
    } catch (CouldNotResolveImportException e) {
      logger.log(SEVERE, "Failure to resolve in replacement", e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return addImports(inliner, fix);
  }
1174053
def templated(template=None, *templates):
    

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            template_ = template
            if template_ is None:
                template_ = request.endpoint.split('.', 1)[1].replace(
                    '.', '/') + '.html'
            context = func(*args, **kwargs)
            if context is None:
                context = {}
            elif not isinstance(context, dict):
                return context
            return custom_render_template(
                list(chain(to_list(template_), templates)), **context)

        return wrapper

    return decorator
399992
def _cached_replace_compile(pattern, repl, flags, pattern_type):
    """"""

    return _bregex_parse._ReplaceParser().parse(pattern, repl, bool(flags & FORMAT))
1130935
def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
    

    def wrapper(func):
        @functools.wraps(func)
        async def wrapped(*args, **kwargs):
            if asyncio.iscoroutinefunction(func):
                coro = func
            else:
                coro = asyncio.coroutine(func)
            context = await coro(*args, **kwargs)
            if isinstance(context, web.StreamResponse):
                return context

            if 'request' in kwargs:
                request = kwargs['request']
            elif not args:
                request = None
                warnings.warn("Request not detected")
            elif isinstance(args[0], AbstractView):
                request = args[0].request
            else:
                request = args[-1]

            response = render_template(template_name, request, context,
                                       app_key=app_key, encoding=encoding)
            response.set_status(status)
            return response
        return wrapped
    return wrapper
555757
def _normalize_stack(graphobjs):
    """"""
    for operands, operator in graphobjs:
        operator = str(operator)
        if re.match(r'Q*q+$', operator):  # Zero or more Q, one or more q
            for char in operator:  # Split into individual
                yield ([], char)  # Yield individual
        else:
            yield (operands, operator)
387730
def template(basedir, text, vars, lookup_fatal=True, expand_lists=False):
    '''  '''

    try:
        text = text.decode('utf-8')
    except UnicodeEncodeError:
        pass # already unicode
    text = varReplace(basedir, unicode(text), vars, lookup_fatal=lookup_fatal, expand_lists=expand_lists)
    return text
338763
function inTemplateTag(line) {
                if (line <= 1) {
                    return false
                }
                const lineStartIndex = sourceCode.getIndexFromLoc({
                    line,
                    column: 0,
                })
                return microTemplateService.inTemplateTag(lineStartIndex - 1)
            }