Convert Filter/Traverse blocks and LocalField expressions within @fold to Gremlin objects.
349919
def _convert_folded_blocks(folded_ir_blocks):
    """"""
    new_folded_ir_blocks = []

    def folded_context_visitor(expression):
        """Transform LocalField objects into their Gremlin-specific counterpart."""
        if not isinstance(expression, LocalField):
            return expression

        return GremlinFoldedLocalField(expression.field_name)

    for block in folded_ir_blocks:
        new_block = block

        if isinstance(block, Filter):
            new_predicate = block.predicate.visit_and_update(folded_context_visitor)
            new_block = GremlinFoldedFilter(new_predicate)
        elif isinstance(block, Traverse):
            new_block = GremlinFoldedTraverse.from_traverse(block)
        elif isinstance(block, (MarkLocation, Backtrack)):
            # We remove MarkLocation and Backtrack blocks from the folded blocks output,
            # since they do not produce any Gremlin output code inside folds.
            continue
        else:
            raise AssertionError(u'Found an unexpected IR block in the folded IR blocks: '
                                 u'{} {} {}'.format(type(block), block, folded_ir_blocks))

        new_folded_ir_blocks.append(new_block)

    return new_folded_ir_blocks
1374230
function convertPlaceholders (value) {
      // Probably AST nodes.
      if (typeof value !== 'string') {
        return [value]
      }

      const items = value.split(placeholderRe)
      let placeholder = true
      return items.map((item) => {
        placeholder = !placeholder
        return placeholder ? expressions[item] : t.stringLiteral(item)
      })
    }
717932
def _process_filter_block(query_metadata_table, block):
    """"""
    # For a given Filter block with BinaryComposition predicate expression X,
    # let L be the set of all Locations referenced in any TernaryConditional
    # predicate expression enclosed in X.
    # For each location l in L, we construct a tautological expression that looks like:
    #     ((l IS NULL) OR (l IS NOT NULL))
    # and then join the original BinaryComposition X with all such expressions with ANDs.
    # We set this new BinaryComposition expression as the predicate of the Filter block.
    base_predicate = block.predicate

    # These variables are used by the visitor functions below.
    ternary_conditionals = []
    # "problematic_locations" is a list and not a set,
    # to preserve ordering and generate a deterministic order of added clauses.
    # We expect the maximum size of this list to be a small constant number,
    # so the linear "in" operator is really not a concern.
    problematic_locations = []

    def find_ternary_conditionals(expression):
        """Visitor function that extracts all enclosed TernaryConditional expressions."""
        if isinstance(expression, TernaryConditional):
            ternary_conditionals.append(expression)
        return expression

    def extract_locations_visitor(expression):
        """Visitor function that extracts all the problematic locations."""
        if isinstance(expression, (ContextField, ContextFieldExistence)):
            # We get the location at the vertex, ignoring property fields.
            # The vertex-level location is sufficient to work around the OrientDB bug,
            # and we want as few location as possible overall.
            location_at_vertex = expression.location.at_vertex()
            if location_at_vertex not in problematic_locations:
                problematic_locations.append(location_at_vertex)

        return expression

    # We aren't modifying the base predicate itself, just traversing it.
    # The returned "updated" value must be the exact same as the original.
    return_value = base_predicate.visit_and_update(find_ternary_conditionals)
    if return_value is not base_predicate:
        raise AssertionError(u'Read-only visitor function "find_ternary_conditionals" '
                             u'caused state to change: '
                             u'{} {}'.format(base_predicate, return_value))

    for ternary in ternary_conditionals:
        # We aren't modifying the ternary itself, just traversing it.
        # The returned "updated" value must be the exact same as the original.
        return_value = ternary.visit_and_update(extract_locations_visitor)
        if return_value is not ternary:
            raise AssertionError(u'Read-only visitor function "extract_locations_visitor" '
                                 u'caused state to change: '
                                 u'{} {}'.format(ternary, return_value))

    tautologies = [
        _create_tautological_expression_for_location(query_metadata_table, location)
        for location in problematic_locations
    ]

    if not tautologies:
        return block

    final_predicate = base_predicate
    for tautology in tautologies:
        final_predicate = BinaryComposition(u'&&', final_predicate, tautology)
    return Filter(final_predicate)
587461
def flat_map(include_self = false, &block)
      result = []

      each_expression(include_self) do |exp, index|
        if block_given?
          result << yield(exp, index)
        else
          result << [exp, index]
        end
      end

      result
    end
611676
def foldl(list, &block)
      return '' if list.empty?
      list[1..-1].inject(list.first, &block)
    end
368919
function denormalizeIterable(items, entities, schema, bag) {
  const isMappable = typeof items.map === 'function';

  const itemSchema = Array.isArray(schema) ? schema[0] : schema.schema;

  // Handle arrayOf iterables
  if (isMappable) {
    return items.map(o => denormalize(o, entities, itemSchema, bag));
  }

  // Handle valuesOf iterables
  const denormalized = {};
  Object.keys(items).forEach((key) => {
    denormalized[key] = denormalize(items[key], entities, itemSchema, bag);
  });
  return denormalized;
}
851734
def flatten_to_sql(*values)
      flatten_safely(values) do |value|
        value = yield value if block_given?
        to_arel_sql(value)
      end
    end
1116640
function getMutations(spec, attr) {
      var fns = compose(extraction, cleanup, stitch)(spec);
      return _.callmap(fns, attr);
    }
931980
def filtered_elements(self, model):
        """"""
        if isinstance(model, self.element_type):
            yield model
        yield from (e for e in model.eAllContents() if isinstance(e, self.element_type))
312889
def _represent_fold(fold_location, fold_ir_blocks):
    """"""
    start_let_template = u'$%(mark_name)s = %(base_location)s'
    traverse_edge_template = u'.%(direction)s("%(edge_name)s")'
    base_template = start_let_template + traverse_edge_template
    edge_direction, edge_name = fold_location.get_first_folded_edge()
    mark_name, _ = fold_location.get_location_name()
    base_location_name, _ = fold_location.base_location.get_location_name()

    validate_safe_string(mark_name)
    validate_safe_string(base_location_name)
    validate_safe_string(edge_direction)
    validate_safe_string(edge_name)

    template_data = {
        'mark_name': mark_name,
        'base_location': base_location_name,
        'direction': edge_direction,
        'edge_name': edge_name,
    }
    final_string = base_template % template_data

    for block in fold_ir_blocks:
        if isinstance(block, Filter):
            final_string += u'[' + block.predicate.to_match() + u']'
        elif isinstance(block, Traverse):
            template_data = {
                'direction': block.direction,
                'edge_name': block.edge_name,
            }
            final_string += traverse_edge_template % template_data
        elif isinstance(block, MarkLocation):
            # MarkLocation blocks inside a fold do not result in any MATCH output.
            pass
        else:
            raise AssertionError(u'Found an unexpected IR block in the folded IR blocks: '
                                 u'{} {} {}'.format(type(block), block, fold_ir_blocks))

    # Workaround for OrientDB's inconsistent return type when filtering a list.
    # https://github.com/orientechnologies/orientdb/issues/7811
    final_string += '.asList()'

    return final_string
619313
def to_gremlin(self):
        """"""
        self.validate()
        if self.optional:
            operation = u'optional'
        else:
            operation = u'back'

        mark_name, _ = self.location.get_location_name()

        return u'{operation}({mark_name})'.format(
            operation=operation,
            mark_name=safe_quoted_string(mark_name))
550610
def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
            SequenceTypes=SequenceTypes, do_flatten=do_flatten):
    
    if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
        return [obj]
    result = []
    for item in obj:
        if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
            result.append(item)
        else:
            do_flatten(item, result)
    return result
134757
static ModelNode filterSpecToFilter(final String value) {
        final ModelNode filter = new ModelNode(CommonAttributes.FILTER.getName()).setEmptyObject();
        final Iterator<String> iterator = tokens(value).iterator();
        parseFilterExpression(iterator, filter, true);
        return filter;
    }
1289954
def derived(self, locals=None):
        
        context = new_context(self.environment, self.name, {},
                              self.get_all(), True, None, locals)
        context.eval_ctx = self.eval_ctx
        context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))
        return context
350197
def to_gremlin(self):
        """"""
        self.validate()

        template = (
            u'transform{{'
            u'it, m -> new com.orientechnologies.orient.core.record.impl.ODocument([ {} ])'
            u'}}')

        field_representations = (
            u'{name}: {expr}'.format(name=key, expr=self.fields[key].to_gremlin())
            for key in sorted(self.fields.keys())  # Sort the keys for deterministic output order.
        )
        return template.format(u', '.join(field_representations))
650261
def to_mongo(self, disjunction=True):
        
        q = {}
        # add all the main clauses to `q`
        clauses = [e.expr for e in self._main]
        if clauses:
            if disjunction:
                if len(clauses) + len(self._where) > 1:
                    q['$or'] = clauses
                else:
                    # simplify 'or' of one thing
                    q.update(clauses[0])
            else:
                for c in clauses:
                    q.update(c)
        # add all the main2 clauses; these are not or'ed
        for c in (e.expr for e in self._main2):
            # add to existing stuff for the field
            for field in c:
                if field in q:
                    q[field].update(c[field])
                else:
                    q.update(c)
        # add where clauses, if any, to `q`
        if self._where:
            wsep = ' || ' if self._where[0].is_reversed else ' && '
            where_clause = wsep.join([w.expr for w in self._where])
            if disjunction:
                if not '$or' in q:
                    q['$or'] = []
                q['$or'].append({'$where': where_clause})
            else:
                q['$where'] = where_clause
        return q
175533
def _validate_fold_has_outputs_or_count_filter(fold_scope_location, fold_has_count_filter, outputs):
    """"""
    # This function makes sure that the @fold scope has an effect.
    # Folds either output data, or filter the data enclosing the fold based on the size of the fold.
    if fold_has_count_filter:
        # This fold has a filter on the "_x_count" property, so it is legal and has an effect.
        return True

    # At least one output in the outputs list must point to the fold_scope_location,
    # or the scope corresponding to fold_scope_location had no @outputs and is illegal.
    for output in six.itervalues(outputs):
        if output['fold'] == fold_scope_location:
            return True

    raise GraphQLCompilationError(u'Found a @fold scope that has no effect on the query. '
                                  u'Each @fold scope must either perform filtering, or contain at '
                                  u'least one field marked for output. Fold location: {}'
                                  .format(fold_scope_location))