A Helper to materialize primitive data types
1454
public void materializeHelper(Materializer maker) throws IOException {
    if (!materialized) {
      ReaderWriterProfiler.start(ReaderWriterProfiler.Counter.DECODING_TIME);
      try {
        maker.materialize(treeReader, currentRow);
        materialized = true;
        writableCreated = false;
        nextIsNull = false;
        nextIsNullSet = true;
      }
      catch (ValueNotPresentException e) {
        // Is the value null?
        //
        materialized = true;
        writableCreated = true; // We have effectively created a writable
        nextIsNull = true;
        nextIsNullSet = true;
        throw new IOException("Cannot materialize primitive: value not present");
      }
      ReaderWriterProfiler.end(ReaderWriterProfiler.Counter.DECODING_TIME);
    }
    else if (nextIsNull) {
      throw new IOException("Cannot materialize primitive: value not present.");
    }
  }
333007
def get_input_shape(sym, proto_obj):
    """"""
    arg_params = proto_obj.arg_dict
    aux_params = proto_obj.aux_dict

    model_input_shape = [data[1] for data  in proto_obj.model_metadata.get('input_tensor_data')]
    data_names = [data[0] for data  in proto_obj.model_metadata.get('input_tensor_data')]

    # creating dummy inputs
    inputs = []
    for  in_shape in model_input_shape:
        inputs.append(nd.ones(shape=in_shape))

    data_shapes = []
    for idx, input_name in enumerate(data_names):
        data_shapes.append((input_name, inputs[idx].shape))

    ctx = context.cpu()
    # create a module
    mod = module.Module(symbol=sym, data_names=data_names, context=ctx, label_names=None)
    mod.bind(for_training=False, data_shapes=data_shapes, label_shapes=None)
    mod.set_params(arg_params=arg_params, aux_params=aux_params)

    data_forward = []
    for idx, input_name in enumerate(data_names):
        val = inputs[idx]
        data_forward.append(val)

    mod.forward(io.DataBatch(data_forward))
    result = mod.get_outputs()[0].asnumpy()

    return result.shape
194610
private static Class<?>[] convertArgumentTypesToPrimitive(Class<?>[] paramTypes, Object[] arguments) {
        Class<?>[] types = new Class<?>[arguments.length];
        for (int i = 0; i < arguments.length; i++) {
            Class<?> argumentType = null;
            if (arguments[i] == null) {
                argumentType = paramTypes[i];
            } else {
                argumentType = getType(arguments[i]);
            }
            Class<?> primitiveWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(argumentType);
            if (primitiveWrapperType == null) {
                types[i] = argumentType;
            } else {
                types[i] = primitiveWrapperType;
            }
        }
        return types;
    }
210082
def _consolidate(data_type):
    
    if isinstance(data_type, _ATOMIC):
        out = data_type
    elif isinstance(data_type, Array):
        element_type = _consolidate(data_type.element_type)
        out = data_type._replace(element_type=element_type)
    elif isinstance(data_type, Structure):
        fields = tuple(
            Field(*(_consolidate(field[i]) if i == _FIELD_TYPE_IDX
                    else field[i]
                    for i in _range(len(field))))
            for field in data_type.fields)
        out = data_type._replace(fields=fields)

    return out
450405
def primitives():
    
    z = randomZ(orderG1())

    # G1 operations
    P,Q = randomG1(),randomG1()
    R = generatorG1()
    g1Add = P + Q
    g1ScalarMultiply = z*P
    g1GeneratorMultiply = z*R
    g1Hash = hashG1(hash_in)

    # G2 operations
    P,Q = randomG2(),randomG2()
    R = generatorG2()
    g2Add = P + Q
    g2ScalarMultiply = z*P
    g2GeneratorMultiply = z*R
    g2hash = hashG2(hash_in)

    # Gt operations
    P = randomGt()
    Q = randomGt()
    gtMult = P * Q
    gtExp = P**z

    # Pairing
    x,y = (randomG1(), randomG2())
    R = pair(x,y)
297507
function encodeArray_Primitive( encoder, data ) {

	// Analyze primitive array and return clusters of values
	// that can be efficiently merged (such as numbers, repeated values,
	// primitives etc.)
	var chunks = analyzePrimitiveArray( encoder, data );
	if (chunks.length === 1) {

		// Just check
		if (chunks[0][1] !== data.length) {
			throw new Errors.AssertError('Primitive array analysis reported single chunk but does not match array length!');
		}

		// Just encode a single chunk as array component
		encodeArray_Chunk( encoder, data, chunks[0] );

	} else {

		// We have more than one chunk, start encoding chunked array
		encodeArray_PRIM_CHUNK( encoder, data, chunks );

	}

}
1144336
def native_types(code):
    """"""
    out = []
    for c in code:
        if isconstant(c, quoted=True):
            if isstring(c, quoted=True):
                v = c[1:-1]
            elif isbool(c):
                v = to_bool(c)
            elif isnumber(c):
                v = c
            else:
                raise CompileError("Unknown type %s: %s" % (type(c).__name__, c))

            # Instead of pushing constants in the code, we always push callable
            # Python functions, for fast dispatching:
            out.append(make_embedded_push(v))
        else:
            try:
                out.append(instructions.lookup(c))
            except KeyError:
                raise CompileError("Unknown word '%s'" % c)
    return out
1236333
def return_primitive(fn):
    
    @wraps(fn)
    def wrapped_fn(x):
        if isinstance(x, PRIMITIVE_TYPES):
            return x
        return fn(x)
    return wrapped_fn
1234744
def primitive(self, primitive):
        """"""
        self.entry_number = primitive['entry-number']
        self.item_hash = primitive['item-hash']
        self.timestamp = primitive['timestamp']
1131944
function (type, definitions) {
      var isPrimitive, listType;

      if (type instanceof Array) {
        listType = true;
        type = type[0];
      }

      // Convert undefined to string of 'undefined'
      if (typeof type === 'undefined') {
        type = 'undefined';
        isPrimitive = true;

      } else if (definitions[type]){
        // a model def exists?
        type = definitions[type]; /* Model */
        isPrimitive = false;

      } else if (getInlineModel(type)) {
        type = getInlineModel(type); /* Model */
        isPrimitive = false;

      } else {
        // We default to primitive
        isPrimitive = true;
      }

      if (isPrimitive) {
        if (listType) {
          return 'Array[' + type + ']';
        } else {
          return type.toString();
        }
      } else {
        if (listType) {
          return 'Array[' + getModelSignature(type.name, type.definition, type.models, type.modelPropertyMacro) + ']';
        } else {
          return getModelSignature(type.name, type.definition, type.models, type.modelPropertyMacro);
        }
      }
  }
255721
function handlePrimitive (primitive, gltf, ctx) {
  let geometryProps = {}

  // Format attributes for pex-context
  const attributes = Object.keys(primitive.attributes).reduce((attributes, name) => {
    const attributeName = PEX_ATTRIBUTE_NAME_MAP[name]
    if (!attributeName) console.warn(`glTF Loader: Unknown attribute '${name}'`)

    const accessor = getAccessor(gltf.accessors[primitive.attributes[name]], gltf.bufferViews)

    if (accessor.sparse) {
      attributes[attributeName] = accessor._data
    } else {
      if (!accessor._bufferView._vertexBuffer) {
        accessor._bufferView._vertexBuffer = ctx.vertexBuffer(accessor._bufferView._data)
      }
      attributes[attributeName] = {
        buffer: accessor._bufferView._vertexBuffer,
        offset: accessor.byteOffset,
        type: accessor.componentType,
        stride: accessor._bufferView.byteStride
      }
    }

    return attributes
  }, {})

  const positionAccessor = gltf.accessors[primitive.attributes.POSITION]
  const indicesAccessor = gltf.accessors[primitive.indices] && getAccessor(gltf.accessors[primitive.indices], gltf.bufferViews)

  // Create geometry
  geometryProps = {
    ...geometryProps,
    ...attributes,
    bounds: [positionAccessor.min, positionAccessor.max]
  }

  if (indicesAccessor) {
    if (!indicesAccessor._bufferView._indexBuffer) {
      indicesAccessor._bufferView._indexBuffer = ctx.indexBuffer(indicesAccessor._bufferView._data)
    }
    geometryProps = {
      ...geometryProps,
      indices: {
        buffer: indicesAccessor._bufferView._indexBuffer,
        offset: indicesAccessor.byteOffset,
        type: indicesAccessor.componentType,
        count: indicesAccessor.count
      }
    }
  } else {
    geometryProps = {
      ...geometryProps,
      count: positionAccessor._data.length / 3
    }
  }

  // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#primitivemode
  if (primitive.mode) {
    geometryProps = {
      ...geometryProps,
      primitive: primitive.mode
    }
  }

  return geometryProps
}
1373312
def primitive_type(attr)
      case
      when serialized_properties.include?(attr)
        serialized_properties[attr]
      when magic_typecast_properties.include?(attr)
        magic_typecast_properties[attr]
      else
        fetch_upstream_primitive(attr)
      end
    end
296568
def generate_value_processor(type_, collectionFormat=None, items=None, **kwargs):
    
    processors = []
    if is_non_string_iterable(type_):
        assert False, "This should not be possible"
    else:
        if type_ == ARRAY and collectionFormat:
            if collectionFormat in DELIMETERS:
                delimeter = DELIMETERS[collectionFormat]
                # split the string based on the delimeter specified by the
                # `collectionFormat`
                processors.append(operator.methodcaller('split', delimeter))
            else:
                if collectionFormat != MULTI:
                    raise TypeError("collectionFormat not implemented")
                processors.append(add_string_into_list)
            # remove any Falsy values like empty strings.
            processors.append(functools.partial(filter, bool))
            # strip off any whitespace
            processors.append(functools.partial(map, operator.methodcaller('strip')))
            if items is not None:
                if isinstance(items, collections.Mapping):
                    items_processors = itertools.repeat(
                        generate_value_processor(**items)
                    )
                elif isinstance(items, collections.Sequence):
                    items_processors = itertools.chain(
                        (generate_value_processor(**item) for item in items),
                        itertools.repeat(lambda v: v),
                    )
                elif isinstance(items, six.string_types):
                    raise NotImplementedError("Not implemented")
                else:
                    assert False, "Should not be possible"
                # 1. zip the processor and the array items together
                # 2. apply the processor to each array item.
                # 3. cast the starmap generator to a list.
                processors.append(
                    chain_reduce_partial(
                        functools.partial(zip, items_processors),
                        functools.partial(itertools.starmap, lambda fn, v: fn(v)),
                        list,
                    )
                )
        else:
            processors.append(
                functools.partial(cast_value_to_type, type_=type_)
            )

    def processor(value, **kwargs):
        try:
            return chain_reduce_partial(*processors)(value)
        except (ValueError, TypeError):
            return value

    return processor
899727
private DataSet<Vertex<K, VV>> createResultSimpleVertex(EdgeDirection messagingDirection,
		TypeInformation<Tuple2<K, Message>> messageTypeInfo, DataSet<LongValue> numberOfVertices) {

		DataSet<Tuple2<K, Message>> messages;

		TypeInformation<Vertex<K, VV>> vertexTypes = initialVertices.getType();

		final DeltaIteration<Vertex<K, VV>, Vertex<K, VV>> iteration =
				initialVertices.iterateDelta(initialVertices, this.maximumNumberOfIterations, 0);
				setUpIteration(iteration);

		switch (messagingDirection) {
			case IN:
				messages = buildScatterFunction(iteration, messageTypeInfo, 1, 0, numberOfVertices);
				break;
			case OUT:
				messages = buildScatterFunction(iteration, messageTypeInfo, 0, 0, numberOfVertices);
				break;
			case ALL:
				messages = buildScatterFunction(iteration, messageTypeInfo, 1, 0, numberOfVertices)
						.union(buildScatterFunction(iteration, messageTypeInfo, 0, 0, numberOfVertices));
				break;
			default:
				throw new IllegalArgumentException("Illegal edge direction");
		}

		GatherUdf<K, VV, Message> updateUdf = new GatherUdfSimpleVV<>(gatherFunction, vertexTypes);

		// build the update function (co group)
		CoGroupOperator<?, ?, Vertex<K, VV>> updates =
				messages.coGroup(iteration.getSolutionSet()).where(0).equalTo(0).with(updateUdf);

		if (this.configuration != null && this.configuration.isOptNumVertices()) {
			updates = updates.withBroadcastSet(numberOfVertices, "number of vertices");
		}

		configureUpdateFunction(updates);

		return iteration.closeWith(updates, updates);
	}
45163
function objectForKey(object, key, primitives){
  var proto = primitives.getPrototypeOf(object)
  if (!proto || hasOwnProperty(object, key)){
    return object
  } else {
    return objectForKey(proto, key, primitives)
  }
}
502446
function encodeArray( encoder, data ) {
	encoder.log(LOG.PRM, "array, len="+data.length+", peek="+data[0]);
	
	// Check for empty array
	if (data.length === 0) {
		encodeArray_EMPTY( encoder );
		return;
	}

	// Get typed array typed
	var tt = getTypedArrayType(data);

	// Check for numerical array
	if ( tt <= NUMTYPE.NUMERIC ) {
		encodeArray_Numeric( encoder, data, tt );
	} else {
		encodeArray_Primitive( encoder, data );
	}

}
259996
function parseImports(ast, compiler) {
  const imports = {};
  let hasMemory = false;

  compiler.walkNode({
    Import(node, _) {
      // Import nodes consist of field and a string literal node
      const [fields, module] = node.params;
      if (imports[module.value] == null) {
        imports[module.value] = [];
      }

      compiler.walkNode({
        Pair(pair, __) {
          // Import pairs consist of identifier and type
          const [identifier, type] = pair.params;
          imports[module.value] = Array.from(
            new Set(imports[module.value].concat(identifier.value))
          );

          if (type.value === "Memory") {
            hasMemory = true;
          }
        },
      })(fields);
    },
  })(ast);

  return [imports, hasMemory];
}