id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28,800 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py | NeuralNetworkBuilder.add_load_constant | def add_load_constant(self, name, output_name, constant_value, shape):
"""
Add a load constant layer.
Parameters
----------
name: str
The name of this layer.
output_name: str
The output blob name of this layer.
constant_value: numpy.array
value of the constant as a numpy array.
shape: [int]
List of ints representing the shape of the constant. Must be of length 3: [C,H,W]
See Also
--------
add_elementwise
"""
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.loadConstant
data = spec_layer_params.data
data.floatValue.extend(map(float, constant_value.flatten()))
spec_layer_params.shape.extend(shape)
if len(data.floatValue) != np.prod(shape):
raise ValueError("Dimensions of 'shape' do not match the size of the provided constant")
if len(shape) != 3:
raise ValueError("'shape' must be of length 3") | python | def add_load_constant(self, name, output_name, constant_value, shape):
"""
Add a load constant layer.
Parameters
----------
name: str
The name of this layer.
output_name: str
The output blob name of this layer.
constant_value: numpy.array
value of the constant as a numpy array.
shape: [int]
List of ints representing the shape of the constant. Must be of length 3: [C,H,W]
See Also
--------
add_elementwise
"""
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.loadConstant
data = spec_layer_params.data
data.floatValue.extend(map(float, constant_value.flatten()))
spec_layer_params.shape.extend(shape)
if len(data.floatValue) != np.prod(shape):
raise ValueError("Dimensions of 'shape' do not match the size of the provided constant")
if len(shape) != 3:
raise ValueError("'shape' must be of length 3") | [
"def",
"add_load_constant",
"(",
"self",
",",
"name",
",",
"output_name",
",",
"constant_value",
",",
"shape",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"nn_spec",
"=",
"self",
".",
"nn_spec",
"# Add a new layer",
"spec_layer",
"=",
"nn_spec",
".",
"layers",
".",
"add",
"(",
")",
"spec_layer",
".",
"name",
"=",
"name",
"spec_layer",
".",
"output",
".",
"append",
"(",
"output_name",
")",
"spec_layer_params",
"=",
"spec_layer",
".",
"loadConstant",
"data",
"=",
"spec_layer_params",
".",
"data",
"data",
".",
"floatValue",
".",
"extend",
"(",
"map",
"(",
"float",
",",
"constant_value",
".",
"flatten",
"(",
")",
")",
")",
"spec_layer_params",
".",
"shape",
".",
"extend",
"(",
"shape",
")",
"if",
"len",
"(",
"data",
".",
"floatValue",
")",
"!=",
"np",
".",
"prod",
"(",
"shape",
")",
":",
"raise",
"ValueError",
"(",
"\"Dimensions of 'shape' do not match the size of the provided constant\"",
")",
"if",
"len",
"(",
"shape",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"'shape' must be of length 3\"",
")"
] | Add a load constant layer.
Parameters
----------
name: str
The name of this layer.
output_name: str
The output blob name of this layer.
constant_value: numpy.array
value of the constant as a numpy array.
shape: [int]
List of ints representing the shape of the constant. Must be of length 3: [C,H,W]
See Also
--------
add_elementwise | [
"Add",
"a",
"load",
"constant",
"layer",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py#L2411-L2452 |
28,801 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py | NeuralNetworkBuilder.add_custom | def add_custom(self, name, input_names, output_names, custom_proto_spec = None):
"""
Add a custom layer.
Parameters
----------
name: str
The name of this layer.
input_names: [str]
The input blob names to this layer.
output_names: [str]
The output blob names from this layer.
custom_proto_spec: CustomLayerParams
A protobuf CustomLayerParams message. This can also be left blank and filled in later.
"""
spec = self.spec
nn_spec = self.nn_spec
# custom layers require a newer specification version
from coremltools import _MINIMUM_CUSTOM_LAYER_SPEC_VERSION
spec.specificationVersion = max(spec.specificationVersion, _MINIMUM_CUSTOM_LAYER_SPEC_VERSION)
spec_layer = nn_spec.layers.add()
spec_layer.name = name
for inname in input_names:
spec_layer.input.append(inname)
for outname in output_names:
spec_layer.output.append(outname)
# Have to do it this way since I can't just assign custom in a layer
spec_layer.custom.MergeFromString(b'')
if custom_proto_spec:
spec_layer.custom.CopyFrom(custom_proto_spec) | python | def add_custom(self, name, input_names, output_names, custom_proto_spec = None):
"""
Add a custom layer.
Parameters
----------
name: str
The name of this layer.
input_names: [str]
The input blob names to this layer.
output_names: [str]
The output blob names from this layer.
custom_proto_spec: CustomLayerParams
A protobuf CustomLayerParams message. This can also be left blank and filled in later.
"""
spec = self.spec
nn_spec = self.nn_spec
# custom layers require a newer specification version
from coremltools import _MINIMUM_CUSTOM_LAYER_SPEC_VERSION
spec.specificationVersion = max(spec.specificationVersion, _MINIMUM_CUSTOM_LAYER_SPEC_VERSION)
spec_layer = nn_spec.layers.add()
spec_layer.name = name
for inname in input_names:
spec_layer.input.append(inname)
for outname in output_names:
spec_layer.output.append(outname)
# Have to do it this way since I can't just assign custom in a layer
spec_layer.custom.MergeFromString(b'')
if custom_proto_spec:
spec_layer.custom.CopyFrom(custom_proto_spec) | [
"def",
"add_custom",
"(",
"self",
",",
"name",
",",
"input_names",
",",
"output_names",
",",
"custom_proto_spec",
"=",
"None",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"nn_spec",
"=",
"self",
".",
"nn_spec",
"# custom layers require a newer specification version",
"from",
"coremltools",
"import",
"_MINIMUM_CUSTOM_LAYER_SPEC_VERSION",
"spec",
".",
"specificationVersion",
"=",
"max",
"(",
"spec",
".",
"specificationVersion",
",",
"_MINIMUM_CUSTOM_LAYER_SPEC_VERSION",
")",
"spec_layer",
"=",
"nn_spec",
".",
"layers",
".",
"add",
"(",
")",
"spec_layer",
".",
"name",
"=",
"name",
"for",
"inname",
"in",
"input_names",
":",
"spec_layer",
".",
"input",
".",
"append",
"(",
"inname",
")",
"for",
"outname",
"in",
"output_names",
":",
"spec_layer",
".",
"output",
".",
"append",
"(",
"outname",
")",
"# Have to do it this way since I can't just assign custom in a layer",
"spec_layer",
".",
"custom",
".",
"MergeFromString",
"(",
"b''",
")",
"if",
"custom_proto_spec",
":",
"spec_layer",
".",
"custom",
".",
"CopyFrom",
"(",
"custom_proto_spec",
")"
] | Add a custom layer.
Parameters
----------
name: str
The name of this layer.
input_names: [str]
The input blob names to this layer.
output_names: [str]
The output blob names from this layer.
custom_proto_spec: CustomLayerParams
A protobuf CustomLayerParams message. This can also be left blank and filled in later. | [
"Add",
"a",
"custom",
"layer",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py#L2455-L2491 |
28,802 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py | NeuralNetworkBuilder.set_pre_processing_parameters | def set_pre_processing_parameters(self, image_input_names = [], is_bgr = False,
red_bias = 0.0, green_bias = 0.0, blue_bias = 0.0, gray_bias = 0.0, image_scale = 1.0):
"""Add pre-processing parameters to the neural network object
Parameters
----------
image_input_names: [str]
Name of input blobs that are images
is_bgr: boolean | dict()
Channel order for input blobs that are images. BGR if True else RGB.
To specify a different value for each image input,
provide a dictionary with input names as keys.
red_bias: float | dict()
Image re-centering parameter (red channel)
blue_bias: float | dict()
Image re-centering parameter (blue channel)
green_bias: float | dict()
Image re-centering parameter (green channel)
gray_bias: float | dict()
Image re-centering parameter (for grayscale images)
image_scale: float | dict()
Value by which to scale the images.
See Also
--------
set_input, set_output, set_class_labels
"""
spec = self.spec
if not image_input_names:
return # nothing to do here
if not isinstance(is_bgr, dict): is_bgr = dict.fromkeys(image_input_names, is_bgr)
if not isinstance(red_bias, dict): red_bias = dict.fromkeys(image_input_names, red_bias)
if not isinstance(blue_bias, dict): blue_bias = dict.fromkeys(image_input_names, blue_bias)
if not isinstance(green_bias, dict): green_bias = dict.fromkeys(image_input_names, green_bias)
if not isinstance(gray_bias, dict): gray_bias = dict.fromkeys(image_input_names, gray_bias)
if not isinstance(image_scale, dict): image_scale = dict.fromkeys(image_input_names, image_scale)
# Add image inputs
for input_ in spec.description.input:
if input_.name in image_input_names:
if input_.type.WhichOneof('Type') == 'multiArrayType':
array_shape = tuple(input_.type.multiArrayType.shape)
channels, height, width = array_shape
if channels == 1:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('GRAYSCALE')
elif channels == 3:
if input_.name in is_bgr:
if is_bgr[input_.name]:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('BGR')
else:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('RGB')
else:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('RGB')
else:
raise ValueError("Channel Value %d not supported for image inputs" % channels)
input_.type.imageType.width = width
input_.type.imageType.height = height
preprocessing = self.nn_spec.preprocessing.add()
preprocessing.featureName = input_.name
scaler = preprocessing.scaler
if input_.name in image_scale:
scaler.channelScale = image_scale[input_.name]
else:
scaler.channelScale = 1.0
if input_.name in red_bias: scaler.redBias = red_bias[input_.name]
if input_.name in blue_bias: scaler.blueBias = blue_bias[input_.name]
if input_.name in green_bias: scaler.greenBias = green_bias[input_.name]
if input_.name in gray_bias: scaler.grayBias = gray_bias[input_.name] | python | def set_pre_processing_parameters(self, image_input_names = [], is_bgr = False,
red_bias = 0.0, green_bias = 0.0, blue_bias = 0.0, gray_bias = 0.0, image_scale = 1.0):
"""Add pre-processing parameters to the neural network object
Parameters
----------
image_input_names: [str]
Name of input blobs that are images
is_bgr: boolean | dict()
Channel order for input blobs that are images. BGR if True else RGB.
To specify a different value for each image input,
provide a dictionary with input names as keys.
red_bias: float | dict()
Image re-centering parameter (red channel)
blue_bias: float | dict()
Image re-centering parameter (blue channel)
green_bias: float | dict()
Image re-centering parameter (green channel)
gray_bias: float | dict()
Image re-centering parameter (for grayscale images)
image_scale: float | dict()
Value by which to scale the images.
See Also
--------
set_input, set_output, set_class_labels
"""
spec = self.spec
if not image_input_names:
return # nothing to do here
if not isinstance(is_bgr, dict): is_bgr = dict.fromkeys(image_input_names, is_bgr)
if not isinstance(red_bias, dict): red_bias = dict.fromkeys(image_input_names, red_bias)
if not isinstance(blue_bias, dict): blue_bias = dict.fromkeys(image_input_names, blue_bias)
if not isinstance(green_bias, dict): green_bias = dict.fromkeys(image_input_names, green_bias)
if not isinstance(gray_bias, dict): gray_bias = dict.fromkeys(image_input_names, gray_bias)
if not isinstance(image_scale, dict): image_scale = dict.fromkeys(image_input_names, image_scale)
# Add image inputs
for input_ in spec.description.input:
if input_.name in image_input_names:
if input_.type.WhichOneof('Type') == 'multiArrayType':
array_shape = tuple(input_.type.multiArrayType.shape)
channels, height, width = array_shape
if channels == 1:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('GRAYSCALE')
elif channels == 3:
if input_.name in is_bgr:
if is_bgr[input_.name]:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('BGR')
else:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('RGB')
else:
input_.type.imageType.colorSpace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('RGB')
else:
raise ValueError("Channel Value %d not supported for image inputs" % channels)
input_.type.imageType.width = width
input_.type.imageType.height = height
preprocessing = self.nn_spec.preprocessing.add()
preprocessing.featureName = input_.name
scaler = preprocessing.scaler
if input_.name in image_scale:
scaler.channelScale = image_scale[input_.name]
else:
scaler.channelScale = 1.0
if input_.name in red_bias: scaler.redBias = red_bias[input_.name]
if input_.name in blue_bias: scaler.blueBias = blue_bias[input_.name]
if input_.name in green_bias: scaler.greenBias = green_bias[input_.name]
if input_.name in gray_bias: scaler.grayBias = gray_bias[input_.name] | [
"def",
"set_pre_processing_parameters",
"(",
"self",
",",
"image_input_names",
"=",
"[",
"]",
",",
"is_bgr",
"=",
"False",
",",
"red_bias",
"=",
"0.0",
",",
"green_bias",
"=",
"0.0",
",",
"blue_bias",
"=",
"0.0",
",",
"gray_bias",
"=",
"0.0",
",",
"image_scale",
"=",
"1.0",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"if",
"not",
"image_input_names",
":",
"return",
"# nothing to do here",
"if",
"not",
"isinstance",
"(",
"is_bgr",
",",
"dict",
")",
":",
"is_bgr",
"=",
"dict",
".",
"fromkeys",
"(",
"image_input_names",
",",
"is_bgr",
")",
"if",
"not",
"isinstance",
"(",
"red_bias",
",",
"dict",
")",
":",
"red_bias",
"=",
"dict",
".",
"fromkeys",
"(",
"image_input_names",
",",
"red_bias",
")",
"if",
"not",
"isinstance",
"(",
"blue_bias",
",",
"dict",
")",
":",
"blue_bias",
"=",
"dict",
".",
"fromkeys",
"(",
"image_input_names",
",",
"blue_bias",
")",
"if",
"not",
"isinstance",
"(",
"green_bias",
",",
"dict",
")",
":",
"green_bias",
"=",
"dict",
".",
"fromkeys",
"(",
"image_input_names",
",",
"green_bias",
")",
"if",
"not",
"isinstance",
"(",
"gray_bias",
",",
"dict",
")",
":",
"gray_bias",
"=",
"dict",
".",
"fromkeys",
"(",
"image_input_names",
",",
"gray_bias",
")",
"if",
"not",
"isinstance",
"(",
"image_scale",
",",
"dict",
")",
":",
"image_scale",
"=",
"dict",
".",
"fromkeys",
"(",
"image_input_names",
",",
"image_scale",
")",
"# Add image inputs",
"for",
"input_",
"in",
"spec",
".",
"description",
".",
"input",
":",
"if",
"input_",
".",
"name",
"in",
"image_input_names",
":",
"if",
"input_",
".",
"type",
".",
"WhichOneof",
"(",
"'Type'",
")",
"==",
"'multiArrayType'",
":",
"array_shape",
"=",
"tuple",
"(",
"input_",
".",
"type",
".",
"multiArrayType",
".",
"shape",
")",
"channels",
",",
"height",
",",
"width",
"=",
"array_shape",
"if",
"channels",
"==",
"1",
":",
"input_",
".",
"type",
".",
"imageType",
".",
"colorSpace",
"=",
"_FeatureTypes_pb2",
".",
"ImageFeatureType",
".",
"ColorSpace",
".",
"Value",
"(",
"'GRAYSCALE'",
")",
"elif",
"channels",
"==",
"3",
":",
"if",
"input_",
".",
"name",
"in",
"is_bgr",
":",
"if",
"is_bgr",
"[",
"input_",
".",
"name",
"]",
":",
"input_",
".",
"type",
".",
"imageType",
".",
"colorSpace",
"=",
"_FeatureTypes_pb2",
".",
"ImageFeatureType",
".",
"ColorSpace",
".",
"Value",
"(",
"'BGR'",
")",
"else",
":",
"input_",
".",
"type",
".",
"imageType",
".",
"colorSpace",
"=",
"_FeatureTypes_pb2",
".",
"ImageFeatureType",
".",
"ColorSpace",
".",
"Value",
"(",
"'RGB'",
")",
"else",
":",
"input_",
".",
"type",
".",
"imageType",
".",
"colorSpace",
"=",
"_FeatureTypes_pb2",
".",
"ImageFeatureType",
".",
"ColorSpace",
".",
"Value",
"(",
"'RGB'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Channel Value %d not supported for image inputs\"",
"%",
"channels",
")",
"input_",
".",
"type",
".",
"imageType",
".",
"width",
"=",
"width",
"input_",
".",
"type",
".",
"imageType",
".",
"height",
"=",
"height",
"preprocessing",
"=",
"self",
".",
"nn_spec",
".",
"preprocessing",
".",
"add",
"(",
")",
"preprocessing",
".",
"featureName",
"=",
"input_",
".",
"name",
"scaler",
"=",
"preprocessing",
".",
"scaler",
"if",
"input_",
".",
"name",
"in",
"image_scale",
":",
"scaler",
".",
"channelScale",
"=",
"image_scale",
"[",
"input_",
".",
"name",
"]",
"else",
":",
"scaler",
".",
"channelScale",
"=",
"1.0",
"if",
"input_",
".",
"name",
"in",
"red_bias",
":",
"scaler",
".",
"redBias",
"=",
"red_bias",
"[",
"input_",
".",
"name",
"]",
"if",
"input_",
".",
"name",
"in",
"blue_bias",
":",
"scaler",
".",
"blueBias",
"=",
"blue_bias",
"[",
"input_",
".",
"name",
"]",
"if",
"input_",
".",
"name",
"in",
"green_bias",
":",
"scaler",
".",
"greenBias",
"=",
"green_bias",
"[",
"input_",
".",
"name",
"]",
"if",
"input_",
".",
"name",
"in",
"gray_bias",
":",
"scaler",
".",
"grayBias",
"=",
"gray_bias",
"[",
"input_",
".",
"name",
"]"
] | Add pre-processing parameters to the neural network object
Parameters
----------
image_input_names: [str]
Name of input blobs that are images
is_bgr: boolean | dict()
Channel order for input blobs that are images. BGR if True else RGB.
To specify a different value for each image input,
provide a dictionary with input names as keys.
red_bias: float | dict()
Image re-centering parameter (red channel)
blue_bias: float | dict()
Image re-centering parameter (blue channel)
green_bias: float | dict()
Image re-centering parameter (green channel)
gray_bias: float | dict()
Image re-centering parameter (for grayscale images)
image_scale: float | dict()
Value by which to scale the images.
See Also
--------
set_input, set_output, set_class_labels | [
"Add",
"pre",
"-",
"processing",
"parameters",
"to",
"the",
"neural",
"network",
"object"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py#L2494-L2570 |
28,803 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/scanner.py | get | def get(scanner_class, properties):
""" Returns an instance of previously registered scanner
with the specified properties.
"""
assert issubclass(scanner_class, Scanner)
assert is_iterable_typed(properties, basestring)
scanner_name = str(scanner_class)
if not registered(scanner_name):
raise BaseException ("attempt to get unregisted scanner: %s" % scanner_name)
relevant_properties = __scanners[scanner_name]
r = property.select(relevant_properties, properties)
scanner_id = scanner_name + '.' + '-'.join(r)
if scanner_id not in __scanner_cache:
__scanner_cache[scanner_id] = scanner_class(r)
return __scanner_cache[scanner_id] | python | def get(scanner_class, properties):
""" Returns an instance of previously registered scanner
with the specified properties.
"""
assert issubclass(scanner_class, Scanner)
assert is_iterable_typed(properties, basestring)
scanner_name = str(scanner_class)
if not registered(scanner_name):
raise BaseException ("attempt to get unregisted scanner: %s" % scanner_name)
relevant_properties = __scanners[scanner_name]
r = property.select(relevant_properties, properties)
scanner_id = scanner_name + '.' + '-'.join(r)
if scanner_id not in __scanner_cache:
__scanner_cache[scanner_id] = scanner_class(r)
return __scanner_cache[scanner_id] | [
"def",
"get",
"(",
"scanner_class",
",",
"properties",
")",
":",
"assert",
"issubclass",
"(",
"scanner_class",
",",
"Scanner",
")",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"basestring",
")",
"scanner_name",
"=",
"str",
"(",
"scanner_class",
")",
"if",
"not",
"registered",
"(",
"scanner_name",
")",
":",
"raise",
"BaseException",
"(",
"\"attempt to get unregisted scanner: %s\"",
"%",
"scanner_name",
")",
"relevant_properties",
"=",
"__scanners",
"[",
"scanner_name",
"]",
"r",
"=",
"property",
".",
"select",
"(",
"relevant_properties",
",",
"properties",
")",
"scanner_id",
"=",
"scanner_name",
"+",
"'.'",
"+",
"'-'",
".",
"join",
"(",
"r",
")",
"if",
"scanner_id",
"not",
"in",
"__scanner_cache",
":",
"__scanner_cache",
"[",
"scanner_id",
"]",
"=",
"scanner_class",
"(",
"r",
")",
"return",
"__scanner_cache",
"[",
"scanner_id",
"]"
] | Returns an instance of previously registered scanner
with the specified properties. | [
"Returns",
"an",
"instance",
"of",
"previously",
"registered",
"scanner",
"with",
"the",
"specified",
"properties",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/scanner.py#L68-L87 |
28,804 | apple/turicreate | src/unity/python/turicreate/util/_cloudpickle.py | CloudPickler._save_subimports | def _save_subimports(self, code, top_level_dependencies):
"""
Ensure de-pickler imports any package child-modules that
are needed by the function
"""
# check if any known dependency is an imported package
for x in top_level_dependencies:
if isinstance(x, types.ModuleType) and hasattr(x, '__package__') and x.__package__:
# check if the package has any currently loaded sub-imports
prefix = x.__name__ + '.'
for name, module in sys.modules.items():
# Older versions of pytest will add a "None" module to sys.modules.
if name is not None and name.startswith(prefix):
# check whether the function can address the sub-module
tokens = set(name[len(prefix):].split('.'))
if not tokens - set(code.co_names):
# ensure unpickler executes this import
self.save(module)
# then discards the reference to it
self.write(pickle.POP) | python | def _save_subimports(self, code, top_level_dependencies):
"""
Ensure de-pickler imports any package child-modules that
are needed by the function
"""
# check if any known dependency is an imported package
for x in top_level_dependencies:
if isinstance(x, types.ModuleType) and hasattr(x, '__package__') and x.__package__:
# check if the package has any currently loaded sub-imports
prefix = x.__name__ + '.'
for name, module in sys.modules.items():
# Older versions of pytest will add a "None" module to sys.modules.
if name is not None and name.startswith(prefix):
# check whether the function can address the sub-module
tokens = set(name[len(prefix):].split('.'))
if not tokens - set(code.co_names):
# ensure unpickler executes this import
self.save(module)
# then discards the reference to it
self.write(pickle.POP) | [
"def",
"_save_subimports",
"(",
"self",
",",
"code",
",",
"top_level_dependencies",
")",
":",
"# check if any known dependency is an imported package",
"for",
"x",
"in",
"top_level_dependencies",
":",
"if",
"isinstance",
"(",
"x",
",",
"types",
".",
"ModuleType",
")",
"and",
"hasattr",
"(",
"x",
",",
"'__package__'",
")",
"and",
"x",
".",
"__package__",
":",
"# check if the package has any currently loaded sub-imports",
"prefix",
"=",
"x",
".",
"__name__",
"+",
"'.'",
"for",
"name",
",",
"module",
"in",
"sys",
".",
"modules",
".",
"items",
"(",
")",
":",
"# Older versions of pytest will add a \"None\" module to sys.modules.",
"if",
"name",
"is",
"not",
"None",
"and",
"name",
".",
"startswith",
"(",
"prefix",
")",
":",
"# check whether the function can address the sub-module",
"tokens",
"=",
"set",
"(",
"name",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
".",
"split",
"(",
"'.'",
")",
")",
"if",
"not",
"tokens",
"-",
"set",
"(",
"code",
".",
"co_names",
")",
":",
"# ensure unpickler executes this import",
"self",
".",
"save",
"(",
"module",
")",
"# then discards the reference to it",
"self",
".",
"write",
"(",
"pickle",
".",
"POP",
")"
] | Ensure de-pickler imports any package child-modules that
are needed by the function | [
"Ensure",
"de",
"-",
"pickler",
"imports",
"any",
"package",
"child",
"-",
"modules",
"that",
"are",
"needed",
"by",
"the",
"function"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/_cloudpickle.py#L405-L424 |
28,805 | apple/turicreate | src/unity/python/turicreate/util/_cloudpickle.py | CloudPickler.extract_code_globals | def extract_code_globals(cls, co):
"""
Find all globals names read or written to by codeblock co
"""
out_names = cls._extract_code_globals_cache.get(co)
if out_names is None:
try:
names = co.co_names
except AttributeError:
# PyPy "builtin-code" object
out_names = set()
else:
out_names = set(names[oparg]
for op, oparg in _walk_global_ops(co))
# see if nested function have any global refs
if co.co_consts:
for const in co.co_consts:
if type(const) is types.CodeType:
out_names |= cls.extract_code_globals(const)
cls._extract_code_globals_cache[co] = out_names
return out_names | python | def extract_code_globals(cls, co):
"""
Find all globals names read or written to by codeblock co
"""
out_names = cls._extract_code_globals_cache.get(co)
if out_names is None:
try:
names = co.co_names
except AttributeError:
# PyPy "builtin-code" object
out_names = set()
else:
out_names = set(names[oparg]
for op, oparg in _walk_global_ops(co))
# see if nested function have any global refs
if co.co_consts:
for const in co.co_consts:
if type(const) is types.CodeType:
out_names |= cls.extract_code_globals(const)
cls._extract_code_globals_cache[co] = out_names
return out_names | [
"def",
"extract_code_globals",
"(",
"cls",
",",
"co",
")",
":",
"out_names",
"=",
"cls",
".",
"_extract_code_globals_cache",
".",
"get",
"(",
"co",
")",
"if",
"out_names",
"is",
"None",
":",
"try",
":",
"names",
"=",
"co",
".",
"co_names",
"except",
"AttributeError",
":",
"# PyPy \"builtin-code\" object",
"out_names",
"=",
"set",
"(",
")",
"else",
":",
"out_names",
"=",
"set",
"(",
"names",
"[",
"oparg",
"]",
"for",
"op",
",",
"oparg",
"in",
"_walk_global_ops",
"(",
"co",
")",
")",
"# see if nested function have any global refs",
"if",
"co",
".",
"co_consts",
":",
"for",
"const",
"in",
"co",
".",
"co_consts",
":",
"if",
"type",
"(",
"const",
")",
"is",
"types",
".",
"CodeType",
":",
"out_names",
"|=",
"cls",
".",
"extract_code_globals",
"(",
"const",
")",
"cls",
".",
"_extract_code_globals_cache",
"[",
"co",
"]",
"=",
"out_names",
"return",
"out_names"
] | Find all globals names read or written to by codeblock co | [
"Find",
"all",
"globals",
"names",
"read",
"or",
"written",
"to",
"by",
"codeblock",
"co"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/_cloudpickle.py#L551-L574 |
28,806 | apple/turicreate | src/unity/python/turicreate/util/_cloudpickle.py | CloudPickler.save_file | def save_file(self, obj):
"""Save a file"""
try:
import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute
except ImportError:
import io as pystringIO
if not hasattr(obj, 'name') or not hasattr(obj, 'mode'):
raise pickle.PicklingError("Cannot pickle files that do not map to an actual file")
if obj is sys.stdout:
return self.save_reduce(getattr, (sys,'stdout'), obj=obj)
if obj is sys.stderr:
return self.save_reduce(getattr, (sys,'stderr'), obj=obj)
if obj is sys.stdin:
raise pickle.PicklingError("Cannot pickle standard input")
if obj.closed:
raise pickle.PicklingError("Cannot pickle closed files")
if hasattr(obj, 'isatty') and obj.isatty():
raise pickle.PicklingError("Cannot pickle files that map to tty objects")
if 'r' not in obj.mode and '+' not in obj.mode:
raise pickle.PicklingError("Cannot pickle files that are not opened for reading: %s" % obj.mode)
name = obj.name
retval = pystringIO.StringIO()
try:
# Read the whole file
curloc = obj.tell()
obj.seek(0)
contents = obj.read()
obj.seek(curloc)
except IOError:
raise pickle.PicklingError("Cannot pickle file %s as it cannot be read" % name)
retval.write(contents)
retval.seek(curloc)
retval.name = name
self.save(retval)
self.memoize(obj) | python | def save_file(self, obj):
"""Save a file"""
try:
import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute
except ImportError:
import io as pystringIO
if not hasattr(obj, 'name') or not hasattr(obj, 'mode'):
raise pickle.PicklingError("Cannot pickle files that do not map to an actual file")
if obj is sys.stdout:
return self.save_reduce(getattr, (sys,'stdout'), obj=obj)
if obj is sys.stderr:
return self.save_reduce(getattr, (sys,'stderr'), obj=obj)
if obj is sys.stdin:
raise pickle.PicklingError("Cannot pickle standard input")
if obj.closed:
raise pickle.PicklingError("Cannot pickle closed files")
if hasattr(obj, 'isatty') and obj.isatty():
raise pickle.PicklingError("Cannot pickle files that map to tty objects")
if 'r' not in obj.mode and '+' not in obj.mode:
raise pickle.PicklingError("Cannot pickle files that are not opened for reading: %s" % obj.mode)
name = obj.name
retval = pystringIO.StringIO()
try:
# Read the whole file
curloc = obj.tell()
obj.seek(0)
contents = obj.read()
obj.seek(curloc)
except IOError:
raise pickle.PicklingError("Cannot pickle file %s as it cannot be read" % name)
retval.write(contents)
retval.seek(curloc)
retval.name = name
self.save(retval)
self.memoize(obj) | [
"def",
"save_file",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"import",
"StringIO",
"as",
"pystringIO",
"#we can't use cStringIO as it lacks the name attribute",
"except",
"ImportError",
":",
"import",
"io",
"as",
"pystringIO",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'name'",
")",
"or",
"not",
"hasattr",
"(",
"obj",
",",
"'mode'",
")",
":",
"raise",
"pickle",
".",
"PicklingError",
"(",
"\"Cannot pickle files that do not map to an actual file\"",
")",
"if",
"obj",
"is",
"sys",
".",
"stdout",
":",
"return",
"self",
".",
"save_reduce",
"(",
"getattr",
",",
"(",
"sys",
",",
"'stdout'",
")",
",",
"obj",
"=",
"obj",
")",
"if",
"obj",
"is",
"sys",
".",
"stderr",
":",
"return",
"self",
".",
"save_reduce",
"(",
"getattr",
",",
"(",
"sys",
",",
"'stderr'",
")",
",",
"obj",
"=",
"obj",
")",
"if",
"obj",
"is",
"sys",
".",
"stdin",
":",
"raise",
"pickle",
".",
"PicklingError",
"(",
"\"Cannot pickle standard input\"",
")",
"if",
"obj",
".",
"closed",
":",
"raise",
"pickle",
".",
"PicklingError",
"(",
"\"Cannot pickle closed files\"",
")",
"if",
"hasattr",
"(",
"obj",
",",
"'isatty'",
")",
"and",
"obj",
".",
"isatty",
"(",
")",
":",
"raise",
"pickle",
".",
"PicklingError",
"(",
"\"Cannot pickle files that map to tty objects\"",
")",
"if",
"'r'",
"not",
"in",
"obj",
".",
"mode",
"and",
"'+'",
"not",
"in",
"obj",
".",
"mode",
":",
"raise",
"pickle",
".",
"PicklingError",
"(",
"\"Cannot pickle files that are not opened for reading: %s\"",
"%",
"obj",
".",
"mode",
")",
"name",
"=",
"obj",
".",
"name",
"retval",
"=",
"pystringIO",
".",
"StringIO",
"(",
")",
"try",
":",
"# Read the whole file",
"curloc",
"=",
"obj",
".",
"tell",
"(",
")",
"obj",
".",
"seek",
"(",
"0",
")",
"contents",
"=",
"obj",
".",
"read",
"(",
")",
"obj",
".",
"seek",
"(",
"curloc",
")",
"except",
"IOError",
":",
"raise",
"pickle",
".",
"PicklingError",
"(",
"\"Cannot pickle file %s as it cannot be read\"",
"%",
"name",
")",
"retval",
".",
"write",
"(",
"contents",
")",
"retval",
".",
"seek",
"(",
"curloc",
")",
"retval",
".",
"name",
"=",
"name",
"self",
".",
"save",
"(",
"retval",
")",
"self",
".",
"memoize",
"(",
"obj",
")"
] | Save a file | [
"Save",
"a",
"file"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/_cloudpickle.py#L847-L886 |
28,807 | apple/turicreate | src/unity/python/turicreate/util/_cloudpickle.py | CloudPickler.save_ufunc | def save_ufunc(self, obj):
"""Hack function for saving numpy ufunc objects"""
name = obj.__name__
numpy_tst_mods = ['numpy', 'scipy.special']
for tst_mod_name in numpy_tst_mods:
tst_mod = sys.modules.get(tst_mod_name, None)
if tst_mod and name in tst_mod.__dict__:
return self.save_reduce(_getobject, (tst_mod_name, name))
raise pickle.PicklingError('cannot save %s. Cannot resolve what module it is defined in'
% str(obj)) | python | def save_ufunc(self, obj):
"""Hack function for saving numpy ufunc objects"""
name = obj.__name__
numpy_tst_mods = ['numpy', 'scipy.special']
for tst_mod_name in numpy_tst_mods:
tst_mod = sys.modules.get(tst_mod_name, None)
if tst_mod and name in tst_mod.__dict__:
return self.save_reduce(_getobject, (tst_mod_name, name))
raise pickle.PicklingError('cannot save %s. Cannot resolve what module it is defined in'
% str(obj)) | [
"def",
"save_ufunc",
"(",
"self",
",",
"obj",
")",
":",
"name",
"=",
"obj",
".",
"__name__",
"numpy_tst_mods",
"=",
"[",
"'numpy'",
",",
"'scipy.special'",
"]",
"for",
"tst_mod_name",
"in",
"numpy_tst_mods",
":",
"tst_mod",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"tst_mod_name",
",",
"None",
")",
"if",
"tst_mod",
"and",
"name",
"in",
"tst_mod",
".",
"__dict__",
":",
"return",
"self",
".",
"save_reduce",
"(",
"_getobject",
",",
"(",
"tst_mod_name",
",",
"name",
")",
")",
"raise",
"pickle",
".",
"PicklingError",
"(",
"'cannot save %s. Cannot resolve what module it is defined in'",
"%",
"str",
"(",
"obj",
")",
")"
] | Hack function for saving numpy ufunc objects | [
"Hack",
"function",
"for",
"saving",
"numpy",
"ufunc",
"objects"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/_cloudpickle.py#L915-L924 |
28,808 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_database.py | _ExtractSymbols | def _ExtractSymbols(desc_proto, package):
"""Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor.
"""
message_name = '.'.join((package, desc_proto.name))
yield message_name
for nested_type in desc_proto.nested_type:
for symbol in _ExtractSymbols(nested_type, message_name):
yield symbol
for enum_type in desc_proto.enum_type:
yield '.'.join((message_name, enum_type.name)) | python | def _ExtractSymbols(desc_proto, package):
"""Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor.
"""
message_name = '.'.join((package, desc_proto.name))
yield message_name
for nested_type in desc_proto.nested_type:
for symbol in _ExtractSymbols(nested_type, message_name):
yield symbol
for enum_type in desc_proto.enum_type:
yield '.'.join((message_name, enum_type.name)) | [
"def",
"_ExtractSymbols",
"(",
"desc_proto",
",",
"package",
")",
":",
"message_name",
"=",
"'.'",
".",
"join",
"(",
"(",
"package",
",",
"desc_proto",
".",
"name",
")",
")",
"yield",
"message_name",
"for",
"nested_type",
"in",
"desc_proto",
".",
"nested_type",
":",
"for",
"symbol",
"in",
"_ExtractSymbols",
"(",
"nested_type",
",",
"message_name",
")",
":",
"yield",
"symbol",
"for",
"enum_type",
"in",
"desc_proto",
".",
"enum_type",
":",
"yield",
"'.'",
".",
"join",
"(",
"(",
"message_name",
",",
"enum_type",
".",
"name",
")",
")"
] | Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor. | [
"Pulls",
"out",
"all",
"the",
"symbols",
"from",
"a",
"descriptor",
"proto",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_database.py#L127-L144 |
28,809 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_database.py | DescriptorDatabase.Add | def Add(self, file_desc_proto):
"""Adds the FileDescriptorProto and its types to this database.
Args:
file_desc_proto: The FileDescriptorProto to add.
Raises:
DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
add a proto with the same name but different definition than an
exisiting proto in the database.
"""
proto_name = file_desc_proto.name
if proto_name not in self._file_desc_protos_by_file:
self._file_desc_protos_by_file[proto_name] = file_desc_proto
elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:
raise DescriptorDatabaseConflictingDefinitionError(
'%s already added, but with different descriptor.' % proto_name)
# Add all the top-level descriptors to the index.
package = file_desc_proto.package
for message in file_desc_proto.message_type:
self._file_desc_protos_by_symbol.update(
(name, file_desc_proto) for name in _ExtractSymbols(message, package))
for enum in file_desc_proto.enum_type:
self._file_desc_protos_by_symbol[
'.'.join((package, enum.name))] = file_desc_proto
for extension in file_desc_proto.extension:
self._file_desc_protos_by_symbol[
'.'.join((package, extension.name))] = file_desc_proto
for service in file_desc_proto.service:
self._file_desc_protos_by_symbol[
'.'.join((package, service.name))] = file_desc_proto | python | def Add(self, file_desc_proto):
"""Adds the FileDescriptorProto and its types to this database.
Args:
file_desc_proto: The FileDescriptorProto to add.
Raises:
DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
add a proto with the same name but different definition than an
exisiting proto in the database.
"""
proto_name = file_desc_proto.name
if proto_name not in self._file_desc_protos_by_file:
self._file_desc_protos_by_file[proto_name] = file_desc_proto
elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:
raise DescriptorDatabaseConflictingDefinitionError(
'%s already added, but with different descriptor.' % proto_name)
# Add all the top-level descriptors to the index.
package = file_desc_proto.package
for message in file_desc_proto.message_type:
self._file_desc_protos_by_symbol.update(
(name, file_desc_proto) for name in _ExtractSymbols(message, package))
for enum in file_desc_proto.enum_type:
self._file_desc_protos_by_symbol[
'.'.join((package, enum.name))] = file_desc_proto
for extension in file_desc_proto.extension:
self._file_desc_protos_by_symbol[
'.'.join((package, extension.name))] = file_desc_proto
for service in file_desc_proto.service:
self._file_desc_protos_by_symbol[
'.'.join((package, service.name))] = file_desc_proto | [
"def",
"Add",
"(",
"self",
",",
"file_desc_proto",
")",
":",
"proto_name",
"=",
"file_desc_proto",
".",
"name",
"if",
"proto_name",
"not",
"in",
"self",
".",
"_file_desc_protos_by_file",
":",
"self",
".",
"_file_desc_protos_by_file",
"[",
"proto_name",
"]",
"=",
"file_desc_proto",
"elif",
"self",
".",
"_file_desc_protos_by_file",
"[",
"proto_name",
"]",
"!=",
"file_desc_proto",
":",
"raise",
"DescriptorDatabaseConflictingDefinitionError",
"(",
"'%s already added, but with different descriptor.'",
"%",
"proto_name",
")",
"# Add all the top-level descriptors to the index.",
"package",
"=",
"file_desc_proto",
".",
"package",
"for",
"message",
"in",
"file_desc_proto",
".",
"message_type",
":",
"self",
".",
"_file_desc_protos_by_symbol",
".",
"update",
"(",
"(",
"name",
",",
"file_desc_proto",
")",
"for",
"name",
"in",
"_ExtractSymbols",
"(",
"message",
",",
"package",
")",
")",
"for",
"enum",
"in",
"file_desc_proto",
".",
"enum_type",
":",
"self",
".",
"_file_desc_protos_by_symbol",
"[",
"'.'",
".",
"join",
"(",
"(",
"package",
",",
"enum",
".",
"name",
")",
")",
"]",
"=",
"file_desc_proto",
"for",
"extension",
"in",
"file_desc_proto",
".",
"extension",
":",
"self",
".",
"_file_desc_protos_by_symbol",
"[",
"'.'",
".",
"join",
"(",
"(",
"package",
",",
"extension",
".",
"name",
")",
")",
"]",
"=",
"file_desc_proto",
"for",
"service",
"in",
"file_desc_proto",
".",
"service",
":",
"self",
".",
"_file_desc_protos_by_symbol",
"[",
"'.'",
".",
"join",
"(",
"(",
"package",
",",
"service",
".",
"name",
")",
")",
"]",
"=",
"file_desc_proto"
] | Adds the FileDescriptorProto and its types to this database.
Args:
file_desc_proto: The FileDescriptorProto to add.
Raises:
DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
add a proto with the same name but different definition than an
exisiting proto in the database. | [
"Adds",
"the",
"FileDescriptorProto",
"and",
"its",
"types",
"to",
"this",
"database",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_database.py#L51-L81 |
28,810 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_normalizer.py | convert | def convert(model, input_features, output_features):
"""Convert a normalizer model to the protobuf spec.
Parameters
----------
model: Normalizer
A Normalizer.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Normalizer)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'norm'))
# Set the interface params.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
spec = _set_transform_interface_params(spec, input_features, output_features)
# Set the one hot encoder parameters
_normalizer_spec = spec.normalizer
if model.norm == 'l1':
_normalizer_spec.normType = _proto__normalizer.L1
elif model.norm == 'l2':
_normalizer_spec.normType = _proto__normalizer.L2
elif model.norm == 'max':
_normalizer_spec.normType = _proto__normalizer.LMax
return _MLModel(spec) | python | def convert(model, input_features, output_features):
"""Convert a normalizer model to the protobuf spec.
Parameters
----------
model: Normalizer
A Normalizer.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Normalizer)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'norm'))
# Set the interface params.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
spec = _set_transform_interface_params(spec, input_features, output_features)
# Set the one hot encoder parameters
_normalizer_spec = spec.normalizer
if model.norm == 'l1':
_normalizer_spec.normType = _proto__normalizer.L1
elif model.norm == 'l2':
_normalizer_spec.normType = _proto__normalizer.L2
elif model.norm == 'max':
_normalizer_spec.normType = _proto__normalizer.LMax
return _MLModel(spec) | [
"def",
"convert",
"(",
"model",
",",
"input_features",
",",
"output_features",
")",
":",
"if",
"not",
"(",
"_HAS_SKLEARN",
")",
":",
"raise",
"RuntimeError",
"(",
"'scikit-learn not found. scikit-learn conversion API is disabled.'",
")",
"# Test the scikit-learn model",
"_sklearn_util",
".",
"check_expected_type",
"(",
"model",
",",
"Normalizer",
")",
"_sklearn_util",
".",
"check_fitted",
"(",
"model",
",",
"lambda",
"m",
":",
"hasattr",
"(",
"m",
",",
"'norm'",
")",
")",
"# Set the interface params.",
"spec",
"=",
"_Model_pb2",
".",
"Model",
"(",
")",
"spec",
".",
"specificationVersion",
"=",
"SPECIFICATION_VERSION",
"spec",
"=",
"_set_transform_interface_params",
"(",
"spec",
",",
"input_features",
",",
"output_features",
")",
"# Set the one hot encoder parameters",
"_normalizer_spec",
"=",
"spec",
".",
"normalizer",
"if",
"model",
".",
"norm",
"==",
"'l1'",
":",
"_normalizer_spec",
".",
"normType",
"=",
"_proto__normalizer",
".",
"L1",
"elif",
"model",
".",
"norm",
"==",
"'l2'",
":",
"_normalizer_spec",
".",
"normType",
"=",
"_proto__normalizer",
".",
"L2",
"elif",
"model",
".",
"norm",
"==",
"'max'",
":",
"_normalizer_spec",
".",
"normType",
"=",
"_proto__normalizer",
".",
"LMax",
"return",
"_MLModel",
"(",
"spec",
")"
] | Convert a normalizer model to the protobuf spec.
Parameters
----------
model: Normalizer
A Normalizer.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model | [
"Convert",
"a",
"normalizer",
"model",
"to",
"the",
"protobuf",
"spec",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_normalizer.py#L24-L64 |
28,811 | apple/turicreate | src/unity/python/turicreate/meta/bytecodetools/bytecode_consumer.py | ByteCodeConsumer.consume | def consume(self):
'''
Consume byte-code
'''
generic_consume = getattr(self, 'generic_consume', None)
for instr in disassembler(self.code):
method_name = 'consume_%s' % (instr.opname)
method = getattr(self, method_name, generic_consume)
if not method:
raise AttributeError("class %r has no method %r" % (type(self).__name__, method_name))
self.instruction_pre(instr)
method(instr)
self.instruction_post(instr) | python | def consume(self):
'''
Consume byte-code
'''
generic_consume = getattr(self, 'generic_consume', None)
for instr in disassembler(self.code):
method_name = 'consume_%s' % (instr.opname)
method = getattr(self, method_name, generic_consume)
if not method:
raise AttributeError("class %r has no method %r" % (type(self).__name__, method_name))
self.instruction_pre(instr)
method(instr)
self.instruction_post(instr) | [
"def",
"consume",
"(",
"self",
")",
":",
"generic_consume",
"=",
"getattr",
"(",
"self",
",",
"'generic_consume'",
",",
"None",
")",
"for",
"instr",
"in",
"disassembler",
"(",
"self",
".",
"code",
")",
":",
"method_name",
"=",
"'consume_%s'",
"%",
"(",
"instr",
".",
"opname",
")",
"method",
"=",
"getattr",
"(",
"self",
",",
"method_name",
",",
"generic_consume",
")",
"if",
"not",
"method",
":",
"raise",
"AttributeError",
"(",
"\"class %r has no method %r\"",
"%",
"(",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"method_name",
")",
")",
"self",
".",
"instruction_pre",
"(",
"instr",
")",
"method",
"(",
"instr",
")",
"self",
".",
"instruction_post",
"(",
"instr",
")"
] | Consume byte-code | [
"Consume",
"byte",
"-",
"code"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/bytecodetools/bytecode_consumer.py#L25-L39 |
28,812 | apple/turicreate | src/external/xgboost/python-package/xgboost/libpath.py | find_lib_path | def find_lib_path():
"""Load find the path to xgboost dynamic library files.
Returns
-------
lib_path: list(string)
List of all found library path to xgboost
"""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
# make pythonpack hack: copy this directory one level upper for setup.py
dll_path = [curr_path, os.path.join(curr_path, '../../wrapper/'),
os.path.join(curr_path, './wrapper/')]
if os.name == 'nt':
if platform.architecture()[0] == '64bit':
dll_path.append(os.path.join(curr_path, '../../windows/x64/Release/'))
# hack for pip installation when copy all parent source directory here
dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))
else:
dll_path.append(os.path.join(curr_path, '../../windows/Release/'))
# hack for pip installation when copy all parent source directory here
dll_path.append(os.path.join(curr_path, './windows/Release/'))
if os.name == 'nt':
dll_path = [os.path.join(p, 'xgboost_wrapper.dll') for p in dll_path]
else:
dll_path = [os.path.join(p, 'libxgboostwrapper.so') for p in dll_path]
lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]
#From github issues, most of installation errors come from machines w/o compilers
if len(lib_path) == 0 and not os.environ.get('XGBOOST_BUILD_DOC', False):
raise XGBoostLibraryNotFound(
'Cannot find XGBoost Libarary in the candicate path, ' +
'did you install compilers and run build.sh in root path?\n'
'List of candidates:\n' + ('\n'.join(dll_path)))
return lib_path | python | def find_lib_path():
"""Load find the path to xgboost dynamic library files.
Returns
-------
lib_path: list(string)
List of all found library path to xgboost
"""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
# make pythonpack hack: copy this directory one level upper for setup.py
dll_path = [curr_path, os.path.join(curr_path, '../../wrapper/'),
os.path.join(curr_path, './wrapper/')]
if os.name == 'nt':
if platform.architecture()[0] == '64bit':
dll_path.append(os.path.join(curr_path, '../../windows/x64/Release/'))
# hack for pip installation when copy all parent source directory here
dll_path.append(os.path.join(curr_path, './windows/x64/Release/'))
else:
dll_path.append(os.path.join(curr_path, '../../windows/Release/'))
# hack for pip installation when copy all parent source directory here
dll_path.append(os.path.join(curr_path, './windows/Release/'))
if os.name == 'nt':
dll_path = [os.path.join(p, 'xgboost_wrapper.dll') for p in dll_path]
else:
dll_path = [os.path.join(p, 'libxgboostwrapper.so') for p in dll_path]
lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]
#From github issues, most of installation errors come from machines w/o compilers
if len(lib_path) == 0 and not os.environ.get('XGBOOST_BUILD_DOC', False):
raise XGBoostLibraryNotFound(
'Cannot find XGBoost Libarary in the candicate path, ' +
'did you install compilers and run build.sh in root path?\n'
'List of candidates:\n' + ('\n'.join(dll_path)))
return lib_path | [
"def",
"find_lib_path",
"(",
")",
":",
"curr_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"__file__",
")",
")",
")",
"# make pythonpack hack: copy this directory one level upper for setup.py",
"dll_path",
"=",
"[",
"curr_path",
",",
"os",
".",
"path",
".",
"join",
"(",
"curr_path",
",",
"'../../wrapper/'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"curr_path",
",",
"'./wrapper/'",
")",
"]",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"if",
"platform",
".",
"architecture",
"(",
")",
"[",
"0",
"]",
"==",
"'64bit'",
":",
"dll_path",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"curr_path",
",",
"'../../windows/x64/Release/'",
")",
")",
"# hack for pip installation when copy all parent source directory here",
"dll_path",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"curr_path",
",",
"'./windows/x64/Release/'",
")",
")",
"else",
":",
"dll_path",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"curr_path",
",",
"'../../windows/Release/'",
")",
")",
"# hack for pip installation when copy all parent source directory here",
"dll_path",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"curr_path",
",",
"'./windows/Release/'",
")",
")",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"dll_path",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"'xgboost_wrapper.dll'",
")",
"for",
"p",
"in",
"dll_path",
"]",
"else",
":",
"dll_path",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"'libxgboostwrapper.so'",
")",
"for",
"p",
"in",
"dll_path",
"]",
"lib_path",
"=",
"[",
"p",
"for",
"p",
"in",
"dll_path",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"p",
")",
"]",
"#From github issues, most of installation errors come from machines w/o compilers",
"if",
"len",
"(",
"lib_path",
")",
"==",
"0",
"and",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'XGBOOST_BUILD_DOC'",
",",
"False",
")",
":",
"raise",
"XGBoostLibraryNotFound",
"(",
"'Cannot find XGBoost Libarary in the candicate path, '",
"+",
"'did you install compilers and run build.sh in root path?\\n'",
"'List of candidates:\\n'",
"+",
"(",
"'\\n'",
".",
"join",
"(",
"dll_path",
")",
")",
")",
"return",
"lib_path"
] | Load find the path to xgboost dynamic library files.
Returns
-------
lib_path: list(string)
List of all found library path to xgboost | [
"Load",
"find",
"the",
"path",
"to",
"xgboost",
"dynamic",
"library",
"files",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/libpath.py#L13-L45 |
28,813 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_sklearn_util.py | check_expected_type | def check_expected_type(model, expected_type):
"""Check if a model is of the right type. Raise error if not.
Parameters
----------
model: model
Any scikit-learn model
expected_type: Type
Expected type of the scikit-learn.
"""
if (model.__class__.__name__ != expected_type.__name__):
raise TypeError("Expected model of type '%s' (got %s)" % \
(expected_type.__name__, model.__class__.__name__)) | python | def check_expected_type(model, expected_type):
"""Check if a model is of the right type. Raise error if not.
Parameters
----------
model: model
Any scikit-learn model
expected_type: Type
Expected type of the scikit-learn.
"""
if (model.__class__.__name__ != expected_type.__name__):
raise TypeError("Expected model of type '%s' (got %s)" % \
(expected_type.__name__, model.__class__.__name__)) | [
"def",
"check_expected_type",
"(",
"model",
",",
"expected_type",
")",
":",
"if",
"(",
"model",
".",
"__class__",
".",
"__name__",
"!=",
"expected_type",
".",
"__name__",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected model of type '%s' (got %s)\"",
"%",
"(",
"expected_type",
".",
"__name__",
",",
"model",
".",
"__class__",
".",
"__name__",
")",
")"
] | Check if a model is of the right type. Raise error if not.
Parameters
----------
model: model
Any scikit-learn model
expected_type: Type
Expected type of the scikit-learn. | [
"Check",
"if",
"a",
"model",
"is",
"of",
"the",
"right",
"type",
".",
"Raise",
"error",
"if",
"not",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_sklearn_util.py#L20-L33 |
28,814 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/libsvm/__init__.py | convert | def convert(model, input_names='input', target_name='target',
probability='classProbability', input_length='auto'):
"""
Convert a LIBSVM model to Core ML format.
Parameters
----------
model: a libsvm model (C-SVC, nu-SVC, epsilon-SVR, or nu-SVR)
or string path to a saved model.
input_names: str | [str]
Name of the input column(s).
If a single string is used (the default) the input will be an array. The
length of the array will be inferred from the model, this can be overridden
using the 'input_length' parameter.
target: str
Name of the output column.
probability: str
Name of the output class probability column.
Only used for C-SVC and nu-SVC that have been trained with probability
estimates enabled.
input_length: int
Set the length of the input array.
This parameter should only be used when the input is an array (i.e. when
'input_name' is a string).
Returns
-------
model: MLModel
Model in Core ML format.
Examples
--------
.. sourcecode:: python
# Make a LIBSVM model
>>> import svmutil
>>> problem = svmutil.svm_problem([0,0,1,1], [[0,1], [1,1], [8,9], [7,7]])
>>> libsvm_model = svmutil.svm_train(problem, svmutil.svm_parameter())
# Convert using default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.libsvm.convert(libsvm_model)
# Save the CoreML model to a file.
>>> coreml_model.save('./my_model.mlmodel')
# Convert using user specified input names
>>> coreml_model = coremltools.converters.libsvm.convert(libsvm_model, input_names=['x', 'y'])
"""
if not(_HAS_LIBSVM):
raise RuntimeError('libsvm not found. libsvm conversion API is disabled.')
if isinstance(model, _string_types):
libsvm_model = _libsvm_util.load_model(model)
else:
libsvm_model = model
if not isinstance(libsvm_model, _libsvm.svm_model):
raise TypeError("Expected 'model' of type '%s' (got %s)" % (_libsvm.svm_model, type(libsvm_model)))
if not isinstance(target_name, _string_types):
raise TypeError("Expected 'target_name' of type str (got %s)" % type(libsvm_model))
if input_length != 'auto' and not isinstance(input_length, int):
raise TypeError("Expected 'input_length' of type int, got %s" % type(input_length))
if input_length != 'auto' and not isinstance(input_names, _string_types):
raise ValueError("'input_length' should not be used unless the input will be only one array.")
if not isinstance(probability, _string_types):
raise TypeError("Expected 'probability' of type str (got %s)" % type(probability))
return _libsvm_converter.convert(libsvm_model, input_names, target_name, input_length, probability) | python | def convert(model, input_names='input', target_name='target',
probability='classProbability', input_length='auto'):
"""
Convert a LIBSVM model to Core ML format.
Parameters
----------
model: a libsvm model (C-SVC, nu-SVC, epsilon-SVR, or nu-SVR)
or string path to a saved model.
input_names: str | [str]
Name of the input column(s).
If a single string is used (the default) the input will be an array. The
length of the array will be inferred from the model, this can be overridden
using the 'input_length' parameter.
target: str
Name of the output column.
probability: str
Name of the output class probability column.
Only used for C-SVC and nu-SVC that have been trained with probability
estimates enabled.
input_length: int
Set the length of the input array.
This parameter should only be used when the input is an array (i.e. when
'input_name' is a string).
Returns
-------
model: MLModel
Model in Core ML format.
Examples
--------
.. sourcecode:: python
# Make a LIBSVM model
>>> import svmutil
>>> problem = svmutil.svm_problem([0,0,1,1], [[0,1], [1,1], [8,9], [7,7]])
>>> libsvm_model = svmutil.svm_train(problem, svmutil.svm_parameter())
# Convert using default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.libsvm.convert(libsvm_model)
# Save the CoreML model to a file.
>>> coreml_model.save('./my_model.mlmodel')
# Convert using user specified input names
>>> coreml_model = coremltools.converters.libsvm.convert(libsvm_model, input_names=['x', 'y'])
"""
if not(_HAS_LIBSVM):
raise RuntimeError('libsvm not found. libsvm conversion API is disabled.')
if isinstance(model, _string_types):
libsvm_model = _libsvm_util.load_model(model)
else:
libsvm_model = model
if not isinstance(libsvm_model, _libsvm.svm_model):
raise TypeError("Expected 'model' of type '%s' (got %s)" % (_libsvm.svm_model, type(libsvm_model)))
if not isinstance(target_name, _string_types):
raise TypeError("Expected 'target_name' of type str (got %s)" % type(libsvm_model))
if input_length != 'auto' and not isinstance(input_length, int):
raise TypeError("Expected 'input_length' of type int, got %s" % type(input_length))
if input_length != 'auto' and not isinstance(input_names, _string_types):
raise ValueError("'input_length' should not be used unless the input will be only one array.")
if not isinstance(probability, _string_types):
raise TypeError("Expected 'probability' of type str (got %s)" % type(probability))
return _libsvm_converter.convert(libsvm_model, input_names, target_name, input_length, probability) | [
"def",
"convert",
"(",
"model",
",",
"input_names",
"=",
"'input'",
",",
"target_name",
"=",
"'target'",
",",
"probability",
"=",
"'classProbability'",
",",
"input_length",
"=",
"'auto'",
")",
":",
"if",
"not",
"(",
"_HAS_LIBSVM",
")",
":",
"raise",
"RuntimeError",
"(",
"'libsvm not found. libsvm conversion API is disabled.'",
")",
"if",
"isinstance",
"(",
"model",
",",
"_string_types",
")",
":",
"libsvm_model",
"=",
"_libsvm_util",
".",
"load_model",
"(",
"model",
")",
"else",
":",
"libsvm_model",
"=",
"model",
"if",
"not",
"isinstance",
"(",
"libsvm_model",
",",
"_libsvm",
".",
"svm_model",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected 'model' of type '%s' (got %s)\"",
"%",
"(",
"_libsvm",
".",
"svm_model",
",",
"type",
"(",
"libsvm_model",
")",
")",
")",
"if",
"not",
"isinstance",
"(",
"target_name",
",",
"_string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected 'target_name' of type str (got %s)\"",
"%",
"type",
"(",
"libsvm_model",
")",
")",
"if",
"input_length",
"!=",
"'auto'",
"and",
"not",
"isinstance",
"(",
"input_length",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected 'input_length' of type int, got %s\"",
"%",
"type",
"(",
"input_length",
")",
")",
"if",
"input_length",
"!=",
"'auto'",
"and",
"not",
"isinstance",
"(",
"input_names",
",",
"_string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"'input_length' should not be used unless the input will be only one array.\"",
")",
"if",
"not",
"isinstance",
"(",
"probability",
",",
"_string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected 'probability' of type str (got %s)\"",
"%",
"type",
"(",
"probability",
")",
")",
"return",
"_libsvm_converter",
".",
"convert",
"(",
"libsvm_model",
",",
"input_names",
",",
"target_name",
",",
"input_length",
",",
"probability",
")"
] | Convert a LIBSVM model to Core ML format.
Parameters
----------
model: a libsvm model (C-SVC, nu-SVC, epsilon-SVR, or nu-SVR)
or string path to a saved model.
input_names: str | [str]
Name of the input column(s).
If a single string is used (the default) the input will be an array. The
length of the array will be inferred from the model, this can be overridden
using the 'input_length' parameter.
target: str
Name of the output column.
probability: str
Name of the output class probability column.
Only used for C-SVC and nu-SVC that have been trained with probability
estimates enabled.
input_length: int
Set the length of the input array.
This parameter should only be used when the input is an array (i.e. when
'input_name' is a string).
Returns
-------
model: MLModel
Model in Core ML format.
Examples
--------
.. sourcecode:: python
# Make a LIBSVM model
>>> import svmutil
>>> problem = svmutil.svm_problem([0,0,1,1], [[0,1], [1,1], [8,9], [7,7]])
>>> libsvm_model = svmutil.svm_train(problem, svmutil.svm_parameter())
# Convert using default input and output names
>>> import coremltools
>>> coreml_model = coremltools.converters.libsvm.convert(libsvm_model)
# Save the CoreML model to a file.
>>> coreml_model.save('./my_model.mlmodel')
# Convert using user specified input names
>>> coreml_model = coremltools.converters.libsvm.convert(libsvm_model, input_names=['x', 'y']) | [
"Convert",
"a",
"LIBSVM",
"model",
"to",
"Core",
"ML",
"format",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/libsvm/__init__.py#L17-L93 |
28,815 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py | RepeatedScalarFieldContainer.MergeFrom | def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
one. We do not check the types of the individual fields.
"""
self._values.extend(other._values)
self._message_listener.Modified() | python | def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
one. We do not check the types of the individual fields.
"""
self._values.extend(other._values)
self._message_listener.Modified() | [
"def",
"MergeFrom",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_values",
".",
"extend",
"(",
"other",
".",
"_values",
")",
"self",
".",
"_message_listener",
".",
"Modified",
"(",
")"
] | Appends the contents of another repeated field of the same type to this
one. We do not check the types of the individual fields. | [
"Appends",
"the",
"contents",
"of",
"another",
"repeated",
"field",
"of",
"the",
"same",
"type",
"to",
"this",
"one",
".",
"We",
"do",
"not",
"check",
"the",
"types",
"of",
"the",
"individual",
"fields",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py#L280-L285 |
28,816 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py | RepeatedCompositeFieldContainer.add | def add(self, **kwargs):
"""Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element.
"""
new_element = self._message_descriptor._concrete_class(**kwargs)
new_element._SetListener(self._message_listener)
self._values.append(new_element)
if not self._message_listener.dirty:
self._message_listener.Modified()
return new_element | python | def add(self, **kwargs):
"""Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element.
"""
new_element = self._message_descriptor._concrete_class(**kwargs)
new_element._SetListener(self._message_listener)
self._values.append(new_element)
if not self._message_listener.dirty:
self._message_listener.Modified()
return new_element | [
"def",
"add",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new_element",
"=",
"self",
".",
"_message_descriptor",
".",
"_concrete_class",
"(",
"*",
"*",
"kwargs",
")",
"new_element",
".",
"_SetListener",
"(",
"self",
".",
"_message_listener",
")",
"self",
".",
"_values",
".",
"append",
"(",
"new_element",
")",
"if",
"not",
"self",
".",
"_message_listener",
".",
"dirty",
":",
"self",
".",
"_message_listener",
".",
"Modified",
"(",
")",
"return",
"new_element"
] | Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element. | [
"Adds",
"a",
"new",
"element",
"at",
"the",
"end",
"of",
"the",
"list",
"and",
"returns",
"it",
".",
"Keyword",
"arguments",
"may",
"be",
"used",
"to",
"initialize",
"the",
"element",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py#L368-L377 |
28,817 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py | RepeatedCompositeFieldContainer.extend | def extend(self, elem_seq):
"""Extends by appending the given sequence of elements of the same type
as this one, copying each individual message.
"""
message_class = self._message_descriptor._concrete_class
listener = self._message_listener
values = self._values
for message in elem_seq:
new_element = message_class()
new_element._SetListener(listener)
new_element.MergeFrom(message)
values.append(new_element)
listener.Modified() | python | def extend(self, elem_seq):
"""Extends by appending the given sequence of elements of the same type
as this one, copying each individual message.
"""
message_class = self._message_descriptor._concrete_class
listener = self._message_listener
values = self._values
for message in elem_seq:
new_element = message_class()
new_element._SetListener(listener)
new_element.MergeFrom(message)
values.append(new_element)
listener.Modified() | [
"def",
"extend",
"(",
"self",
",",
"elem_seq",
")",
":",
"message_class",
"=",
"self",
".",
"_message_descriptor",
".",
"_concrete_class",
"listener",
"=",
"self",
".",
"_message_listener",
"values",
"=",
"self",
".",
"_values",
"for",
"message",
"in",
"elem_seq",
":",
"new_element",
"=",
"message_class",
"(",
")",
"new_element",
".",
"_SetListener",
"(",
"listener",
")",
"new_element",
".",
"MergeFrom",
"(",
"message",
")",
"values",
".",
"append",
"(",
"new_element",
")",
"listener",
".",
"Modified",
"(",
")"
] | Extends by appending the given sequence of elements of the same type
as this one, copying each individual message. | [
"Extends",
"by",
"appending",
"the",
"given",
"sequence",
"of",
"elements",
"of",
"the",
"same",
"type",
"as",
"this",
"one",
"copying",
"each",
"individual",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py#L379-L391 |
28,818 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/set.py | difference | def difference (b, a):
""" Returns the elements of B that are not in A.
"""
a = set(a)
result = []
for item in b:
if item not in a:
result.append(item)
return result | python | def difference (b, a):
""" Returns the elements of B that are not in A.
"""
a = set(a)
result = []
for item in b:
if item not in a:
result.append(item)
return result | [
"def",
"difference",
"(",
"b",
",",
"a",
")",
":",
"a",
"=",
"set",
"(",
"a",
")",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"b",
":",
"if",
"item",
"not",
"in",
"a",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
] | Returns the elements of B that are not in A. | [
"Returns",
"the",
"elements",
"of",
"B",
"that",
"are",
"not",
"in",
"A",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/set.py#L10-L18 |
28,819 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/set.py | intersection | def intersection (set1, set2):
""" Removes from set1 any items which don't appear in set2 and returns the result.
"""
assert is_iterable(set1)
assert is_iterable(set2)
result = []
for v in set1:
if v in set2:
result.append (v)
return result | python | def intersection (set1, set2):
""" Removes from set1 any items which don't appear in set2 and returns the result.
"""
assert is_iterable(set1)
assert is_iterable(set2)
result = []
for v in set1:
if v in set2:
result.append (v)
return result | [
"def",
"intersection",
"(",
"set1",
",",
"set2",
")",
":",
"assert",
"is_iterable",
"(",
"set1",
")",
"assert",
"is_iterable",
"(",
"set2",
")",
"result",
"=",
"[",
"]",
"for",
"v",
"in",
"set1",
":",
"if",
"v",
"in",
"set2",
":",
"result",
".",
"append",
"(",
"v",
")",
"return",
"result"
] | Removes from set1 any items which don't appear in set2 and returns the result. | [
"Removes",
"from",
"set1",
"any",
"items",
"which",
"don",
"t",
"appear",
"in",
"set2",
"and",
"returns",
"the",
"result",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/set.py#L20-L29 |
28,820 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/set.py | contains | def contains (small, large):
""" Returns true iff all elements of 'small' exist in 'large'.
"""
small = to_seq (small)
large = to_seq (large)
for s in small:
if not s in large:
return False
return True | python | def contains (small, large):
""" Returns true iff all elements of 'small' exist in 'large'.
"""
small = to_seq (small)
large = to_seq (large)
for s in small:
if not s in large:
return False
return True | [
"def",
"contains",
"(",
"small",
",",
"large",
")",
":",
"small",
"=",
"to_seq",
"(",
"small",
")",
"large",
"=",
"to_seq",
"(",
"large",
")",
"for",
"s",
"in",
"small",
":",
"if",
"not",
"s",
"in",
"large",
":",
"return",
"False",
"return",
"True"
] | Returns true iff all elements of 'small' exist in 'large'. | [
"Returns",
"true",
"iff",
"all",
"elements",
"of",
"small",
"exist",
"in",
"large",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/set.py#L31-L40 |
28,821 | apple/turicreate | src/unity/python/turicreate/toolkits/image_classifier/_annotate.py | annotate | def annotate(data, image_column=None, annotation_column='annotations'):
"""
Annotate your images loaded in either an SFrame or SArray Format
The annotate util is a GUI assisted application used to create labels in
SArray Image data. Specifying a column, with dtype Image, in an SFrame
works as well since SFrames are composed of multiple SArrays.
When the GUI is terminated an SFrame is returned with the representative,
images and annotations.
The returned SFrame includes the newly created annotations.
Parameters
--------------
data : SArray | SFrame
The data containing the images. If the data type is 'SArray'
the 'image_column', and 'annotation_column' variables are used to construct
a new 'SFrame' containing the 'SArray' data for annotation.
If the data type is 'SFrame' the 'image_column', and 'annotation_column'
variables are used to annotate the images.
image_column: string, optional
If the data type is SFrame and the 'image_column' parameter is specified
then the column name is used as the image column used in the annotation. If
the data type is 'SFrame' and the 'image_column' variable is left empty. A
default column value of 'image' is used in the annotation. If the data type is
'SArray', the 'image_column' is used to construct the 'SFrame' data for
the annotation
annotation_column : string, optional
If the data type is SFrame and the 'annotation_column' parameter is specified
then the column name is used as the annotation column used in the annotation. If
the data type is 'SFrame' and the 'annotation_column' variable is left empty. A
default column value of 'annotation' is used in the annotation. If the data type is
'SArray', the 'annotation_column' is used to construct the 'SFrame' data for
the annotation
Returns
-------
out : SFrame
A new SFrame that contains the newly annotated data.
Examples
--------
>> import turicreate as tc
>> images = tc.image_analysis.load_images("path/to/images")
>> print(images)
Columns:
path str
image Image
Rows: 4
Data:
+------------------------+--------------------------+
| path | image |
+------------------------+--------------------------+
| /Users/username/Doc... | Height: 1712 Width: 1952 |
| /Users/username/Doc... | Height: 1386 Width: 1000 |
| /Users/username/Doc... | Height: 536 Width: 858 |
| /Users/username/Doc... | Height: 1512 Width: 2680 |
+------------------------+--------------------------+
[4 rows x 2 columns]
>> images = tc.image_classifier.annotate(images)
>> print(images)
Columns:
path str
image Image
annotation str
Rows: 4
Data:
+------------------------+--------------------------+-------------------+
| path | image | annotation |
+------------------------+--------------------------+-------------------+
| /Users/username/Doc... | Height: 1712 Width: 1952 | dog |
| /Users/username/Doc... | Height: 1386 Width: 1000 | dog |
| /Users/username/Doc... | Height: 536 Width: 858 | cat |
| /Users/username/Doc... | Height: 1512 Width: 2680 | mouse |
+------------------------+--------------------------+-------------------+
[4 rows x 3 columns]
"""
# Check Value of Column Variables
if image_column == None:
image_column = _tkutl._find_only_image_column(data)
if image_column == None:
raise ValueError("'image_column' cannot be 'None'")
if type(image_column) != str:
raise TypeError("'image_column' has to be of type 'str'")
if annotation_column == None:
annotation_column = ""
if type(annotation_column) != str:
raise TypeError("'annotation_column' has to be of type 'str'")
# Check Data Structure
if type(data) == __tc.data_structures.image.Image:
data = __tc.SFrame({image_column:__tc.SArray([data])})
elif type(data) == __tc.data_structures.sframe.SFrame:
if(data.shape[0] == 0):
return data
if not (data[image_column].dtype == __tc.data_structures.image.Image):
raise TypeError("'data[image_column]' must be an SFrame or SArray")
elif type(data) == __tc.data_structures.sarray.SArray:
if(data.shape[0] == 0):
return data
data = __tc.SFrame({image_column:data})
else:
raise TypeError("'data' must be an SFrame or SArray")
_warning_annotations()
annotation_window = __tc.extensions.create_image_classification_annotation(
data,
[image_column],
annotation_column
)
annotation_window.annotate(_get_client_app_path())
return annotation_window.returnAnnotations() | python | def annotate(data, image_column=None, annotation_column='annotations'):
"""
Annotate your images loaded in either an SFrame or SArray Format
The annotate util is a GUI assisted application used to create labels in
SArray Image data. Specifying a column, with dtype Image, in an SFrame
works as well since SFrames are composed of multiple SArrays.
When the GUI is terminated an SFrame is returned with the representative,
images and annotations.
The returned SFrame includes the newly created annotations.
Parameters
--------------
data : SArray | SFrame
The data containing the images. If the data type is 'SArray'
the 'image_column', and 'annotation_column' variables are used to construct
a new 'SFrame' containing the 'SArray' data for annotation.
If the data type is 'SFrame' the 'image_column', and 'annotation_column'
variables are used to annotate the images.
image_column: string, optional
If the data type is SFrame and the 'image_column' parameter is specified
then the column name is used as the image column used in the annotation. If
the data type is 'SFrame' and the 'image_column' variable is left empty. A
default column value of 'image' is used in the annotation. If the data type is
'SArray', the 'image_column' is used to construct the 'SFrame' data for
the annotation
annotation_column : string, optional
If the data type is SFrame and the 'annotation_column' parameter is specified
then the column name is used as the annotation column used in the annotation. If
the data type is 'SFrame' and the 'annotation_column' variable is left empty. A
default column value of 'annotation' is used in the annotation. If the data type is
'SArray', the 'annotation_column' is used to construct the 'SFrame' data for
the annotation
Returns
-------
out : SFrame
A new SFrame that contains the newly annotated data.
Examples
--------
>> import turicreate as tc
>> images = tc.image_analysis.load_images("path/to/images")
>> print(images)
Columns:
path str
image Image
Rows: 4
Data:
+------------------------+--------------------------+
| path | image |
+------------------------+--------------------------+
| /Users/username/Doc... | Height: 1712 Width: 1952 |
| /Users/username/Doc... | Height: 1386 Width: 1000 |
| /Users/username/Doc... | Height: 536 Width: 858 |
| /Users/username/Doc... | Height: 1512 Width: 2680 |
+------------------------+--------------------------+
[4 rows x 2 columns]
>> images = tc.image_classifier.annotate(images)
>> print(images)
Columns:
path str
image Image
annotation str
Rows: 4
Data:
+------------------------+--------------------------+-------------------+
| path | image | annotation |
+------------------------+--------------------------+-------------------+
| /Users/username/Doc... | Height: 1712 Width: 1952 | dog |
| /Users/username/Doc... | Height: 1386 Width: 1000 | dog |
| /Users/username/Doc... | Height: 536 Width: 858 | cat |
| /Users/username/Doc... | Height: 1512 Width: 2680 | mouse |
+------------------------+--------------------------+-------------------+
[4 rows x 3 columns]
"""
# Check Value of Column Variables
if image_column == None:
image_column = _tkutl._find_only_image_column(data)
if image_column == None:
raise ValueError("'image_column' cannot be 'None'")
if type(image_column) != str:
raise TypeError("'image_column' has to be of type 'str'")
if annotation_column == None:
annotation_column = ""
if type(annotation_column) != str:
raise TypeError("'annotation_column' has to be of type 'str'")
# Check Data Structure
if type(data) == __tc.data_structures.image.Image:
data = __tc.SFrame({image_column:__tc.SArray([data])})
elif type(data) == __tc.data_structures.sframe.SFrame:
if(data.shape[0] == 0):
return data
if not (data[image_column].dtype == __tc.data_structures.image.Image):
raise TypeError("'data[image_column]' must be an SFrame or SArray")
elif type(data) == __tc.data_structures.sarray.SArray:
if(data.shape[0] == 0):
return data
data = __tc.SFrame({image_column:data})
else:
raise TypeError("'data' must be an SFrame or SArray")
_warning_annotations()
annotation_window = __tc.extensions.create_image_classification_annotation(
data,
[image_column],
annotation_column
)
annotation_window.annotate(_get_client_app_path())
return annotation_window.returnAnnotations() | [
"def",
"annotate",
"(",
"data",
",",
"image_column",
"=",
"None",
",",
"annotation_column",
"=",
"'annotations'",
")",
":",
"# Check Value of Column Variables",
"if",
"image_column",
"==",
"None",
":",
"image_column",
"=",
"_tkutl",
".",
"_find_only_image_column",
"(",
"data",
")",
"if",
"image_column",
"==",
"None",
":",
"raise",
"ValueError",
"(",
"\"'image_column' cannot be 'None'\"",
")",
"if",
"type",
"(",
"image_column",
")",
"!=",
"str",
":",
"raise",
"TypeError",
"(",
"\"'image_column' has to be of type 'str'\"",
")",
"if",
"annotation_column",
"==",
"None",
":",
"annotation_column",
"=",
"\"\"",
"if",
"type",
"(",
"annotation_column",
")",
"!=",
"str",
":",
"raise",
"TypeError",
"(",
"\"'annotation_column' has to be of type 'str'\"",
")",
"# Check Data Structure",
"if",
"type",
"(",
"data",
")",
"==",
"__tc",
".",
"data_structures",
".",
"image",
".",
"Image",
":",
"data",
"=",
"__tc",
".",
"SFrame",
"(",
"{",
"image_column",
":",
"__tc",
".",
"SArray",
"(",
"[",
"data",
"]",
")",
"}",
")",
"elif",
"type",
"(",
"data",
")",
"==",
"__tc",
".",
"data_structures",
".",
"sframe",
".",
"SFrame",
":",
"if",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
")",
":",
"return",
"data",
"if",
"not",
"(",
"data",
"[",
"image_column",
"]",
".",
"dtype",
"==",
"__tc",
".",
"data_structures",
".",
"image",
".",
"Image",
")",
":",
"raise",
"TypeError",
"(",
"\"'data[image_column]' must be an SFrame or SArray\"",
")",
"elif",
"type",
"(",
"data",
")",
"==",
"__tc",
".",
"data_structures",
".",
"sarray",
".",
"SArray",
":",
"if",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
")",
":",
"return",
"data",
"data",
"=",
"__tc",
".",
"SFrame",
"(",
"{",
"image_column",
":",
"data",
"}",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"'data' must be an SFrame or SArray\"",
")",
"_warning_annotations",
"(",
")",
"annotation_window",
"=",
"__tc",
".",
"extensions",
".",
"create_image_classification_annotation",
"(",
"data",
",",
"[",
"image_column",
"]",
",",
"annotation_column",
")",
"annotation_window",
".",
"annotate",
"(",
"_get_client_app_path",
"(",
")",
")",
"return",
"annotation_window",
".",
"returnAnnotations",
"(",
")"
] | Annotate your images loaded in either an SFrame or SArray Format
The annotate util is a GUI assisted application used to create labels in
SArray Image data. Specifying a column, with dtype Image, in an SFrame
works as well since SFrames are composed of multiple SArrays.
When the GUI is terminated an SFrame is returned with the representative,
images and annotations.
The returned SFrame includes the newly created annotations.
Parameters
--------------
data : SArray | SFrame
The data containing the images. If the data type is 'SArray'
the 'image_column', and 'annotation_column' variables are used to construct
a new 'SFrame' containing the 'SArray' data for annotation.
If the data type is 'SFrame' the 'image_column', and 'annotation_column'
variables are used to annotate the images.
image_column: string, optional
If the data type is SFrame and the 'image_column' parameter is specified
then the column name is used as the image column used in the annotation. If
the data type is 'SFrame' and the 'image_column' variable is left empty. A
default column value of 'image' is used in the annotation. If the data type is
'SArray', the 'image_column' is used to construct the 'SFrame' data for
the annotation
annotation_column : string, optional
If the data type is SFrame and the 'annotation_column' parameter is specified
then the column name is used as the annotation column used in the annotation. If
the data type is 'SFrame' and the 'annotation_column' variable is left empty. A
default column value of 'annotation' is used in the annotation. If the data type is
'SArray', the 'annotation_column' is used to construct the 'SFrame' data for
the annotation
Returns
-------
out : SFrame
A new SFrame that contains the newly annotated data.
Examples
--------
>> import turicreate as tc
>> images = tc.image_analysis.load_images("path/to/images")
>> print(images)
Columns:
path str
image Image
Rows: 4
Data:
+------------------------+--------------------------+
| path | image |
+------------------------+--------------------------+
| /Users/username/Doc... | Height: 1712 Width: 1952 |
| /Users/username/Doc... | Height: 1386 Width: 1000 |
| /Users/username/Doc... | Height: 536 Width: 858 |
| /Users/username/Doc... | Height: 1512 Width: 2680 |
+------------------------+--------------------------+
[4 rows x 2 columns]
>> images = tc.image_classifier.annotate(images)
>> print(images)
Columns:
path str
image Image
annotation str
Rows: 4
Data:
+------------------------+--------------------------+-------------------+
| path | image | annotation |
+------------------------+--------------------------+-------------------+
| /Users/username/Doc... | Height: 1712 Width: 1952 | dog |
| /Users/username/Doc... | Height: 1386 Width: 1000 | dog |
| /Users/username/Doc... | Height: 536 Width: 858 | cat |
| /Users/username/Doc... | Height: 1512 Width: 2680 | mouse |
+------------------------+--------------------------+-------------------+
[4 rows x 3 columns] | [
"Annotate",
"your",
"images",
"loaded",
"in",
"either",
"an",
"SFrame",
"or",
"SArray",
"Format"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/_annotate.py#L30-L171 |
28,822 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_imputer.py | convert | def convert(model, input_features, output_features):
"""Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Set the interface params.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# feature name in and out are the same here
spec = set_transform_interface_params(spec, input_features, output_features)
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Imputer)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'statistics_'))
if model.axis != 0:
raise ValueError("Imputation is only supported along axis = 0.")
# The imputer in our framework only works on single columns, so
# we need to translate that over. The easiest way to do that is to
# put it in a nested pipeline with a feature extractor and a
tr_spec = spec.imputer
for v in model.statistics_:
tr_spec.imputedDoubleArray.vector.append(v)
try:
tr_spec.replaceDoubleValue = float(model.missing_values)
except ValueError:
raise ValueError("Only scalar values or NAN as missing_values "
"in _imputer are supported.")
return _MLModel(spec) | python | def convert(model, input_features, output_features):
"""Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Set the interface params.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# feature name in and out are the same here
spec = set_transform_interface_params(spec, input_features, output_features)
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Imputer)
_sklearn_util.check_fitted(model, lambda m: hasattr(m, 'statistics_'))
if model.axis != 0:
raise ValueError("Imputation is only supported along axis = 0.")
# The imputer in our framework only works on single columns, so
# we need to translate that over. The easiest way to do that is to
# put it in a nested pipeline with a feature extractor and a
tr_spec = spec.imputer
for v in model.statistics_:
tr_spec.imputedDoubleArray.vector.append(v)
try:
tr_spec.replaceDoubleValue = float(model.missing_values)
except ValueError:
raise ValueError("Only scalar values or NAN as missing_values "
"in _imputer are supported.")
return _MLModel(spec) | [
"def",
"convert",
"(",
"model",
",",
"input_features",
",",
"output_features",
")",
":",
"if",
"not",
"(",
"_HAS_SKLEARN",
")",
":",
"raise",
"RuntimeError",
"(",
"'scikit-learn not found. scikit-learn conversion API is disabled.'",
")",
"# Set the interface params.",
"spec",
"=",
"_Model_pb2",
".",
"Model",
"(",
")",
"spec",
".",
"specificationVersion",
"=",
"SPECIFICATION_VERSION",
"assert",
"len",
"(",
"input_features",
")",
"==",
"1",
"assert",
"isinstance",
"(",
"input_features",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"datatypes",
".",
"Array",
")",
"# feature name in and out are the same here",
"spec",
"=",
"set_transform_interface_params",
"(",
"spec",
",",
"input_features",
",",
"output_features",
")",
"# Test the scikit-learn model",
"_sklearn_util",
".",
"check_expected_type",
"(",
"model",
",",
"Imputer",
")",
"_sklearn_util",
".",
"check_fitted",
"(",
"model",
",",
"lambda",
"m",
":",
"hasattr",
"(",
"m",
",",
"'statistics_'",
")",
")",
"if",
"model",
".",
"axis",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Imputation is only supported along axis = 0.\"",
")",
"# The imputer in our framework only works on single columns, so",
"# we need to translate that over. The easiest way to do that is to",
"# put it in a nested pipeline with a feature extractor and a",
"tr_spec",
"=",
"spec",
".",
"imputer",
"for",
"v",
"in",
"model",
".",
"statistics_",
":",
"tr_spec",
".",
"imputedDoubleArray",
".",
"vector",
".",
"append",
"(",
"v",
")",
"try",
":",
"tr_spec",
".",
"replaceDoubleValue",
"=",
"float",
"(",
"model",
".",
"missing_values",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Only scalar values or NAN as missing_values \"",
"\"in _imputer are supported.\"",
")",
"return",
"_MLModel",
"(",
"spec",
")"
] | Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model | [
"Convert",
"a",
"DictVectorizer",
"model",
"to",
"the",
"protobuf",
"spec",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_imputer.py#L21-L76 |
28,823 | apple/turicreate | src/unity/python/turicreate/_cython/python_printer_callback.py | print_callback | def print_callback(val):
"""
Internal function.
This function is called via a call back returning from IPC to Cython
to Python. It tries to perform incremental printing to IPython Notebook or
Jupyter Notebook and when all else fails, just prints locally.
"""
success = False
try:
# for reasons I cannot fathom, regular printing, even directly
# to io.stdout does not work.
# I have to intrude rather deep into IPython to make it behave
if have_ipython:
if InteractiveShell.initialized():
IPython.display.publish_display_data({'text/plain':val,'text/html':'<pre>' + val + '</pre>'})
success = True
except:
pass
if not success:
print(val)
sys.stdout.flush() | python | def print_callback(val):
"""
Internal function.
This function is called via a call back returning from IPC to Cython
to Python. It tries to perform incremental printing to IPython Notebook or
Jupyter Notebook and when all else fails, just prints locally.
"""
success = False
try:
# for reasons I cannot fathom, regular printing, even directly
# to io.stdout does not work.
# I have to intrude rather deep into IPython to make it behave
if have_ipython:
if InteractiveShell.initialized():
IPython.display.publish_display_data({'text/plain':val,'text/html':'<pre>' + val + '</pre>'})
success = True
except:
pass
if not success:
print(val)
sys.stdout.flush() | [
"def",
"print_callback",
"(",
"val",
")",
":",
"success",
"=",
"False",
"try",
":",
"# for reasons I cannot fathom, regular printing, even directly",
"# to io.stdout does not work.",
"# I have to intrude rather deep into IPython to make it behave",
"if",
"have_ipython",
":",
"if",
"InteractiveShell",
".",
"initialized",
"(",
")",
":",
"IPython",
".",
"display",
".",
"publish_display_data",
"(",
"{",
"'text/plain'",
":",
"val",
",",
"'text/html'",
":",
"'<pre>'",
"+",
"val",
"+",
"'</pre>'",
"}",
")",
"success",
"=",
"True",
"except",
":",
"pass",
"if",
"not",
"success",
":",
"print",
"(",
"val",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | Internal function.
This function is called via a call back returning from IPC to Cython
to Python. It tries to perform incremental printing to IPython Notebook or
Jupyter Notebook and when all else fails, just prints locally. | [
"Internal",
"function",
".",
"This",
"function",
"is",
"called",
"via",
"a",
"call",
"back",
"returning",
"from",
"IPC",
"to",
"Cython",
"to",
"Python",
".",
"It",
"tries",
"to",
"perform",
"incremental",
"printing",
"to",
"IPython",
"Notebook",
"or",
"Jupyter",
"Notebook",
"and",
"when",
"all",
"else",
"fails",
"just",
"prints",
"locally",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_cython/python_printer_callback.py#L17-L38 |
28,824 | apple/turicreate | src/unity/python/turicreate/toolkits/_main.py | run | def run(toolkit_name, options, verbose=True, show_progress=False):
"""
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function,
for example: {'graph': g, 'reset_prob': 0.15}.
verbose : bool
If true, enable progress log from server.
show_progress : bool
If true, display progress plot.
Returns
-------
out : dict
The toolkit specific model parameters.
Raises
------
RuntimeError
Raises RuntimeError if the server fail executing the toolkit.
"""
unity = glconnect.get_unity()
if (not verbose):
glconnect.get_server().set_log_progress(False)
(success, message, params) = unity.run_toolkit(toolkit_name, options)
if (len(message) > 0):
logging.getLogger(__name__).error("Toolkit error: " + message)
# set the verbose level back to default
glconnect.get_server().set_log_progress(True)
if success:
return params
else:
raise ToolkitError(str(message)) | python | def run(toolkit_name, options, verbose=True, show_progress=False):
"""
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function,
for example: {'graph': g, 'reset_prob': 0.15}.
verbose : bool
If true, enable progress log from server.
show_progress : bool
If true, display progress plot.
Returns
-------
out : dict
The toolkit specific model parameters.
Raises
------
RuntimeError
Raises RuntimeError if the server fail executing the toolkit.
"""
unity = glconnect.get_unity()
if (not verbose):
glconnect.get_server().set_log_progress(False)
(success, message, params) = unity.run_toolkit(toolkit_name, options)
if (len(message) > 0):
logging.getLogger(__name__).error("Toolkit error: " + message)
# set the verbose level back to default
glconnect.get_server().set_log_progress(True)
if success:
return params
else:
raise ToolkitError(str(message)) | [
"def",
"run",
"(",
"toolkit_name",
",",
"options",
",",
"verbose",
"=",
"True",
",",
"show_progress",
"=",
"False",
")",
":",
"unity",
"=",
"glconnect",
".",
"get_unity",
"(",
")",
"if",
"(",
"not",
"verbose",
")",
":",
"glconnect",
".",
"get_server",
"(",
")",
".",
"set_log_progress",
"(",
"False",
")",
"(",
"success",
",",
"message",
",",
"params",
")",
"=",
"unity",
".",
"run_toolkit",
"(",
"toolkit_name",
",",
"options",
")",
"if",
"(",
"len",
"(",
"message",
")",
">",
"0",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"error",
"(",
"\"Toolkit error: \"",
"+",
"message",
")",
"# set the verbose level back to default",
"glconnect",
".",
"get_server",
"(",
")",
".",
"set_log_progress",
"(",
"True",
")",
"if",
"success",
":",
"return",
"params",
"else",
":",
"raise",
"ToolkitError",
"(",
"str",
"(",
"message",
")",
")"
] | Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function,
for example: {'graph': g, 'reset_prob': 0.15}.
verbose : bool
If true, enable progress log from server.
show_progress : bool
If true, display progress plot.
Returns
-------
out : dict
The toolkit specific model parameters.
Raises
------
RuntimeError
Raises RuntimeError if the server fail executing the toolkit. | [
"Internal",
"function",
"to",
"execute",
"toolkit",
"on",
"the",
"turicreate",
"server",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_main.py#L25-L69 |
28,825 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _RoundTowardZero | def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation
# dependent if any of the operands is negative. Here we enforce
# "rounded toward zero" semantics. For example, for (-5) / 2 an
# implementation may give -3 as the result with the remainder being
# 1. This function ensures we always return -2 (closer to zero).
result = value // divider
remainder = value % divider
if result < 0 and remainder > 0:
return result + 1
else:
return result | python | def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation
# dependent if any of the operands is negative. Here we enforce
# "rounded toward zero" semantics. For example, for (-5) / 2 an
# implementation may give -3 as the result with the remainder being
# 1. This function ensures we always return -2 (closer to zero).
result = value // divider
remainder = value % divider
if result < 0 and remainder > 0:
return result + 1
else:
return result | [
"def",
"_RoundTowardZero",
"(",
"value",
",",
"divider",
")",
":",
"# For some languanges, the sign of the remainder is implementation",
"# dependent if any of the operands is negative. Here we enforce",
"# \"rounded toward zero\" semantics. For example, for (-5) / 2 an",
"# implementation may give -3 as the result with the remainder being",
"# 1. This function ensures we always return -2 (closer to zero).",
"result",
"=",
"value",
"//",
"divider",
"remainder",
"=",
"value",
"%",
"divider",
"if",
"result",
"<",
"0",
"and",
"remainder",
">",
"0",
":",
"return",
"result",
"+",
"1",
"else",
":",
"return",
"result"
] | Truncates the remainder part after division. | [
"Truncates",
"the",
"remainder",
"part",
"after",
"division",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L378-L390 |
28,826 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _IsValidPath | def _IsValidPath(message_descriptor, path):
"""Checks whether the path is valid for Message Descriptor."""
parts = path.split('.')
last = parts.pop()
for name in parts:
field = message_descriptor.fields_by_name[name]
if (field is None or
field.label == FieldDescriptor.LABEL_REPEATED or
field.type != FieldDescriptor.TYPE_MESSAGE):
return False
message_descriptor = field.message_type
return last in message_descriptor.fields_by_name | python | def _IsValidPath(message_descriptor, path):
"""Checks whether the path is valid for Message Descriptor."""
parts = path.split('.')
last = parts.pop()
for name in parts:
field = message_descriptor.fields_by_name[name]
if (field is None or
field.label == FieldDescriptor.LABEL_REPEATED or
field.type != FieldDescriptor.TYPE_MESSAGE):
return False
message_descriptor = field.message_type
return last in message_descriptor.fields_by_name | [
"def",
"_IsValidPath",
"(",
"message_descriptor",
",",
"path",
")",
":",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"last",
"=",
"parts",
".",
"pop",
"(",
")",
"for",
"name",
"in",
"parts",
":",
"field",
"=",
"message_descriptor",
".",
"fields_by_name",
"[",
"name",
"]",
"if",
"(",
"field",
"is",
"None",
"or",
"field",
".",
"label",
"==",
"FieldDescriptor",
".",
"LABEL_REPEATED",
"or",
"field",
".",
"type",
"!=",
"FieldDescriptor",
".",
"TYPE_MESSAGE",
")",
":",
"return",
"False",
"message_descriptor",
"=",
"field",
".",
"message_type",
"return",
"last",
"in",
"message_descriptor",
".",
"fields_by_name"
] | Checks whether the path is valid for Message Descriptor. | [
"Checks",
"whether",
"the",
"path",
"is",
"valid",
"for",
"Message",
"Descriptor",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L471-L482 |
28,827 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _CheckFieldMaskMessage | def _CheckFieldMaskMessage(message):
"""Raises ValueError if message is not a FieldMask."""
message_descriptor = message.DESCRIPTOR
if (message_descriptor.name != 'FieldMask' or
message_descriptor.file.name != 'google/protobuf/field_mask.proto'):
raise ValueError('Message {0} is not a FieldMask.'.format(
message_descriptor.full_name)) | python | def _CheckFieldMaskMessage(message):
"""Raises ValueError if message is not a FieldMask."""
message_descriptor = message.DESCRIPTOR
if (message_descriptor.name != 'FieldMask' or
message_descriptor.file.name != 'google/protobuf/field_mask.proto'):
raise ValueError('Message {0} is not a FieldMask.'.format(
message_descriptor.full_name)) | [
"def",
"_CheckFieldMaskMessage",
"(",
"message",
")",
":",
"message_descriptor",
"=",
"message",
".",
"DESCRIPTOR",
"if",
"(",
"message_descriptor",
".",
"name",
"!=",
"'FieldMask'",
"or",
"message_descriptor",
".",
"file",
".",
"name",
"!=",
"'google/protobuf/field_mask.proto'",
")",
":",
"raise",
"ValueError",
"(",
"'Message {0} is not a FieldMask.'",
".",
"format",
"(",
"message_descriptor",
".",
"full_name",
")",
")"
] | Raises ValueError if message is not a FieldMask. | [
"Raises",
"ValueError",
"if",
"message",
"is",
"not",
"a",
"FieldMask",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L485-L491 |
28,828 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _SnakeCaseToCamelCase | def _SnakeCaseToCamelCase(path_name):
"""Converts a path name from snake_case to camelCase."""
result = []
after_underscore = False
for c in path_name:
if c.isupper():
raise Error('Fail to print FieldMask to Json string: Path name '
'{0} must not contain uppercase letters.'.format(path_name))
if after_underscore:
if c.islower():
result.append(c.upper())
after_underscore = False
else:
raise Error('Fail to print FieldMask to Json string: The '
'character after a "_" must be a lowercase letter '
'in path name {0}.'.format(path_name))
elif c == '_':
after_underscore = True
else:
result += c
if after_underscore:
raise Error('Fail to print FieldMask to Json string: Trailing "_" '
'in path name {0}.'.format(path_name))
return ''.join(result) | python | def _SnakeCaseToCamelCase(path_name):
"""Converts a path name from snake_case to camelCase."""
result = []
after_underscore = False
for c in path_name:
if c.isupper():
raise Error('Fail to print FieldMask to Json string: Path name '
'{0} must not contain uppercase letters.'.format(path_name))
if after_underscore:
if c.islower():
result.append(c.upper())
after_underscore = False
else:
raise Error('Fail to print FieldMask to Json string: The '
'character after a "_" must be a lowercase letter '
'in path name {0}.'.format(path_name))
elif c == '_':
after_underscore = True
else:
result += c
if after_underscore:
raise Error('Fail to print FieldMask to Json string: Trailing "_" '
'in path name {0}.'.format(path_name))
return ''.join(result) | [
"def",
"_SnakeCaseToCamelCase",
"(",
"path_name",
")",
":",
"result",
"=",
"[",
"]",
"after_underscore",
"=",
"False",
"for",
"c",
"in",
"path_name",
":",
"if",
"c",
".",
"isupper",
"(",
")",
":",
"raise",
"Error",
"(",
"'Fail to print FieldMask to Json string: Path name '",
"'{0} must not contain uppercase letters.'",
".",
"format",
"(",
"path_name",
")",
")",
"if",
"after_underscore",
":",
"if",
"c",
".",
"islower",
"(",
")",
":",
"result",
".",
"append",
"(",
"c",
".",
"upper",
"(",
")",
")",
"after_underscore",
"=",
"False",
"else",
":",
"raise",
"Error",
"(",
"'Fail to print FieldMask to Json string: The '",
"'character after a \"_\" must be a lowercase letter '",
"'in path name {0}.'",
".",
"format",
"(",
"path_name",
")",
")",
"elif",
"c",
"==",
"'_'",
":",
"after_underscore",
"=",
"True",
"else",
":",
"result",
"+=",
"c",
"if",
"after_underscore",
":",
"raise",
"Error",
"(",
"'Fail to print FieldMask to Json string: Trailing \"_\" '",
"'in path name {0}.'",
".",
"format",
"(",
"path_name",
")",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Converts a path name from snake_case to camelCase. | [
"Converts",
"a",
"path",
"name",
"from",
"snake_case",
"to",
"camelCase",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L494-L518 |
28,829 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _CamelCaseToSnakeCase | def _CamelCaseToSnakeCase(path_name):
"""Converts a field name from camelCase to snake_case."""
result = []
for c in path_name:
if c == '_':
raise ParseError('Fail to parse FieldMask: Path name '
'{0} must not contain "_"s.'.format(path_name))
if c.isupper():
result += '_'
result += c.lower()
else:
result += c
return ''.join(result) | python | def _CamelCaseToSnakeCase(path_name):
"""Converts a field name from camelCase to snake_case."""
result = []
for c in path_name:
if c == '_':
raise ParseError('Fail to parse FieldMask: Path name '
'{0} must not contain "_"s.'.format(path_name))
if c.isupper():
result += '_'
result += c.lower()
else:
result += c
return ''.join(result) | [
"def",
"_CamelCaseToSnakeCase",
"(",
"path_name",
")",
":",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"path_name",
":",
"if",
"c",
"==",
"'_'",
":",
"raise",
"ParseError",
"(",
"'Fail to parse FieldMask: Path name '",
"'{0} must not contain \"_\"s.'",
".",
"format",
"(",
"path_name",
")",
")",
"if",
"c",
".",
"isupper",
"(",
")",
":",
"result",
"+=",
"'_'",
"result",
"+=",
"c",
".",
"lower",
"(",
")",
"else",
":",
"result",
"+=",
"c",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Converts a field name from camelCase to snake_case. | [
"Converts",
"a",
"field",
"name",
"from",
"camelCase",
"to",
"snake_case",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L521-L533 |
28,830 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _MergeMessage | def _MergeMessage(
node, source, destination, replace_message, replace_repeated):
"""Merge all fields specified by a sub-tree from source to destination."""
source_descriptor = source.DESCRIPTOR
for name in node:
child = node[name]
field = source_descriptor.fields_by_name[name]
if field is None:
raise ValueError('Error: Can\'t find field {0} in message {1}.'.format(
name, source_descriptor.full_name))
if child:
# Sub-paths are only allowed for singular message fields.
if (field.label == FieldDescriptor.LABEL_REPEATED or
field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE):
raise ValueError('Error: Field {0} in message {1} is not a singular '
'message field and cannot have sub-fields.'.format(
name, source_descriptor.full_name))
_MergeMessage(
child, getattr(source, name), getattr(destination, name),
replace_message, replace_repeated)
continue
if field.label == FieldDescriptor.LABEL_REPEATED:
if replace_repeated:
destination.ClearField(_StrConvert(name))
repeated_source = getattr(source, name)
repeated_destination = getattr(destination, name)
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
for item in repeated_source:
repeated_destination.add().MergeFrom(item)
else:
repeated_destination.extend(repeated_source)
else:
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
if replace_message:
destination.ClearField(_StrConvert(name))
if source.HasField(name):
getattr(destination, name).MergeFrom(getattr(source, name))
else:
setattr(destination, name, getattr(source, name)) | python | def _MergeMessage(
node, source, destination, replace_message, replace_repeated):
"""Merge all fields specified by a sub-tree from source to destination."""
source_descriptor = source.DESCRIPTOR
for name in node:
child = node[name]
field = source_descriptor.fields_by_name[name]
if field is None:
raise ValueError('Error: Can\'t find field {0} in message {1}.'.format(
name, source_descriptor.full_name))
if child:
# Sub-paths are only allowed for singular message fields.
if (field.label == FieldDescriptor.LABEL_REPEATED or
field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE):
raise ValueError('Error: Field {0} in message {1} is not a singular '
'message field and cannot have sub-fields.'.format(
name, source_descriptor.full_name))
_MergeMessage(
child, getattr(source, name), getattr(destination, name),
replace_message, replace_repeated)
continue
if field.label == FieldDescriptor.LABEL_REPEATED:
if replace_repeated:
destination.ClearField(_StrConvert(name))
repeated_source = getattr(source, name)
repeated_destination = getattr(destination, name)
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
for item in repeated_source:
repeated_destination.add().MergeFrom(item)
else:
repeated_destination.extend(repeated_source)
else:
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
if replace_message:
destination.ClearField(_StrConvert(name))
if source.HasField(name):
getattr(destination, name).MergeFrom(getattr(source, name))
else:
setattr(destination, name, getattr(source, name)) | [
"def",
"_MergeMessage",
"(",
"node",
",",
"source",
",",
"destination",
",",
"replace_message",
",",
"replace_repeated",
")",
":",
"source_descriptor",
"=",
"source",
".",
"DESCRIPTOR",
"for",
"name",
"in",
"node",
":",
"child",
"=",
"node",
"[",
"name",
"]",
"field",
"=",
"source_descriptor",
".",
"fields_by_name",
"[",
"name",
"]",
"if",
"field",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Error: Can\\'t find field {0} in message {1}.'",
".",
"format",
"(",
"name",
",",
"source_descriptor",
".",
"full_name",
")",
")",
"if",
"child",
":",
"# Sub-paths are only allowed for singular message fields.",
"if",
"(",
"field",
".",
"label",
"==",
"FieldDescriptor",
".",
"LABEL_REPEATED",
"or",
"field",
".",
"cpp_type",
"!=",
"FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
")",
":",
"raise",
"ValueError",
"(",
"'Error: Field {0} in message {1} is not a singular '",
"'message field and cannot have sub-fields.'",
".",
"format",
"(",
"name",
",",
"source_descriptor",
".",
"full_name",
")",
")",
"_MergeMessage",
"(",
"child",
",",
"getattr",
"(",
"source",
",",
"name",
")",
",",
"getattr",
"(",
"destination",
",",
"name",
")",
",",
"replace_message",
",",
"replace_repeated",
")",
"continue",
"if",
"field",
".",
"label",
"==",
"FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"if",
"replace_repeated",
":",
"destination",
".",
"ClearField",
"(",
"_StrConvert",
"(",
"name",
")",
")",
"repeated_source",
"=",
"getattr",
"(",
"source",
",",
"name",
")",
"repeated_destination",
"=",
"getattr",
"(",
"destination",
",",
"name",
")",
"if",
"field",
".",
"cpp_type",
"==",
"FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"for",
"item",
"in",
"repeated_source",
":",
"repeated_destination",
".",
"add",
"(",
")",
".",
"MergeFrom",
"(",
"item",
")",
"else",
":",
"repeated_destination",
".",
"extend",
"(",
"repeated_source",
")",
"else",
":",
"if",
"field",
".",
"cpp_type",
"==",
"FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"if",
"replace_message",
":",
"destination",
".",
"ClearField",
"(",
"_StrConvert",
"(",
"name",
")",
")",
"if",
"source",
".",
"HasField",
"(",
"name",
")",
":",
"getattr",
"(",
"destination",
",",
"name",
")",
".",
"MergeFrom",
"(",
"getattr",
"(",
"source",
",",
"name",
")",
")",
"else",
":",
"setattr",
"(",
"destination",
",",
"name",
",",
"getattr",
"(",
"source",
",",
"name",
")",
")"
] | Merge all fields specified by a sub-tree from source to destination. | [
"Merge",
"all",
"fields",
"specified",
"by",
"a",
"sub",
"-",
"tree",
"from",
"source",
"to",
"destination",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L633-L671 |
28,831 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _AddFieldPaths | def _AddFieldPaths(node, prefix, field_mask):
"""Adds the field paths descended from node to field_mask."""
if not node:
field_mask.paths.append(prefix)
return
for name in sorted(node):
if prefix:
child_path = prefix + '.' + name
else:
child_path = name
_AddFieldPaths(node[name], child_path, field_mask) | python | def _AddFieldPaths(node, prefix, field_mask):
"""Adds the field paths descended from node to field_mask."""
if not node:
field_mask.paths.append(prefix)
return
for name in sorted(node):
if prefix:
child_path = prefix + '.' + name
else:
child_path = name
_AddFieldPaths(node[name], child_path, field_mask) | [
"def",
"_AddFieldPaths",
"(",
"node",
",",
"prefix",
",",
"field_mask",
")",
":",
"if",
"not",
"node",
":",
"field_mask",
".",
"paths",
".",
"append",
"(",
"prefix",
")",
"return",
"for",
"name",
"in",
"sorted",
"(",
"node",
")",
":",
"if",
"prefix",
":",
"child_path",
"=",
"prefix",
"+",
"'.'",
"+",
"name",
"else",
":",
"child_path",
"=",
"name",
"_AddFieldPaths",
"(",
"node",
"[",
"name",
"]",
",",
"child_path",
",",
"field_mask",
")"
] | Adds the field paths descended from node to field_mask. | [
"Adds",
"the",
"field",
"paths",
"descended",
"from",
"node",
"to",
"field_mask",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L674-L684 |
28,832 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Any.Pack | def Pack(self, msg, type_url_prefix='type.googleapis.com/'):
"""Packs the specified message into current Any message."""
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
else:
self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
self.value = msg.SerializeToString() | python | def Pack(self, msg, type_url_prefix='type.googleapis.com/'):
"""Packs the specified message into current Any message."""
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
else:
self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
self.value = msg.SerializeToString() | [
"def",
"Pack",
"(",
"self",
",",
"msg",
",",
"type_url_prefix",
"=",
"'type.googleapis.com/'",
")",
":",
"if",
"len",
"(",
"type_url_prefix",
")",
"<",
"1",
"or",
"type_url_prefix",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"self",
".",
"type_url",
"=",
"'%s/%s'",
"%",
"(",
"type_url_prefix",
",",
"msg",
".",
"DESCRIPTOR",
".",
"full_name",
")",
"else",
":",
"self",
".",
"type_url",
"=",
"'%s%s'",
"%",
"(",
"type_url_prefix",
",",
"msg",
".",
"DESCRIPTOR",
".",
"full_name",
")",
"self",
".",
"value",
"=",
"msg",
".",
"SerializeToString",
"(",
")"
] | Packs the specified message into current Any message. | [
"Packs",
"the",
"specified",
"message",
"into",
"current",
"Any",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L70-L76 |
28,833 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Any.Unpack | def Unpack(self, msg):
"""Unpacks the current Any message into specified message."""
descriptor = msg.DESCRIPTOR
if not self.Is(descriptor):
return False
msg.ParseFromString(self.value)
return True | python | def Unpack(self, msg):
"""Unpacks the current Any message into specified message."""
descriptor = msg.DESCRIPTOR
if not self.Is(descriptor):
return False
msg.ParseFromString(self.value)
return True | [
"def",
"Unpack",
"(",
"self",
",",
"msg",
")",
":",
"descriptor",
"=",
"msg",
".",
"DESCRIPTOR",
"if",
"not",
"self",
".",
"Is",
"(",
"descriptor",
")",
":",
"return",
"False",
"msg",
".",
"ParseFromString",
"(",
"self",
".",
"value",
")",
"return",
"True"
] | Unpacks the current Any message into specified message. | [
"Unpacks",
"the",
"current",
"Any",
"message",
"into",
"specified",
"message",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L78-L84 |
28,834 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Timestamp.ToJsonString | def ToJsonString(self):
"""Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z'
"""
nanos = self.nanos % _NANOS_PER_SECOND
total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND
seconds = total_sec % _SECONDS_PER_DAY
days = (total_sec - seconds) // _SECONDS_PER_DAY
dt = datetime(1970, 1, 1) + timedelta(days, seconds)
result = dt.isoformat()
if (nanos % 1e9) == 0:
# If there are 0 fractional digits, the fractional
# point '.' should be omitted when serializing.
return result + 'Z'
if (nanos % 1e6) == 0:
# Serialize 3 fractional digits.
return result + '.%03dZ' % (nanos / 1e6)
if (nanos % 1e3) == 0:
# Serialize 6 fractional digits.
return result + '.%06dZ' % (nanos / 1e3)
# Serialize 9 fractional digits.
return result + '.%09dZ' % nanos | python | def ToJsonString(self):
"""Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z'
"""
nanos = self.nanos % _NANOS_PER_SECOND
total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND
seconds = total_sec % _SECONDS_PER_DAY
days = (total_sec - seconds) // _SECONDS_PER_DAY
dt = datetime(1970, 1, 1) + timedelta(days, seconds)
result = dt.isoformat()
if (nanos % 1e9) == 0:
# If there are 0 fractional digits, the fractional
# point '.' should be omitted when serializing.
return result + 'Z'
if (nanos % 1e6) == 0:
# Serialize 3 fractional digits.
return result + '.%03dZ' % (nanos / 1e6)
if (nanos % 1e3) == 0:
# Serialize 6 fractional digits.
return result + '.%06dZ' % (nanos / 1e3)
# Serialize 9 fractional digits.
return result + '.%09dZ' % nanos | [
"def",
"ToJsonString",
"(",
"self",
")",
":",
"nanos",
"=",
"self",
".",
"nanos",
"%",
"_NANOS_PER_SECOND",
"total_sec",
"=",
"self",
".",
"seconds",
"+",
"(",
"self",
".",
"nanos",
"-",
"nanos",
")",
"//",
"_NANOS_PER_SECOND",
"seconds",
"=",
"total_sec",
"%",
"_SECONDS_PER_DAY",
"days",
"=",
"(",
"total_sec",
"-",
"seconds",
")",
"//",
"_SECONDS_PER_DAY",
"dt",
"=",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"+",
"timedelta",
"(",
"days",
",",
"seconds",
")",
"result",
"=",
"dt",
".",
"isoformat",
"(",
")",
"if",
"(",
"nanos",
"%",
"1e9",
")",
"==",
"0",
":",
"# If there are 0 fractional digits, the fractional",
"# point '.' should be omitted when serializing.",
"return",
"result",
"+",
"'Z'",
"if",
"(",
"nanos",
"%",
"1e6",
")",
"==",
"0",
":",
"# Serialize 3 fractional digits.",
"return",
"result",
"+",
"'.%03dZ'",
"%",
"(",
"nanos",
"/",
"1e6",
")",
"if",
"(",
"nanos",
"%",
"1e3",
")",
"==",
"0",
":",
"# Serialize 6 fractional digits.",
"return",
"result",
"+",
"'.%06dZ'",
"%",
"(",
"nanos",
"/",
"1e3",
")",
"# Serialize 9 fractional digits.",
"return",
"result",
"+",
"'.%09dZ'",
"%",
"nanos"
] | Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z' | [
"Converts",
"Timestamp",
"to",
"RFC",
"3339",
"date",
"string",
"format",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L99-L125 |
28,835 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Timestamp.FromJsonString | def FromJsonString(self, value):
"""Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ParseError: On parsing problems.
"""
timezone_offset = value.find('Z')
if timezone_offset == -1:
timezone_offset = value.find('+')
if timezone_offset == -1:
timezone_offset = value.rfind('-')
if timezone_offset == -1:
raise ParseError(
'Failed to parse timestamp: missing valid timezone offset.')
time_value = value[0:timezone_offset]
# Parse datetime and nanos.
point_position = time_value.find('.')
if point_position == -1:
second_value = time_value
nano_value = ''
else:
second_value = time_value[:point_position]
nano_value = time_value[point_position + 1:]
date_object = datetime.strptime(second_value, _TIMESTAMPFOMAT)
td = date_object - datetime(1970, 1, 1)
seconds = td.seconds + td.days * _SECONDS_PER_DAY
if len(nano_value) > 9:
raise ParseError(
'Failed to parse Timestamp: nanos {0} more than '
'9 fractional digits.'.format(nano_value))
if nano_value:
nanos = round(float('0.' + nano_value) * 1e9)
else:
nanos = 0
# Parse timezone offsets.
if value[timezone_offset] == 'Z':
if len(value) != timezone_offset + 1:
raise ParseError('Failed to parse timestamp: invalid trailing'
' data {0}.'.format(value))
else:
timezone = value[timezone_offset:]
pos = timezone.find(':')
if pos == -1:
raise ParseError(
'Invalid timezone offset value: {0}.'.format(timezone))
if timezone[0] == '+':
seconds -= (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
else:
seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
# Set seconds and nanos
self.seconds = int(seconds)
self.nanos = int(nanos) | python | def FromJsonString(self, value):
"""Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ParseError: On parsing problems.
"""
timezone_offset = value.find('Z')
if timezone_offset == -1:
timezone_offset = value.find('+')
if timezone_offset == -1:
timezone_offset = value.rfind('-')
if timezone_offset == -1:
raise ParseError(
'Failed to parse timestamp: missing valid timezone offset.')
time_value = value[0:timezone_offset]
# Parse datetime and nanos.
point_position = time_value.find('.')
if point_position == -1:
second_value = time_value
nano_value = ''
else:
second_value = time_value[:point_position]
nano_value = time_value[point_position + 1:]
date_object = datetime.strptime(second_value, _TIMESTAMPFOMAT)
td = date_object - datetime(1970, 1, 1)
seconds = td.seconds + td.days * _SECONDS_PER_DAY
if len(nano_value) > 9:
raise ParseError(
'Failed to parse Timestamp: nanos {0} more than '
'9 fractional digits.'.format(nano_value))
if nano_value:
nanos = round(float('0.' + nano_value) * 1e9)
else:
nanos = 0
# Parse timezone offsets.
if value[timezone_offset] == 'Z':
if len(value) != timezone_offset + 1:
raise ParseError('Failed to parse timestamp: invalid trailing'
' data {0}.'.format(value))
else:
timezone = value[timezone_offset:]
pos = timezone.find(':')
if pos == -1:
raise ParseError(
'Invalid timezone offset value: {0}.'.format(timezone))
if timezone[0] == '+':
seconds -= (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
else:
seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
# Set seconds and nanos
self.seconds = int(seconds)
self.nanos = int(nanos) | [
"def",
"FromJsonString",
"(",
"self",
",",
"value",
")",
":",
"timezone_offset",
"=",
"value",
".",
"find",
"(",
"'Z'",
")",
"if",
"timezone_offset",
"==",
"-",
"1",
":",
"timezone_offset",
"=",
"value",
".",
"find",
"(",
"'+'",
")",
"if",
"timezone_offset",
"==",
"-",
"1",
":",
"timezone_offset",
"=",
"value",
".",
"rfind",
"(",
"'-'",
")",
"if",
"timezone_offset",
"==",
"-",
"1",
":",
"raise",
"ParseError",
"(",
"'Failed to parse timestamp: missing valid timezone offset.'",
")",
"time_value",
"=",
"value",
"[",
"0",
":",
"timezone_offset",
"]",
"# Parse datetime and nanos.",
"point_position",
"=",
"time_value",
".",
"find",
"(",
"'.'",
")",
"if",
"point_position",
"==",
"-",
"1",
":",
"second_value",
"=",
"time_value",
"nano_value",
"=",
"''",
"else",
":",
"second_value",
"=",
"time_value",
"[",
":",
"point_position",
"]",
"nano_value",
"=",
"time_value",
"[",
"point_position",
"+",
"1",
":",
"]",
"date_object",
"=",
"datetime",
".",
"strptime",
"(",
"second_value",
",",
"_TIMESTAMPFOMAT",
")",
"td",
"=",
"date_object",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"seconds",
"=",
"td",
".",
"seconds",
"+",
"td",
".",
"days",
"*",
"_SECONDS_PER_DAY",
"if",
"len",
"(",
"nano_value",
")",
">",
"9",
":",
"raise",
"ParseError",
"(",
"'Failed to parse Timestamp: nanos {0} more than '",
"'9 fractional digits.'",
".",
"format",
"(",
"nano_value",
")",
")",
"if",
"nano_value",
":",
"nanos",
"=",
"round",
"(",
"float",
"(",
"'0.'",
"+",
"nano_value",
")",
"*",
"1e9",
")",
"else",
":",
"nanos",
"=",
"0",
"# Parse timezone offsets.",
"if",
"value",
"[",
"timezone_offset",
"]",
"==",
"'Z'",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"timezone_offset",
"+",
"1",
":",
"raise",
"ParseError",
"(",
"'Failed to parse timestamp: invalid trailing'",
"' data {0}.'",
".",
"format",
"(",
"value",
")",
")",
"else",
":",
"timezone",
"=",
"value",
"[",
"timezone_offset",
":",
"]",
"pos",
"=",
"timezone",
".",
"find",
"(",
"':'",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"raise",
"ParseError",
"(",
"'Invalid timezone offset value: {0}.'",
".",
"format",
"(",
"timezone",
")",
")",
"if",
"timezone",
"[",
"0",
"]",
"==",
"'+'",
":",
"seconds",
"-=",
"(",
"int",
"(",
"timezone",
"[",
"1",
":",
"pos",
"]",
")",
"*",
"60",
"+",
"int",
"(",
"timezone",
"[",
"pos",
"+",
"1",
":",
"]",
")",
")",
"*",
"60",
"else",
":",
"seconds",
"+=",
"(",
"int",
"(",
"timezone",
"[",
"1",
":",
"pos",
"]",
")",
"*",
"60",
"+",
"int",
"(",
"timezone",
"[",
"pos",
"+",
"1",
":",
"]",
")",
")",
"*",
"60",
"# Set seconds and nanos",
"self",
".",
"seconds",
"=",
"int",
"(",
"seconds",
")",
"self",
".",
"nanos",
"=",
"int",
"(",
"nanos",
")"
] | Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ParseError: On parsing problems. | [
"Parse",
"a",
"RFC",
"3339",
"date",
"string",
"format",
"to",
"Timestamp",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L127-L183 |
28,836 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Timestamp.FromNanoseconds | def FromNanoseconds(self, nanos):
"""Converts nanoseconds since epoch to Timestamp."""
self.seconds = nanos // _NANOS_PER_SECOND
self.nanos = nanos % _NANOS_PER_SECOND | python | def FromNanoseconds(self, nanos):
"""Converts nanoseconds since epoch to Timestamp."""
self.seconds = nanos // _NANOS_PER_SECOND
self.nanos = nanos % _NANOS_PER_SECOND | [
"def",
"FromNanoseconds",
"(",
"self",
",",
"nanos",
")",
":",
"self",
".",
"seconds",
"=",
"nanos",
"//",
"_NANOS_PER_SECOND",
"self",
".",
"nanos",
"=",
"nanos",
"%",
"_NANOS_PER_SECOND"
] | Converts nanoseconds since epoch to Timestamp. | [
"Converts",
"nanoseconds",
"since",
"epoch",
"to",
"Timestamp",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L207-L210 |
28,837 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Timestamp.FromMicroseconds | def FromMicroseconds(self, micros):
"""Converts microseconds since epoch to Timestamp."""
self.seconds = micros // _MICROS_PER_SECOND
self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND | python | def FromMicroseconds(self, micros):
"""Converts microseconds since epoch to Timestamp."""
self.seconds = micros // _MICROS_PER_SECOND
self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND | [
"def",
"FromMicroseconds",
"(",
"self",
",",
"micros",
")",
":",
"self",
".",
"seconds",
"=",
"micros",
"//",
"_MICROS_PER_SECOND",
"self",
".",
"nanos",
"=",
"(",
"micros",
"%",
"_MICROS_PER_SECOND",
")",
"*",
"_NANOS_PER_MICROSECOND"
] | Converts microseconds since epoch to Timestamp. | [
"Converts",
"microseconds",
"since",
"epoch",
"to",
"Timestamp",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L212-L215 |
28,838 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Timestamp.FromMilliseconds | def FromMilliseconds(self, millis):
"""Converts milliseconds since epoch to Timestamp."""
self.seconds = millis // _MILLIS_PER_SECOND
self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND | python | def FromMilliseconds(self, millis):
"""Converts milliseconds since epoch to Timestamp."""
self.seconds = millis // _MILLIS_PER_SECOND
self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND | [
"def",
"FromMilliseconds",
"(",
"self",
",",
"millis",
")",
":",
"self",
".",
"seconds",
"=",
"millis",
"//",
"_MILLIS_PER_SECOND",
"self",
".",
"nanos",
"=",
"(",
"millis",
"%",
"_MILLIS_PER_SECOND",
")",
"*",
"_NANOS_PER_MILLISECOND"
] | Converts milliseconds since epoch to Timestamp. | [
"Converts",
"milliseconds",
"since",
"epoch",
"to",
"Timestamp",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L217-L220 |
28,839 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Timestamp.ToDatetime | def ToDatetime(self):
"""Converts Timestamp to datetime."""
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND)) | python | def ToDatetime(self):
"""Converts Timestamp to datetime."""
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND)) | [
"def",
"ToDatetime",
"(",
"self",
")",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"self",
".",
"seconds",
"+",
"self",
".",
"nanos",
"/",
"float",
"(",
"_NANOS_PER_SECOND",
")",
")"
] | Converts Timestamp to datetime. | [
"Converts",
"Timestamp",
"to",
"datetime",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L227-L230 |
28,840 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Timestamp.FromDatetime | def FromDatetime(self, dt):
"""Converts datetime to Timestamp."""
td = dt - datetime(1970, 1, 1)
self.seconds = td.seconds + td.days * _SECONDS_PER_DAY
self.nanos = td.microseconds * _NANOS_PER_MICROSECOND | python | def FromDatetime(self, dt):
"""Converts datetime to Timestamp."""
td = dt - datetime(1970, 1, 1)
self.seconds = td.seconds + td.days * _SECONDS_PER_DAY
self.nanos = td.microseconds * _NANOS_PER_MICROSECOND | [
"def",
"FromDatetime",
"(",
"self",
",",
"dt",
")",
":",
"td",
"=",
"dt",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"self",
".",
"seconds",
"=",
"td",
".",
"seconds",
"+",
"td",
".",
"days",
"*",
"_SECONDS_PER_DAY",
"self",
".",
"nanos",
"=",
"td",
".",
"microseconds",
"*",
"_NANOS_PER_MICROSECOND"
] | Converts datetime to Timestamp. | [
"Converts",
"datetime",
"to",
"Timestamp",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L232-L236 |
28,841 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Duration.ToMicroseconds | def ToMicroseconds(self):
"""Converts a Duration to microseconds."""
micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)
return self.seconds * _MICROS_PER_SECOND + micros | python | def ToMicroseconds(self):
"""Converts a Duration to microseconds."""
micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)
return self.seconds * _MICROS_PER_SECOND + micros | [
"def",
"ToMicroseconds",
"(",
"self",
")",
":",
"micros",
"=",
"_RoundTowardZero",
"(",
"self",
".",
"nanos",
",",
"_NANOS_PER_MICROSECOND",
")",
"return",
"self",
".",
"seconds",
"*",
"_MICROS_PER_SECOND",
"+",
"micros"
] | Converts a Duration to microseconds. | [
"Converts",
"a",
"Duration",
"to",
"microseconds",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L310-L313 |
28,842 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Duration.ToMilliseconds | def ToMilliseconds(self):
"""Converts a Duration to milliseconds."""
millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND)
return self.seconds * _MILLIS_PER_SECOND + millis | python | def ToMilliseconds(self):
"""Converts a Duration to milliseconds."""
millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND)
return self.seconds * _MILLIS_PER_SECOND + millis | [
"def",
"ToMilliseconds",
"(",
"self",
")",
":",
"millis",
"=",
"_RoundTowardZero",
"(",
"self",
".",
"nanos",
",",
"_NANOS_PER_MILLISECOND",
")",
"return",
"self",
".",
"seconds",
"*",
"_MILLIS_PER_SECOND",
"+",
"millis"
] | Converts a Duration to milliseconds. | [
"Converts",
"a",
"Duration",
"to",
"milliseconds",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L315-L318 |
28,843 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Duration.FromMicroseconds | def FromMicroseconds(self, micros):
"""Converts microseconds to Duration."""
self._NormalizeDuration(
micros // _MICROS_PER_SECOND,
(micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND) | python | def FromMicroseconds(self, micros):
"""Converts microseconds to Duration."""
self._NormalizeDuration(
micros // _MICROS_PER_SECOND,
(micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND) | [
"def",
"FromMicroseconds",
"(",
"self",
",",
"micros",
")",
":",
"self",
".",
"_NormalizeDuration",
"(",
"micros",
"//",
"_MICROS_PER_SECOND",
",",
"(",
"micros",
"%",
"_MICROS_PER_SECOND",
")",
"*",
"_NANOS_PER_MICROSECOND",
")"
] | Converts microseconds to Duration. | [
"Converts",
"microseconds",
"to",
"Duration",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L329-L333 |
28,844 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Duration.FromMilliseconds | def FromMilliseconds(self, millis):
"""Converts milliseconds to Duration."""
self._NormalizeDuration(
millis // _MILLIS_PER_SECOND,
(millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND) | python | def FromMilliseconds(self, millis):
"""Converts milliseconds to Duration."""
self._NormalizeDuration(
millis // _MILLIS_PER_SECOND,
(millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND) | [
"def",
"FromMilliseconds",
"(",
"self",
",",
"millis",
")",
":",
"self",
".",
"_NormalizeDuration",
"(",
"millis",
"//",
"_MILLIS_PER_SECOND",
",",
"(",
"millis",
"%",
"_MILLIS_PER_SECOND",
")",
"*",
"_NANOS_PER_MILLISECOND",
")"
] | Converts milliseconds to Duration. | [
"Converts",
"milliseconds",
"to",
"Duration",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L335-L339 |
28,845 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Duration.ToTimedelta | def ToTimedelta(self):
"""Converts Duration to timedelta."""
return timedelta(
seconds=self.seconds, microseconds=_RoundTowardZero(
self.nanos, _NANOS_PER_MICROSECOND)) | python | def ToTimedelta(self):
"""Converts Duration to timedelta."""
return timedelta(
seconds=self.seconds, microseconds=_RoundTowardZero(
self.nanos, _NANOS_PER_MICROSECOND)) | [
"def",
"ToTimedelta",
"(",
"self",
")",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"seconds",
",",
"microseconds",
"=",
"_RoundTowardZero",
"(",
"self",
".",
"nanos",
",",
"_NANOS_PER_MICROSECOND",
")",
")"
] | Converts Duration to timedelta. | [
"Converts",
"Duration",
"to",
"timedelta",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L346-L350 |
28,846 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Duration.FromTimedelta | def FromTimedelta(self, td):
"""Convertd timedelta to Duration."""
self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY,
td.microseconds * _NANOS_PER_MICROSECOND) | python | def FromTimedelta(self, td):
"""Convertd timedelta to Duration."""
self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY,
td.microseconds * _NANOS_PER_MICROSECOND) | [
"def",
"FromTimedelta",
"(",
"self",
",",
"td",
")",
":",
"self",
".",
"_NormalizeDuration",
"(",
"td",
".",
"seconds",
"+",
"td",
".",
"days",
"*",
"_SECONDS_PER_DAY",
",",
"td",
".",
"microseconds",
"*",
"_NANOS_PER_MICROSECOND",
")"
] | Convertd timedelta to Duration. | [
"Convertd",
"timedelta",
"to",
"Duration",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L352-L355 |
28,847 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | Duration._NormalizeDuration | def _NormalizeDuration(self, seconds, nanos):
"""Set Duration by seconds and nonas."""
# Force nanos to be negative if the duration is negative.
if seconds < 0 and nanos > 0:
seconds += 1
nanos -= _NANOS_PER_SECOND
self.seconds = seconds
self.nanos = nanos | python | def _NormalizeDuration(self, seconds, nanos):
"""Set Duration by seconds and nonas."""
# Force nanos to be negative if the duration is negative.
if seconds < 0 and nanos > 0:
seconds += 1
nanos -= _NANOS_PER_SECOND
self.seconds = seconds
self.nanos = nanos | [
"def",
"_NormalizeDuration",
"(",
"self",
",",
"seconds",
",",
"nanos",
")",
":",
"# Force nanos to be negative if the duration is negative.",
"if",
"seconds",
"<",
"0",
"and",
"nanos",
">",
"0",
":",
"seconds",
"+=",
"1",
"nanos",
"-=",
"_NANOS_PER_SECOND",
"self",
".",
"seconds",
"=",
"seconds",
"self",
".",
"nanos",
"=",
"nanos"
] | Set Duration by seconds and nonas. | [
"Set",
"Duration",
"by",
"seconds",
"and",
"nonas",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L357-L364 |
28,848 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | FieldMask.ToJsonString | def ToJsonString(self):
"""Converts FieldMask to string according to proto3 JSON spec."""
camelcase_paths = []
for path in self.paths:
camelcase_paths.append(_SnakeCaseToCamelCase(path))
return ','.join(camelcase_paths) | python | def ToJsonString(self):
"""Converts FieldMask to string according to proto3 JSON spec."""
camelcase_paths = []
for path in self.paths:
camelcase_paths.append(_SnakeCaseToCamelCase(path))
return ','.join(camelcase_paths) | [
"def",
"ToJsonString",
"(",
"self",
")",
":",
"camelcase_paths",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"paths",
":",
"camelcase_paths",
".",
"append",
"(",
"_SnakeCaseToCamelCase",
"(",
"path",
")",
")",
"return",
"','",
".",
"join",
"(",
"camelcase_paths",
")"
] | Converts FieldMask to string according to proto3 JSON spec. | [
"Converts",
"FieldMask",
"to",
"string",
"according",
"to",
"proto3",
"JSON",
"spec",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L396-L401 |
28,849 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | FieldMask.IsValidForDescriptor | def IsValidForDescriptor(self, message_descriptor):
"""Checks whether the FieldMask is valid for Message Descriptor."""
for path in self.paths:
if not _IsValidPath(message_descriptor, path):
return False
return True | python | def IsValidForDescriptor(self, message_descriptor):
"""Checks whether the FieldMask is valid for Message Descriptor."""
for path in self.paths:
if not _IsValidPath(message_descriptor, path):
return False
return True | [
"def",
"IsValidForDescriptor",
"(",
"self",
",",
"message_descriptor",
")",
":",
"for",
"path",
"in",
"self",
".",
"paths",
":",
"if",
"not",
"_IsValidPath",
"(",
"message_descriptor",
",",
"path",
")",
":",
"return",
"False",
"return",
"True"
] | Checks whether the FieldMask is valid for Message Descriptor. | [
"Checks",
"whether",
"the",
"FieldMask",
"is",
"valid",
"for",
"Message",
"Descriptor",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L409-L414 |
28,850 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | FieldMask.AllFieldsFromDescriptor | def AllFieldsFromDescriptor(self, message_descriptor):
"""Gets all direct fields of Message Descriptor to FieldMask."""
self.Clear()
for field in message_descriptor.fields:
self.paths.append(field.name) | python | def AllFieldsFromDescriptor(self, message_descriptor):
"""Gets all direct fields of Message Descriptor to FieldMask."""
self.Clear()
for field in message_descriptor.fields:
self.paths.append(field.name) | [
"def",
"AllFieldsFromDescriptor",
"(",
"self",
",",
"message_descriptor",
")",
":",
"self",
".",
"Clear",
"(",
")",
"for",
"field",
"in",
"message_descriptor",
".",
"fields",
":",
"self",
".",
"paths",
".",
"append",
"(",
"field",
".",
"name",
")"
] | Gets all direct fields of Message Descriptor to FieldMask. | [
"Gets",
"all",
"direct",
"fields",
"of",
"Message",
"Descriptor",
"to",
"FieldMask",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L416-L420 |
28,851 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | FieldMask.Union | def Union(self, mask1, mask2):
"""Merges mask1 and mask2 into this FieldMask."""
_CheckFieldMaskMessage(mask1)
_CheckFieldMaskMessage(mask2)
tree = _FieldMaskTree(mask1)
tree.MergeFromFieldMask(mask2)
tree.ToFieldMask(self) | python | def Union(self, mask1, mask2):
"""Merges mask1 and mask2 into this FieldMask."""
_CheckFieldMaskMessage(mask1)
_CheckFieldMaskMessage(mask2)
tree = _FieldMaskTree(mask1)
tree.MergeFromFieldMask(mask2)
tree.ToFieldMask(self) | [
"def",
"Union",
"(",
"self",
",",
"mask1",
",",
"mask2",
")",
":",
"_CheckFieldMaskMessage",
"(",
"mask1",
")",
"_CheckFieldMaskMessage",
"(",
"mask2",
")",
"tree",
"=",
"_FieldMaskTree",
"(",
"mask1",
")",
"tree",
".",
"MergeFromFieldMask",
"(",
"mask2",
")",
"tree",
".",
"ToFieldMask",
"(",
"self",
")"
] | Merges mask1 and mask2 into this FieldMask. | [
"Merges",
"mask1",
"and",
"mask2",
"into",
"this",
"FieldMask",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L435-L441 |
28,852 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | FieldMask.Intersect | def Intersect(self, mask1, mask2):
"""Intersects mask1 and mask2 into this FieldMask."""
_CheckFieldMaskMessage(mask1)
_CheckFieldMaskMessage(mask2)
tree = _FieldMaskTree(mask1)
intersection = _FieldMaskTree()
for path in mask2.paths:
tree.IntersectPath(path, intersection)
intersection.ToFieldMask(self) | python | def Intersect(self, mask1, mask2):
"""Intersects mask1 and mask2 into this FieldMask."""
_CheckFieldMaskMessage(mask1)
_CheckFieldMaskMessage(mask2)
tree = _FieldMaskTree(mask1)
intersection = _FieldMaskTree()
for path in mask2.paths:
tree.IntersectPath(path, intersection)
intersection.ToFieldMask(self) | [
"def",
"Intersect",
"(",
"self",
",",
"mask1",
",",
"mask2",
")",
":",
"_CheckFieldMaskMessage",
"(",
"mask1",
")",
"_CheckFieldMaskMessage",
"(",
"mask2",
")",
"tree",
"=",
"_FieldMaskTree",
"(",
"mask1",
")",
"intersection",
"=",
"_FieldMaskTree",
"(",
")",
"for",
"path",
"in",
"mask2",
".",
"paths",
":",
"tree",
".",
"IntersectPath",
"(",
"path",
",",
"intersection",
")",
"intersection",
".",
"ToFieldMask",
"(",
"self",
")"
] | Intersects mask1 and mask2 into this FieldMask. | [
"Intersects",
"mask1",
"and",
"mask2",
"into",
"this",
"FieldMask",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L443-L451 |
28,853 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | FieldMask.MergeMessage | def MergeMessage(
self, source, destination,
replace_message_field=False, replace_repeated_field=False):
"""Merges fields specified in FieldMask from source to destination.
Args:
source: Source message.
destination: The destination message to be merged into.
replace_message_field: Replace message field if True. Merge message
field if False.
replace_repeated_field: Replace repeated field if True. Append
elements of repeated field if False.
"""
tree = _FieldMaskTree(self)
tree.MergeMessage(
source, destination, replace_message_field, replace_repeated_field) | python | def MergeMessage(
self, source, destination,
replace_message_field=False, replace_repeated_field=False):
"""Merges fields specified in FieldMask from source to destination.
Args:
source: Source message.
destination: The destination message to be merged into.
replace_message_field: Replace message field if True. Merge message
field if False.
replace_repeated_field: Replace repeated field if True. Append
elements of repeated field if False.
"""
tree = _FieldMaskTree(self)
tree.MergeMessage(
source, destination, replace_message_field, replace_repeated_field) | [
"def",
"MergeMessage",
"(",
"self",
",",
"source",
",",
"destination",
",",
"replace_message_field",
"=",
"False",
",",
"replace_repeated_field",
"=",
"False",
")",
":",
"tree",
"=",
"_FieldMaskTree",
"(",
"self",
")",
"tree",
".",
"MergeMessage",
"(",
"source",
",",
"destination",
",",
"replace_message_field",
",",
"replace_repeated_field",
")"
] | Merges fields specified in FieldMask from source to destination.
Args:
source: Source message.
destination: The destination message to be merged into.
replace_message_field: Replace message field if True. Merge message
field if False.
replace_repeated_field: Replace repeated field if True. Append
elements of repeated field if False. | [
"Merges",
"fields",
"specified",
"in",
"FieldMask",
"from",
"source",
"to",
"destination",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L453-L468 |
28,854 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _FieldMaskTree.AddPath | def AddPath(self, path):
"""Adds a field path into the tree.
If the field path to add is a sub-path of an existing field path
in the tree (i.e., a leaf node), it means the tree already matches
the given path so nothing will be added to the tree. If the path
matches an existing non-leaf node in the tree, that non-leaf node
will be turned into a leaf node with all its children removed because
the path matches all the node's children. Otherwise, a new path will
be added.
Args:
path: The field path to add.
"""
node = self._root
for name in path.split('.'):
if name not in node:
node[name] = {}
elif not node[name]:
# Pre-existing empty node implies we already have this entire tree.
return
node = node[name]
# Remove any sub-trees we might have had.
node.clear() | python | def AddPath(self, path):
"""Adds a field path into the tree.
If the field path to add is a sub-path of an existing field path
in the tree (i.e., a leaf node), it means the tree already matches
the given path so nothing will be added to the tree. If the path
matches an existing non-leaf node in the tree, that non-leaf node
will be turned into a leaf node with all its children removed because
the path matches all the node's children. Otherwise, a new path will
be added.
Args:
path: The field path to add.
"""
node = self._root
for name in path.split('.'):
if name not in node:
node[name] = {}
elif not node[name]:
# Pre-existing empty node implies we already have this entire tree.
return
node = node[name]
# Remove any sub-trees we might have had.
node.clear() | [
"def",
"AddPath",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"_root",
"for",
"name",
"in",
"path",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"name",
"not",
"in",
"node",
":",
"node",
"[",
"name",
"]",
"=",
"{",
"}",
"elif",
"not",
"node",
"[",
"name",
"]",
":",
"# Pre-existing empty node implies we already have this entire tree.",
"return",
"node",
"=",
"node",
"[",
"name",
"]",
"# Remove any sub-trees we might have had.",
"node",
".",
"clear",
"(",
")"
] | Adds a field path into the tree.
If the field path to add is a sub-path of an existing field path
in the tree (i.e., a leaf node), it means the tree already matches
the given path so nothing will be added to the tree. If the path
matches an existing non-leaf node in the tree, that non-leaf node
will be turned into a leaf node with all its children removed because
the path matches all the node's children. Otherwise, a new path will
be added.
Args:
path: The field path to add. | [
"Adds",
"a",
"field",
"path",
"into",
"the",
"tree",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L560-L583 |
28,855 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _FieldMaskTree.IntersectPath | def IntersectPath(self, path, intersection):
"""Calculates the intersection part of a field path with this tree.
Args:
path: The field path to calculates.
intersection: The out tree to record the intersection part.
"""
node = self._root
for name in path.split('.'):
if name not in node:
return
elif not node[name]:
intersection.AddPath(path)
return
node = node[name]
intersection.AddLeafNodes(path, node) | python | def IntersectPath(self, path, intersection):
"""Calculates the intersection part of a field path with this tree.
Args:
path: The field path to calculates.
intersection: The out tree to record the intersection part.
"""
node = self._root
for name in path.split('.'):
if name not in node:
return
elif not node[name]:
intersection.AddPath(path)
return
node = node[name]
intersection.AddLeafNodes(path, node) | [
"def",
"IntersectPath",
"(",
"self",
",",
"path",
",",
"intersection",
")",
":",
"node",
"=",
"self",
".",
"_root",
"for",
"name",
"in",
"path",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"name",
"not",
"in",
"node",
":",
"return",
"elif",
"not",
"node",
"[",
"name",
"]",
":",
"intersection",
".",
"AddPath",
"(",
"path",
")",
"return",
"node",
"=",
"node",
"[",
"name",
"]",
"intersection",
".",
"AddLeafNodes",
"(",
"path",
",",
"node",
")"
] | Calculates the intersection part of a field path with this tree.
Args:
path: The field path to calculates.
intersection: The out tree to record the intersection part. | [
"Calculates",
"the",
"intersection",
"part",
"of",
"a",
"field",
"path",
"with",
"this",
"tree",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L590-L605 |
28,856 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _FieldMaskTree.AddLeafNodes | def AddLeafNodes(self, prefix, node):
"""Adds leaf nodes begin with prefix to this tree."""
if not node:
self.AddPath(prefix)
for name in node:
child_path = prefix + '.' + name
self.AddLeafNodes(child_path, node[name]) | python | def AddLeafNodes(self, prefix, node):
"""Adds leaf nodes begin with prefix to this tree."""
if not node:
self.AddPath(prefix)
for name in node:
child_path = prefix + '.' + name
self.AddLeafNodes(child_path, node[name]) | [
"def",
"AddLeafNodes",
"(",
"self",
",",
"prefix",
",",
"node",
")",
":",
"if",
"not",
"node",
":",
"self",
".",
"AddPath",
"(",
"prefix",
")",
"for",
"name",
"in",
"node",
":",
"child_path",
"=",
"prefix",
"+",
"'.'",
"+",
"name",
"self",
".",
"AddLeafNodes",
"(",
"child_path",
",",
"node",
"[",
"name",
"]",
")"
] | Adds leaf nodes begin with prefix to this tree. | [
"Adds",
"leaf",
"nodes",
"begin",
"with",
"prefix",
"to",
"this",
"tree",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L607-L613 |
28,857 | apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | _FieldMaskTree.MergeMessage | def MergeMessage(
self, source, destination,
replace_message, replace_repeated):
"""Merge all fields specified by this tree from source to destination."""
_MergeMessage(
self._root, source, destination, replace_message, replace_repeated) | python | def MergeMessage(
self, source, destination,
replace_message, replace_repeated):
"""Merge all fields specified by this tree from source to destination."""
_MergeMessage(
self._root, source, destination, replace_message, replace_repeated) | [
"def",
"MergeMessage",
"(",
"self",
",",
"source",
",",
"destination",
",",
"replace_message",
",",
"replace_repeated",
")",
":",
"_MergeMessage",
"(",
"self",
".",
"_root",
",",
"source",
",",
"destination",
",",
"replace_message",
",",
"replace_repeated",
")"
] | Merge all fields specified by this tree from source to destination. | [
"Merge",
"all",
"fields",
"specified",
"by",
"this",
"tree",
"from",
"source",
"to",
"destination",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L615-L620 |
28,858 | apple/turicreate | src/unity/python/turicreate/toolkits/regression/linear_regression.py | LinearRegression.predict | def predict(self, dataset, missing_value_action='auto'):
"""
Return target value predictions for ``dataset``, using the trained
linear regression model. This method can be used to get fitted values
for the model by inputting the training dataset.
Parameters
----------
dataset : SFrame | pandas.Dataframe
Dataset of new observations. Must include columns with the same
names as the features used for model training, but does not require
a target column. Additional columns are ignored.
missing_value_action : str, optional
Action to perform when missing values are encountered. This can be
one of:
- 'auto': Default to 'impute'
- 'impute': Proceed with evaluation by filling in the missing
values with the mean of the training data. Missing
values are also imputed if an entire column of data is
missing during evaluation.
- 'error': Do not proceed with prediction and terminate with
an error message.
Returns
-------
out : SArray
Predicted target value for each example (i.e. row) in the dataset.
See Also
----------
create, evaluate
Examples
----------
>>> data = turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv')
>>> model = turicreate.linear_regression.create(data,
target='price',
features=['bath', 'bedroom', 'size'])
>>> results = model.predict(data)
"""
return super(LinearRegression, self).predict(dataset, missing_value_action=missing_value_action) | python | def predict(self, dataset, missing_value_action='auto'):
"""
Return target value predictions for ``dataset``, using the trained
linear regression model. This method can be used to get fitted values
for the model by inputting the training dataset.
Parameters
----------
dataset : SFrame | pandas.Dataframe
Dataset of new observations. Must include columns with the same
names as the features used for model training, but does not require
a target column. Additional columns are ignored.
missing_value_action : str, optional
Action to perform when missing values are encountered. This can be
one of:
- 'auto': Default to 'impute'
- 'impute': Proceed with evaluation by filling in the missing
values with the mean of the training data. Missing
values are also imputed if an entire column of data is
missing during evaluation.
- 'error': Do not proceed with prediction and terminate with
an error message.
Returns
-------
out : SArray
Predicted target value for each example (i.e. row) in the dataset.
See Also
----------
create, evaluate
Examples
----------
>>> data = turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv')
>>> model = turicreate.linear_regression.create(data,
target='price',
features=['bath', 'bedroom', 'size'])
>>> results = model.predict(data)
"""
return super(LinearRegression, self).predict(dataset, missing_value_action=missing_value_action) | [
"def",
"predict",
"(",
"self",
",",
"dataset",
",",
"missing_value_action",
"=",
"'auto'",
")",
":",
"return",
"super",
"(",
"LinearRegression",
",",
"self",
")",
".",
"predict",
"(",
"dataset",
",",
"missing_value_action",
"=",
"missing_value_action",
")"
] | Return target value predictions for ``dataset``, using the trained
linear regression model. This method can be used to get fitted values
for the model by inputting the training dataset.
Parameters
----------
dataset : SFrame | pandas.Dataframe
Dataset of new observations. Must include columns with the same
names as the features used for model training, but does not require
a target column. Additional columns are ignored.
missing_value_action : str, optional
Action to perform when missing values are encountered. This can be
one of:
- 'auto': Default to 'impute'
- 'impute': Proceed with evaluation by filling in the missing
values with the mean of the training data. Missing
values are also imputed if an entire column of data is
missing during evaluation.
- 'error': Do not proceed with prediction and terminate with
an error message.
Returns
-------
out : SArray
Predicted target value for each example (i.e. row) in the dataset.
See Also
----------
create, evaluate
Examples
----------
>>> data = turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv')
>>> model = turicreate.linear_regression.create(data,
target='price',
features=['bath', 'bedroom', 'size'])
>>> results = model.predict(data) | [
"Return",
"target",
"value",
"predictions",
"for",
"dataset",
"using",
"the",
"trained",
"linear",
"regression",
"model",
".",
"This",
"method",
"can",
"be",
"used",
"to",
"get",
"fitted",
"values",
"for",
"the",
"model",
"by",
"inputting",
"the",
"training",
"dataset",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/regression/linear_regression.py#L519-L564 |
28,859 | apple/turicreate | src/unity/python/turicreate/toolkits/regression/linear_regression.py | LinearRegression.evaluate | def evaluate(self, dataset, metric='auto', missing_value_action='auto'):
r"""Evaluate the model by making target value predictions and comparing
to actual values.
Two metrics are used to evaluate linear regression models. The first
is root-mean-squared error (RMSE) while the second is the absolute
value of the maximum error between the actual and predicted values.
Let :math:`y` and :math:`\hat{y}` denote vectors of length :math:`N`
(number of examples) with actual and predicted values. The RMSE is
defined as:
.. math::
RMSE = \sqrt{\frac{1}{N} \sum_{i=1}^N (\widehat{y}_i - y_i)^2}
while the max-error is defined as
.. math::
max-error = \max_{i=1}^N \|\widehat{y}_i - y_i\|
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the target and features used for model training. Additional
columns are ignored.
metric : str, optional
Name of the evaluation metric. Possible values are:
- 'auto': Compute all metrics.
- 'rmse': Rooted mean squared error.
- 'max_error': Maximum error.
missing_value_action : str, optional
Action to perform when missing values are encountered. This can be
one of:
- 'auto': Default to 'impute'
- 'impute': Proceed with evaluation by filling in the missing
values with the mean of the training data. Missing
values are also imputed if an entire column of data is
missing during evaluation.
- 'error': Do not proceed with evaluation and terminate with
an error message.
Returns
-------
out : dict
Results from model evaluation procedure.
See Also
----------
create, predict
Examples
----------
>>> data = turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv')
>>> model = turicreate.linear_regression.create(data,
target='price',
features=['bath', 'bedroom', 'size'])
>>> results = model.evaluate(data)
"""
_raise_error_evaluation_metric_is_valid(metric,
['auto', 'rmse', 'max_error'])
return super(LinearRegression, self).evaluate(dataset, missing_value_action=missing_value_action,
metric=metric) | python | def evaluate(self, dataset, metric='auto', missing_value_action='auto'):
r"""Evaluate the model by making target value predictions and comparing
to actual values.
Two metrics are used to evaluate linear regression models. The first
is root-mean-squared error (RMSE) while the second is the absolute
value of the maximum error between the actual and predicted values.
Let :math:`y` and :math:`\hat{y}` denote vectors of length :math:`N`
(number of examples) with actual and predicted values. The RMSE is
defined as:
.. math::
RMSE = \sqrt{\frac{1}{N} \sum_{i=1}^N (\widehat{y}_i - y_i)^2}
while the max-error is defined as
.. math::
max-error = \max_{i=1}^N \|\widehat{y}_i - y_i\|
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the target and features used for model training. Additional
columns are ignored.
metric : str, optional
Name of the evaluation metric. Possible values are:
- 'auto': Compute all metrics.
- 'rmse': Rooted mean squared error.
- 'max_error': Maximum error.
missing_value_action : str, optional
Action to perform when missing values are encountered. This can be
one of:
- 'auto': Default to 'impute'
- 'impute': Proceed with evaluation by filling in the missing
values with the mean of the training data. Missing
values are also imputed if an entire column of data is
missing during evaluation.
- 'error': Do not proceed with evaluation and terminate with
an error message.
Returns
-------
out : dict
Results from model evaluation procedure.
See Also
----------
create, predict
Examples
----------
>>> data = turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv')
>>> model = turicreate.linear_regression.create(data,
target='price',
features=['bath', 'bedroom', 'size'])
>>> results = model.evaluate(data)
"""
_raise_error_evaluation_metric_is_valid(metric,
['auto', 'rmse', 'max_error'])
return super(LinearRegression, self).evaluate(dataset, missing_value_action=missing_value_action,
metric=metric) | [
"def",
"evaluate",
"(",
"self",
",",
"dataset",
",",
"metric",
"=",
"'auto'",
",",
"missing_value_action",
"=",
"'auto'",
")",
":",
"_raise_error_evaluation_metric_is_valid",
"(",
"metric",
",",
"[",
"'auto'",
",",
"'rmse'",
",",
"'max_error'",
"]",
")",
"return",
"super",
"(",
"LinearRegression",
",",
"self",
")",
".",
"evaluate",
"(",
"dataset",
",",
"missing_value_action",
"=",
"missing_value_action",
",",
"metric",
"=",
"metric",
")"
] | r"""Evaluate the model by making target value predictions and comparing
to actual values.
Two metrics are used to evaluate linear regression models. The first
is root-mean-squared error (RMSE) while the second is the absolute
value of the maximum error between the actual and predicted values.
Let :math:`y` and :math:`\hat{y}` denote vectors of length :math:`N`
(number of examples) with actual and predicted values. The RMSE is
defined as:
.. math::
RMSE = \sqrt{\frac{1}{N} \sum_{i=1}^N (\widehat{y}_i - y_i)^2}
while the max-error is defined as
.. math::
max-error = \max_{i=1}^N \|\widehat{y}_i - y_i\|
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the target and features used for model training. Additional
columns are ignored.
metric : str, optional
Name of the evaluation metric. Possible values are:
- 'auto': Compute all metrics.
- 'rmse': Rooted mean squared error.
- 'max_error': Maximum error.
missing_value_action : str, optional
Action to perform when missing values are encountered. This can be
one of:
- 'auto': Default to 'impute'
- 'impute': Proceed with evaluation by filling in the missing
values with the mean of the training data. Missing
values are also imputed if an entire column of data is
missing during evaluation.
- 'error': Do not proceed with evaluation and terminate with
an error message.
Returns
-------
out : dict
Results from model evaluation procedure.
See Also
----------
create, predict
Examples
----------
>>> data = turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv')
>>> model = turicreate.linear_regression.create(data,
target='price',
features=['bath', 'bedroom', 'size'])
>>> results = model.evaluate(data) | [
"r",
"Evaluate",
"the",
"model",
"by",
"making",
"target",
"value",
"predictions",
"and",
"comparing",
"to",
"actual",
"values",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/regression/linear_regression.py#L567-L635 |
28,860 | apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py | frame | def frame(data, window_length, hop_length):
"""Convert array into a sequence of successive possibly overlapping frames.
An n-dimensional array of shape (num_samples, ...) is converted into an
(n+1)-D array of shape (num_frames, window_length, ...), where each frame
starts hop_length points after the preceding one.
This is accomplished using stride_tricks, so the original data is not
copied. However, there is no zero-padding, so any incomplete frames at the
end are not included.
Args:
data: np.array of dimension N >= 1.
window_length: Number of samples in each frame.
hop_length: Advance (in samples) between each window.
Returns:
(N+1)-D np.array with as many rows as there are complete frames that can be
extracted.
"""
num_samples = data.shape[0]
num_frames = 1 + int(np.floor((num_samples - window_length) / hop_length))
shape = (num_frames, window_length) + data.shape[1:]
strides = (data.strides[0] * hop_length,) + data.strides
return np.lib.stride_tricks.as_strided(data, shape=shape, strides=strides) | python | def frame(data, window_length, hop_length):
"""Convert array into a sequence of successive possibly overlapping frames.
An n-dimensional array of shape (num_samples, ...) is converted into an
(n+1)-D array of shape (num_frames, window_length, ...), where each frame
starts hop_length points after the preceding one.
This is accomplished using stride_tricks, so the original data is not
copied. However, there is no zero-padding, so any incomplete frames at the
end are not included.
Args:
data: np.array of dimension N >= 1.
window_length: Number of samples in each frame.
hop_length: Advance (in samples) between each window.
Returns:
(N+1)-D np.array with as many rows as there are complete frames that can be
extracted.
"""
num_samples = data.shape[0]
num_frames = 1 + int(np.floor((num_samples - window_length) / hop_length))
shape = (num_frames, window_length) + data.shape[1:]
strides = (data.strides[0] * hop_length,) + data.strides
return np.lib.stride_tricks.as_strided(data, shape=shape, strides=strides) | [
"def",
"frame",
"(",
"data",
",",
"window_length",
",",
"hop_length",
")",
":",
"num_samples",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"num_frames",
"=",
"1",
"+",
"int",
"(",
"np",
".",
"floor",
"(",
"(",
"num_samples",
"-",
"window_length",
")",
"/",
"hop_length",
")",
")",
"shape",
"=",
"(",
"num_frames",
",",
"window_length",
")",
"+",
"data",
".",
"shape",
"[",
"1",
":",
"]",
"strides",
"=",
"(",
"data",
".",
"strides",
"[",
"0",
"]",
"*",
"hop_length",
",",
")",
"+",
"data",
".",
"strides",
"return",
"np",
".",
"lib",
".",
"stride_tricks",
".",
"as_strided",
"(",
"data",
",",
"shape",
"=",
"shape",
",",
"strides",
"=",
"strides",
")"
] | Convert array into a sequence of successive possibly overlapping frames.
An n-dimensional array of shape (num_samples, ...) is converted into an
(n+1)-D array of shape (num_frames, window_length, ...), where each frame
starts hop_length points after the preceding one.
This is accomplished using stride_tricks, so the original data is not
copied. However, there is no zero-padding, so any incomplete frames at the
end are not included.
Args:
data: np.array of dimension N >= 1.
window_length: Number of samples in each frame.
hop_length: Advance (in samples) between each window.
Returns:
(N+1)-D np.array with as many rows as there are complete frames that can be
extracted. | [
"Convert",
"array",
"into",
"a",
"sequence",
"of",
"successive",
"possibly",
"overlapping",
"frames",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py#L21-L45 |
28,861 | apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py | periodic_hann | def periodic_hann(window_length):
"""Calculate a "periodic" Hann window.
The classic Hann window is defined as a raised cosine that starts and
ends on zero, and where every value appears twice, except the middle
point for an odd-length window. Matlab calls this a "symmetric" window
and np.hanning() returns it. However, for Fourier analysis, this
actually represents just over one cycle of a period N-1 cosine, and
thus is not compactly expressed on a length-N Fourier basis. Instead,
it's better to use a raised cosine that ends just before the final
zero value - i.e. a complete cycle of a period-N cosine. Matlab
calls this a "periodic" window. This routine calculates it.
Args:
window_length: The number of points in the returned window.
Returns:
A 1D np.array containing the periodic hann window.
"""
return 0.5 - (0.5 * np.cos(2 * np.pi / window_length *
np.arange(window_length))) | python | def periodic_hann(window_length):
"""Calculate a "periodic" Hann window.
The classic Hann window is defined as a raised cosine that starts and
ends on zero, and where every value appears twice, except the middle
point for an odd-length window. Matlab calls this a "symmetric" window
and np.hanning() returns it. However, for Fourier analysis, this
actually represents just over one cycle of a period N-1 cosine, and
thus is not compactly expressed on a length-N Fourier basis. Instead,
it's better to use a raised cosine that ends just before the final
zero value - i.e. a complete cycle of a period-N cosine. Matlab
calls this a "periodic" window. This routine calculates it.
Args:
window_length: The number of points in the returned window.
Returns:
A 1D np.array containing the periodic hann window.
"""
return 0.5 - (0.5 * np.cos(2 * np.pi / window_length *
np.arange(window_length))) | [
"def",
"periodic_hann",
"(",
"window_length",
")",
":",
"return",
"0.5",
"-",
"(",
"0.5",
"*",
"np",
".",
"cos",
"(",
"2",
"*",
"np",
".",
"pi",
"/",
"window_length",
"*",
"np",
".",
"arange",
"(",
"window_length",
")",
")",
")"
] | Calculate a "periodic" Hann window.
The classic Hann window is defined as a raised cosine that starts and
ends on zero, and where every value appears twice, except the middle
point for an odd-length window. Matlab calls this a "symmetric" window
and np.hanning() returns it. However, for Fourier analysis, this
actually represents just over one cycle of a period N-1 cosine, and
thus is not compactly expressed on a length-N Fourier basis. Instead,
it's better to use a raised cosine that ends just before the final
zero value - i.e. a complete cycle of a period-N cosine. Matlab
calls this a "periodic" window. This routine calculates it.
Args:
window_length: The number of points in the returned window.
Returns:
A 1D np.array containing the periodic hann window. | [
"Calculate",
"a",
"periodic",
"Hann",
"window",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py#L48-L68 |
28,862 | apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py | stft_magnitude | def stft_magnitude(signal, fft_length,
hop_length=None,
window_length=None):
"""Calculate the short-time Fourier transform magnitude.
Args:
signal: 1D np.array of the input time-domain signal.
fft_length: Size of the FFT to apply.
hop_length: Advance (in samples) between each frame passed to FFT.
window_length: Length of each block of samples to pass to FFT.
Returns:
2D np.array where each row contains the magnitudes of the fft_length/2+1
unique values of the FFT for the corresponding frame of input samples.
"""
frames = frame(signal, window_length, hop_length)
# Apply frame window to each frame. We use a periodic Hann (cosine of period
# window_length) instead of the symmetric Hann of np.hanning (period
# window_length-1).
window = periodic_hann(window_length)
windowed_frames = frames * window
return np.abs(np.fft.rfft(windowed_frames, int(fft_length))) | python | def stft_magnitude(signal, fft_length,
hop_length=None,
window_length=None):
"""Calculate the short-time Fourier transform magnitude.
Args:
signal: 1D np.array of the input time-domain signal.
fft_length: Size of the FFT to apply.
hop_length: Advance (in samples) between each frame passed to FFT.
window_length: Length of each block of samples to pass to FFT.
Returns:
2D np.array where each row contains the magnitudes of the fft_length/2+1
unique values of the FFT for the corresponding frame of input samples.
"""
frames = frame(signal, window_length, hop_length)
# Apply frame window to each frame. We use a periodic Hann (cosine of period
# window_length) instead of the symmetric Hann of np.hanning (period
# window_length-1).
window = periodic_hann(window_length)
windowed_frames = frames * window
return np.abs(np.fft.rfft(windowed_frames, int(fft_length))) | [
"def",
"stft_magnitude",
"(",
"signal",
",",
"fft_length",
",",
"hop_length",
"=",
"None",
",",
"window_length",
"=",
"None",
")",
":",
"frames",
"=",
"frame",
"(",
"signal",
",",
"window_length",
",",
"hop_length",
")",
"# Apply frame window to each frame. We use a periodic Hann (cosine of period",
"# window_length) instead of the symmetric Hann of np.hanning (period",
"# window_length-1).",
"window",
"=",
"periodic_hann",
"(",
"window_length",
")",
"windowed_frames",
"=",
"frames",
"*",
"window",
"return",
"np",
".",
"abs",
"(",
"np",
".",
"fft",
".",
"rfft",
"(",
"windowed_frames",
",",
"int",
"(",
"fft_length",
")",
")",
")"
] | Calculate the short-time Fourier transform magnitude.
Args:
signal: 1D np.array of the input time-domain signal.
fft_length: Size of the FFT to apply.
hop_length: Advance (in samples) between each frame passed to FFT.
window_length: Length of each block of samples to pass to FFT.
Returns:
2D np.array where each row contains the magnitudes of the fft_length/2+1
unique values of the FFT for the corresponding frame of input samples. | [
"Calculate",
"the",
"short",
"-",
"time",
"Fourier",
"transform",
"magnitude",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py#L71-L92 |
28,863 | apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py | spectrogram_to_mel_matrix | def spectrogram_to_mel_matrix(num_mel_bins=20,
num_spectrogram_bins=129,
audio_sample_rate=8000,
lower_edge_hertz=125.0,
upper_edge_hertz=3800.0):
"""Return a matrix that can post-multiply spectrogram rows to make mel.
Returns a np.array matrix A that can be used to post-multiply a matrix S of
spectrogram values (STFT magnitudes) arranged as frames x bins to generate a
"mel spectrogram" M of frames x num_mel_bins. M = S A.
The classic HTK algorithm exploits the complementarity of adjacent mel bands
to multiply each FFT bin by only one mel weight, then add it, with positive
and negative signs, to the two adjacent mel bands to which that bin
contributes. Here, by expressing this operation as a matrix multiply, we go
from num_fft multiplies per frame (plus around 2*num_fft adds) to around
num_fft^2 multiplies and adds. However, because these are all presumably
accomplished in a single call to np.dot(), it's not clear which approach is
faster in Python. The matrix multiplication has the attraction of being more
general and flexible, and much easier to read.
Args:
num_mel_bins: How many bands in the resulting mel spectrum. This is
the number of columns in the output matrix.
num_spectrogram_bins: How many bins there are in the source spectrogram
data, which is understood to be fft_size/2 + 1, i.e. the spectrogram
only contains the nonredundant FFT bins.
audio_sample_rate: Samples per second of the audio at the input to the
spectrogram. We need this to figure out the actual frequencies for
each spectrogram bin, which dictates how they are mapped into mel.
lower_edge_hertz: Lower bound on the frequencies to be included in the mel
spectrum. This corresponds to the lower edge of the lowest triangular
band.
upper_edge_hertz: The desired top edge of the highest frequency band.
Returns:
An np.array with shape (num_spectrogram_bins, num_mel_bins).
Raises:
ValueError: if frequency edges are incorrectly ordered or out of range.
"""
nyquist_hertz = audio_sample_rate / 2.
if lower_edge_hertz < 0.0:
raise ValueError("lower_edge_hertz %.1f must be >= 0" % lower_edge_hertz)
if lower_edge_hertz >= upper_edge_hertz:
raise ValueError("lower_edge_hertz %.1f >= upper_edge_hertz %.1f" %
(lower_edge_hertz, upper_edge_hertz))
if upper_edge_hertz > nyquist_hertz:
raise ValueError("upper_edge_hertz %.1f is greater than Nyquist %.1f" %
(upper_edge_hertz, nyquist_hertz))
spectrogram_bins_hertz = np.linspace(0.0, nyquist_hertz, num_spectrogram_bins)
spectrogram_bins_mel = hertz_to_mel(spectrogram_bins_hertz)
# The i'th mel band (starting from i=1) has center frequency
# band_edges_mel[i], lower edge band_edges_mel[i-1], and higher edge
# band_edges_mel[i+1]. Thus, we need num_mel_bins + 2 values in
# the band_edges_mel arrays.
band_edges_mel = np.linspace(hertz_to_mel(lower_edge_hertz),
hertz_to_mel(upper_edge_hertz), num_mel_bins + 2)
# Matrix to post-multiply feature arrays whose rows are num_spectrogram_bins
# of spectrogram values.
mel_weights_matrix = np.empty((num_spectrogram_bins, num_mel_bins))
for i in range(num_mel_bins):
lower_edge_mel, center_mel, upper_edge_mel = band_edges_mel[i:i + 3]
# Calculate lower and upper slopes for every spectrogram bin.
# Line segments are linear in the *mel* domain, not hertz.
lower_slope = ((spectrogram_bins_mel - lower_edge_mel) /
(center_mel - lower_edge_mel))
upper_slope = ((upper_edge_mel - spectrogram_bins_mel) /
(upper_edge_mel - center_mel))
# .. then intersect them with each other and zero.
mel_weights_matrix[:, i] = np.maximum(0.0, np.minimum(lower_slope,
upper_slope))
# HTK excludes the spectrogram DC bin; make sure it always gets a zero
# coefficient.
mel_weights_matrix[0, :] = 0.0
return mel_weights_matrix | python | def spectrogram_to_mel_matrix(num_mel_bins=20,
num_spectrogram_bins=129,
audio_sample_rate=8000,
lower_edge_hertz=125.0,
upper_edge_hertz=3800.0):
"""Return a matrix that can post-multiply spectrogram rows to make mel.
Returns a np.array matrix A that can be used to post-multiply a matrix S of
spectrogram values (STFT magnitudes) arranged as frames x bins to generate a
"mel spectrogram" M of frames x num_mel_bins. M = S A.
The classic HTK algorithm exploits the complementarity of adjacent mel bands
to multiply each FFT bin by only one mel weight, then add it, with positive
and negative signs, to the two adjacent mel bands to which that bin
contributes. Here, by expressing this operation as a matrix multiply, we go
from num_fft multiplies per frame (plus around 2*num_fft adds) to around
num_fft^2 multiplies and adds. However, because these are all presumably
accomplished in a single call to np.dot(), it's not clear which approach is
faster in Python. The matrix multiplication has the attraction of being more
general and flexible, and much easier to read.
Args:
num_mel_bins: How many bands in the resulting mel spectrum. This is
the number of columns in the output matrix.
num_spectrogram_bins: How many bins there are in the source spectrogram
data, which is understood to be fft_size/2 + 1, i.e. the spectrogram
only contains the nonredundant FFT bins.
audio_sample_rate: Samples per second of the audio at the input to the
spectrogram. We need this to figure out the actual frequencies for
each spectrogram bin, which dictates how they are mapped into mel.
lower_edge_hertz: Lower bound on the frequencies to be included in the mel
spectrum. This corresponds to the lower edge of the lowest triangular
band.
upper_edge_hertz: The desired top edge of the highest frequency band.
Returns:
An np.array with shape (num_spectrogram_bins, num_mel_bins).
Raises:
ValueError: if frequency edges are incorrectly ordered or out of range.
"""
nyquist_hertz = audio_sample_rate / 2.
if lower_edge_hertz < 0.0:
raise ValueError("lower_edge_hertz %.1f must be >= 0" % lower_edge_hertz)
if lower_edge_hertz >= upper_edge_hertz:
raise ValueError("lower_edge_hertz %.1f >= upper_edge_hertz %.1f" %
(lower_edge_hertz, upper_edge_hertz))
if upper_edge_hertz > nyquist_hertz:
raise ValueError("upper_edge_hertz %.1f is greater than Nyquist %.1f" %
(upper_edge_hertz, nyquist_hertz))
spectrogram_bins_hertz = np.linspace(0.0, nyquist_hertz, num_spectrogram_bins)
spectrogram_bins_mel = hertz_to_mel(spectrogram_bins_hertz)
# The i'th mel band (starting from i=1) has center frequency
# band_edges_mel[i], lower edge band_edges_mel[i-1], and higher edge
# band_edges_mel[i+1]. Thus, we need num_mel_bins + 2 values in
# the band_edges_mel arrays.
band_edges_mel = np.linspace(hertz_to_mel(lower_edge_hertz),
hertz_to_mel(upper_edge_hertz), num_mel_bins + 2)
# Matrix to post-multiply feature arrays whose rows are num_spectrogram_bins
# of spectrogram values.
mel_weights_matrix = np.empty((num_spectrogram_bins, num_mel_bins))
for i in range(num_mel_bins):
lower_edge_mel, center_mel, upper_edge_mel = band_edges_mel[i:i + 3]
# Calculate lower and upper slopes for every spectrogram bin.
# Line segments are linear in the *mel* domain, not hertz.
lower_slope = ((spectrogram_bins_mel - lower_edge_mel) /
(center_mel - lower_edge_mel))
upper_slope = ((upper_edge_mel - spectrogram_bins_mel) /
(upper_edge_mel - center_mel))
# .. then intersect them with each other and zero.
mel_weights_matrix[:, i] = np.maximum(0.0, np.minimum(lower_slope,
upper_slope))
# HTK excludes the spectrogram DC bin; make sure it always gets a zero
# coefficient.
mel_weights_matrix[0, :] = 0.0
return mel_weights_matrix | [
"def",
"spectrogram_to_mel_matrix",
"(",
"num_mel_bins",
"=",
"20",
",",
"num_spectrogram_bins",
"=",
"129",
",",
"audio_sample_rate",
"=",
"8000",
",",
"lower_edge_hertz",
"=",
"125.0",
",",
"upper_edge_hertz",
"=",
"3800.0",
")",
":",
"nyquist_hertz",
"=",
"audio_sample_rate",
"/",
"2.",
"if",
"lower_edge_hertz",
"<",
"0.0",
":",
"raise",
"ValueError",
"(",
"\"lower_edge_hertz %.1f must be >= 0\"",
"%",
"lower_edge_hertz",
")",
"if",
"lower_edge_hertz",
">=",
"upper_edge_hertz",
":",
"raise",
"ValueError",
"(",
"\"lower_edge_hertz %.1f >= upper_edge_hertz %.1f\"",
"%",
"(",
"lower_edge_hertz",
",",
"upper_edge_hertz",
")",
")",
"if",
"upper_edge_hertz",
">",
"nyquist_hertz",
":",
"raise",
"ValueError",
"(",
"\"upper_edge_hertz %.1f is greater than Nyquist %.1f\"",
"%",
"(",
"upper_edge_hertz",
",",
"nyquist_hertz",
")",
")",
"spectrogram_bins_hertz",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"nyquist_hertz",
",",
"num_spectrogram_bins",
")",
"spectrogram_bins_mel",
"=",
"hertz_to_mel",
"(",
"spectrogram_bins_hertz",
")",
"# The i'th mel band (starting from i=1) has center frequency",
"# band_edges_mel[i], lower edge band_edges_mel[i-1], and higher edge",
"# band_edges_mel[i+1]. Thus, we need num_mel_bins + 2 values in",
"# the band_edges_mel arrays.",
"band_edges_mel",
"=",
"np",
".",
"linspace",
"(",
"hertz_to_mel",
"(",
"lower_edge_hertz",
")",
",",
"hertz_to_mel",
"(",
"upper_edge_hertz",
")",
",",
"num_mel_bins",
"+",
"2",
")",
"# Matrix to post-multiply feature arrays whose rows are num_spectrogram_bins",
"# of spectrogram values.",
"mel_weights_matrix",
"=",
"np",
".",
"empty",
"(",
"(",
"num_spectrogram_bins",
",",
"num_mel_bins",
")",
")",
"for",
"i",
"in",
"range",
"(",
"num_mel_bins",
")",
":",
"lower_edge_mel",
",",
"center_mel",
",",
"upper_edge_mel",
"=",
"band_edges_mel",
"[",
"i",
":",
"i",
"+",
"3",
"]",
"# Calculate lower and upper slopes for every spectrogram bin.",
"# Line segments are linear in the *mel* domain, not hertz.",
"lower_slope",
"=",
"(",
"(",
"spectrogram_bins_mel",
"-",
"lower_edge_mel",
")",
"/",
"(",
"center_mel",
"-",
"lower_edge_mel",
")",
")",
"upper_slope",
"=",
"(",
"(",
"upper_edge_mel",
"-",
"spectrogram_bins_mel",
")",
"/",
"(",
"upper_edge_mel",
"-",
"center_mel",
")",
")",
"# .. then intersect them with each other and zero.",
"mel_weights_matrix",
"[",
":",
",",
"i",
"]",
"=",
"np",
".",
"maximum",
"(",
"0.0",
",",
"np",
".",
"minimum",
"(",
"lower_slope",
",",
"upper_slope",
")",
")",
"# HTK excludes the spectrogram DC bin; make sure it always gets a zero",
"# coefficient.",
"mel_weights_matrix",
"[",
"0",
",",
":",
"]",
"=",
"0.0",
"return",
"mel_weights_matrix"
] | Return a matrix that can post-multiply spectrogram rows to make mel.
Returns a np.array matrix A that can be used to post-multiply a matrix S of
spectrogram values (STFT magnitudes) arranged as frames x bins to generate a
"mel spectrogram" M of frames x num_mel_bins. M = S A.
The classic HTK algorithm exploits the complementarity of adjacent mel bands
to multiply each FFT bin by only one mel weight, then add it, with positive
and negative signs, to the two adjacent mel bands to which that bin
contributes. Here, by expressing this operation as a matrix multiply, we go
from num_fft multiplies per frame (plus around 2*num_fft adds) to around
num_fft^2 multiplies and adds. However, because these are all presumably
accomplished in a single call to np.dot(), it's not clear which approach is
faster in Python. The matrix multiplication has the attraction of being more
general and flexible, and much easier to read.
Args:
num_mel_bins: How many bands in the resulting mel spectrum. This is
the number of columns in the output matrix.
num_spectrogram_bins: How many bins there are in the source spectrogram
data, which is understood to be fft_size/2 + 1, i.e. the spectrogram
only contains the nonredundant FFT bins.
audio_sample_rate: Samples per second of the audio at the input to the
spectrogram. We need this to figure out the actual frequencies for
each spectrogram bin, which dictates how they are mapped into mel.
lower_edge_hertz: Lower bound on the frequencies to be included in the mel
spectrum. This corresponds to the lower edge of the lowest triangular
band.
upper_edge_hertz: The desired top edge of the highest frequency band.
Returns:
An np.array with shape (num_spectrogram_bins, num_mel_bins).
Raises:
ValueError: if frequency edges are incorrectly ordered or out of range. | [
"Return",
"a",
"matrix",
"that",
"can",
"post",
"-",
"multiply",
"spectrogram",
"rows",
"to",
"make",
"mel",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py#L114-L189 |
28,864 | apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py | log_mel_spectrogram | def log_mel_spectrogram(data,
audio_sample_rate=8000,
log_offset=0.0,
window_length_secs=0.025,
hop_length_secs=0.010,
**kwargs):
"""Convert waveform to a log magnitude mel-frequency spectrogram.
Args:
data: 1D np.array of waveform data.
audio_sample_rate: The sampling rate of data.
log_offset: Add this to values when taking log to avoid -Infs.
window_length_secs: Duration of each window to analyze.
hop_length_secs: Advance between successive analysis windows.
**kwargs: Additional arguments to pass to spectrogram_to_mel_matrix.
Returns:
2D np.array of (num_frames, num_mel_bins) consisting of log mel filterbank
magnitudes for successive frames.
"""
window_length_samples = int(round(audio_sample_rate * window_length_secs))
hop_length_samples = int(round(audio_sample_rate * hop_length_secs))
fft_length = 2 ** int(np.ceil(np.log(window_length_samples) / np.log(2.0)))
spectrogram = stft_magnitude(
data,
fft_length=fft_length,
hop_length=hop_length_samples,
window_length=window_length_samples)
mel_spectrogram = np.dot(spectrogram, spectrogram_to_mel_matrix(
num_spectrogram_bins=spectrogram.shape[1],
audio_sample_rate=audio_sample_rate, **kwargs))
return np.log(mel_spectrogram + log_offset) | python | def log_mel_spectrogram(data,
audio_sample_rate=8000,
log_offset=0.0,
window_length_secs=0.025,
hop_length_secs=0.010,
**kwargs):
"""Convert waveform to a log magnitude mel-frequency spectrogram.
Args:
data: 1D np.array of waveform data.
audio_sample_rate: The sampling rate of data.
log_offset: Add this to values when taking log to avoid -Infs.
window_length_secs: Duration of each window to analyze.
hop_length_secs: Advance between successive analysis windows.
**kwargs: Additional arguments to pass to spectrogram_to_mel_matrix.
Returns:
2D np.array of (num_frames, num_mel_bins) consisting of log mel filterbank
magnitudes for successive frames.
"""
window_length_samples = int(round(audio_sample_rate * window_length_secs))
hop_length_samples = int(round(audio_sample_rate * hop_length_secs))
fft_length = 2 ** int(np.ceil(np.log(window_length_samples) / np.log(2.0)))
spectrogram = stft_magnitude(
data,
fft_length=fft_length,
hop_length=hop_length_samples,
window_length=window_length_samples)
mel_spectrogram = np.dot(spectrogram, spectrogram_to_mel_matrix(
num_spectrogram_bins=spectrogram.shape[1],
audio_sample_rate=audio_sample_rate, **kwargs))
return np.log(mel_spectrogram + log_offset) | [
"def",
"log_mel_spectrogram",
"(",
"data",
",",
"audio_sample_rate",
"=",
"8000",
",",
"log_offset",
"=",
"0.0",
",",
"window_length_secs",
"=",
"0.025",
",",
"hop_length_secs",
"=",
"0.010",
",",
"*",
"*",
"kwargs",
")",
":",
"window_length_samples",
"=",
"int",
"(",
"round",
"(",
"audio_sample_rate",
"*",
"window_length_secs",
")",
")",
"hop_length_samples",
"=",
"int",
"(",
"round",
"(",
"audio_sample_rate",
"*",
"hop_length_secs",
")",
")",
"fft_length",
"=",
"2",
"**",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"log",
"(",
"window_length_samples",
")",
"/",
"np",
".",
"log",
"(",
"2.0",
")",
")",
")",
"spectrogram",
"=",
"stft_magnitude",
"(",
"data",
",",
"fft_length",
"=",
"fft_length",
",",
"hop_length",
"=",
"hop_length_samples",
",",
"window_length",
"=",
"window_length_samples",
")",
"mel_spectrogram",
"=",
"np",
".",
"dot",
"(",
"spectrogram",
",",
"spectrogram_to_mel_matrix",
"(",
"num_spectrogram_bins",
"=",
"spectrogram",
".",
"shape",
"[",
"1",
"]",
",",
"audio_sample_rate",
"=",
"audio_sample_rate",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"np",
".",
"log",
"(",
"mel_spectrogram",
"+",
"log_offset",
")"
] | Convert waveform to a log magnitude mel-frequency spectrogram.
Args:
data: 1D np.array of waveform data.
audio_sample_rate: The sampling rate of data.
log_offset: Add this to values when taking log to avoid -Infs.
window_length_secs: Duration of each window to analyze.
hop_length_secs: Advance between successive analysis windows.
**kwargs: Additional arguments to pass to spectrogram_to_mel_matrix.
Returns:
2D np.array of (num_frames, num_mel_bins) consisting of log mel filterbank
magnitudes for successive frames. | [
"Convert",
"waveform",
"to",
"a",
"log",
"magnitude",
"mel",
"-",
"frequency",
"spectrogram",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/mel_features.py#L192-L223 |
28,865 | apple/turicreate | src/unity/python/turicreate/toolkits/activity_classifier/_activity_classifier.py | ActivityClassifier.classify | def classify(self, dataset, output_frequency='per_row'):
"""
Return a classification, for each ``prediction_window`` examples in the
``dataset``, using the trained activity classification model. The output
SFrame contains predictions as both class labels as well as probabilities
that the predicted value is the associated label.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the features and session id used for model training, but
does not require a target column. Additional columns are ignored.
output_frequency : {'per_row', 'per_window'}, optional
The frequency of the predictions which is one of:
- 'per_row': Each prediction is returned ``prediction_window`` times.
- 'per_window': Return a single prediction for each
``prediction_window`` rows in ``dataset`` per ``session_id``.
Returns
-------
out : SFrame
An SFrame with model predictions i.e class labels and probabilities.
See Also
----------
create, evaluate, predict
Examples
----------
>>> classes = model.classify(data)
"""
_tkutl._check_categorical_option_type(
'output_frequency', output_frequency, ['per_window', 'per_row'])
id_target_map = self._id_target_map
preds = self.predict(
dataset, output_type='probability_vector', output_frequency=output_frequency)
if output_frequency == 'per_row':
return _SFrame({
'class': preds.apply(lambda p: id_target_map[_np.argmax(p)]),
'probability': preds.apply(_np.max)
})
elif output_frequency == 'per_window':
preds['class'] = preds['probability_vector'].apply(
lambda p: id_target_map[_np.argmax(p)])
preds['probability'] = preds['probability_vector'].apply(_np.max)
preds = preds.remove_column('probability_vector')
return preds | python | def classify(self, dataset, output_frequency='per_row'):
"""
Return a classification, for each ``prediction_window`` examples in the
``dataset``, using the trained activity classification model. The output
SFrame contains predictions as both class labels as well as probabilities
that the predicted value is the associated label.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the features and session id used for model training, but
does not require a target column. Additional columns are ignored.
output_frequency : {'per_row', 'per_window'}, optional
The frequency of the predictions which is one of:
- 'per_row': Each prediction is returned ``prediction_window`` times.
- 'per_window': Return a single prediction for each
``prediction_window`` rows in ``dataset`` per ``session_id``.
Returns
-------
out : SFrame
An SFrame with model predictions i.e class labels and probabilities.
See Also
----------
create, evaluate, predict
Examples
----------
>>> classes = model.classify(data)
"""
_tkutl._check_categorical_option_type(
'output_frequency', output_frequency, ['per_window', 'per_row'])
id_target_map = self._id_target_map
preds = self.predict(
dataset, output_type='probability_vector', output_frequency=output_frequency)
if output_frequency == 'per_row':
return _SFrame({
'class': preds.apply(lambda p: id_target_map[_np.argmax(p)]),
'probability': preds.apply(_np.max)
})
elif output_frequency == 'per_window':
preds['class'] = preds['probability_vector'].apply(
lambda p: id_target_map[_np.argmax(p)])
preds['probability'] = preds['probability_vector'].apply(_np.max)
preds = preds.remove_column('probability_vector')
return preds | [
"def",
"classify",
"(",
"self",
",",
"dataset",
",",
"output_frequency",
"=",
"'per_row'",
")",
":",
"_tkutl",
".",
"_check_categorical_option_type",
"(",
"'output_frequency'",
",",
"output_frequency",
",",
"[",
"'per_window'",
",",
"'per_row'",
"]",
")",
"id_target_map",
"=",
"self",
".",
"_id_target_map",
"preds",
"=",
"self",
".",
"predict",
"(",
"dataset",
",",
"output_type",
"=",
"'probability_vector'",
",",
"output_frequency",
"=",
"output_frequency",
")",
"if",
"output_frequency",
"==",
"'per_row'",
":",
"return",
"_SFrame",
"(",
"{",
"'class'",
":",
"preds",
".",
"apply",
"(",
"lambda",
"p",
":",
"id_target_map",
"[",
"_np",
".",
"argmax",
"(",
"p",
")",
"]",
")",
",",
"'probability'",
":",
"preds",
".",
"apply",
"(",
"_np",
".",
"max",
")",
"}",
")",
"elif",
"output_frequency",
"==",
"'per_window'",
":",
"preds",
"[",
"'class'",
"]",
"=",
"preds",
"[",
"'probability_vector'",
"]",
".",
"apply",
"(",
"lambda",
"p",
":",
"id_target_map",
"[",
"_np",
".",
"argmax",
"(",
"p",
")",
"]",
")",
"preds",
"[",
"'probability'",
"]",
"=",
"preds",
"[",
"'probability_vector'",
"]",
".",
"apply",
"(",
"_np",
".",
"max",
")",
"preds",
"=",
"preds",
".",
"remove_column",
"(",
"'probability_vector'",
")",
"return",
"preds"
] | Return a classification, for each ``prediction_window`` examples in the
``dataset``, using the trained activity classification model. The output
SFrame contains predictions as both class labels as well as probabilities
that the predicted value is the associated label.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the features and session id used for model training, but
does not require a target column. Additional columns are ignored.
output_frequency : {'per_row', 'per_window'}, optional
The frequency of the predictions which is one of:
- 'per_row': Each prediction is returned ``prediction_window`` times.
- 'per_window': Return a single prediction for each
``prediction_window`` rows in ``dataset`` per ``session_id``.
Returns
-------
out : SFrame
An SFrame with model predictions i.e class labels and probabilities.
See Also
----------
create, evaluate, predict
Examples
----------
>>> classes = model.classify(data) | [
"Return",
"a",
"classification",
"for",
"each",
"prediction_window",
"examples",
"in",
"the",
"dataset",
"using",
"the",
"trained",
"activity",
"classification",
"model",
".",
"The",
"output",
"SFrame",
"contains",
"predictions",
"as",
"both",
"class",
"labels",
"as",
"well",
"as",
"probabilities",
"that",
"the",
"predicted",
"value",
"is",
"the",
"associated",
"label",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/activity_classifier/_activity_classifier.py#L745-L795 |
28,866 | apple/turicreate | deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/char_stat.py | count_characters | def count_characters(root, out):
"""Count the occurrances of the different characters in the files"""
if os.path.isfile(root):
with open(root, 'rb') as in_f:
for line in in_f:
for char in line:
if char not in out:
out[char] = 0
out[char] = out[char] + 1
elif os.path.isdir(root):
for filename in os.listdir(root):
count_characters(os.path.join(root, filename), out) | python | def count_characters(root, out):
"""Count the occurrances of the different characters in the files"""
if os.path.isfile(root):
with open(root, 'rb') as in_f:
for line in in_f:
for char in line:
if char not in out:
out[char] = 0
out[char] = out[char] + 1
elif os.path.isdir(root):
for filename in os.listdir(root):
count_characters(os.path.join(root, filename), out) | [
"def",
"count_characters",
"(",
"root",
",",
"out",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"root",
")",
":",
"with",
"open",
"(",
"root",
",",
"'rb'",
")",
"as",
"in_f",
":",
"for",
"line",
"in",
"in_f",
":",
"for",
"char",
"in",
"line",
":",
"if",
"char",
"not",
"in",
"out",
":",
"out",
"[",
"char",
"]",
"=",
"0",
"out",
"[",
"char",
"]",
"=",
"out",
"[",
"char",
"]",
"+",
"1",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"root",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"root",
")",
":",
"count_characters",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
",",
"out",
")"
] | Count the occurrances of the different characters in the files | [
"Count",
"the",
"occurrances",
"of",
"the",
"different",
"characters",
"in",
"the",
"files"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/char_stat.py#L13-L24 |
28,867 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | save_spec | def save_spec(spec, filename):
"""
Save a protobuf model specification to file.
Parameters
----------
spec: Model_pb
Protobuf representation of the model
filename: str
File path where the spec gets saved.
Examples
--------
.. sourcecode:: python
>>> coremltools.utils.save_spec(spec, 'HousePricer.mlmodel')
See Also
--------
load_spec
"""
name, ext = _os.path.splitext(filename)
if not ext:
filename = "%s.mlmodel" % filename
else:
if ext != '.mlmodel':
raise Exception("Extension must be .mlmodel (not %s)" % ext)
with open(filename, 'wb') as f:
s = spec.SerializeToString()
f.write(s) | python | def save_spec(spec, filename):
"""
Save a protobuf model specification to file.
Parameters
----------
spec: Model_pb
Protobuf representation of the model
filename: str
File path where the spec gets saved.
Examples
--------
.. sourcecode:: python
>>> coremltools.utils.save_spec(spec, 'HousePricer.mlmodel')
See Also
--------
load_spec
"""
name, ext = _os.path.splitext(filename)
if not ext:
filename = "%s.mlmodel" % filename
else:
if ext != '.mlmodel':
raise Exception("Extension must be .mlmodel (not %s)" % ext)
with open(filename, 'wb') as f:
s = spec.SerializeToString()
f.write(s) | [
"def",
"save_spec",
"(",
"spec",
",",
"filename",
")",
":",
"name",
",",
"ext",
"=",
"_os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"not",
"ext",
":",
"filename",
"=",
"\"%s.mlmodel\"",
"%",
"filename",
"else",
":",
"if",
"ext",
"!=",
"'.mlmodel'",
":",
"raise",
"Exception",
"(",
"\"Extension must be .mlmodel (not %s)\"",
"%",
"ext",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"s",
"=",
"spec",
".",
"SerializeToString",
"(",
")",
"f",
".",
"write",
"(",
"s",
")"
] | Save a protobuf model specification to file.
Parameters
----------
spec: Model_pb
Protobuf representation of the model
filename: str
File path where the spec gets saved.
Examples
--------
.. sourcecode:: python
>>> coremltools.utils.save_spec(spec, 'HousePricer.mlmodel')
See Also
--------
load_spec | [
"Save",
"a",
"protobuf",
"model",
"specification",
"to",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L28-L59 |
28,868 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | load_spec | def load_spec(filename):
"""
Load a protobuf model specification from file
Parameters
----------
filename: str
Location on disk (a valid filepath) from which the file is loaded
as a protobuf spec.
Returns
-------
model_spec: Model_pb
Protobuf representation of the model
Examples
--------
.. sourcecode:: python
>>> spec = coremltools.utils.load_spec('HousePricer.mlmodel')
See Also
--------
save_spec
"""
from ..proto import Model_pb2
spec = Model_pb2.Model()
with open(filename, 'rb') as f:
contents = f.read()
spec.ParseFromString(contents)
return spec | python | def load_spec(filename):
"""
Load a protobuf model specification from file
Parameters
----------
filename: str
Location on disk (a valid filepath) from which the file is loaded
as a protobuf spec.
Returns
-------
model_spec: Model_pb
Protobuf representation of the model
Examples
--------
.. sourcecode:: python
>>> spec = coremltools.utils.load_spec('HousePricer.mlmodel')
See Also
--------
save_spec
"""
from ..proto import Model_pb2
spec = Model_pb2.Model()
with open(filename, 'rb') as f:
contents = f.read()
spec.ParseFromString(contents)
return spec | [
"def",
"load_spec",
"(",
"filename",
")",
":",
"from",
".",
".",
"proto",
"import",
"Model_pb2",
"spec",
"=",
"Model_pb2",
".",
"Model",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"spec",
".",
"ParseFromString",
"(",
"contents",
")",
"return",
"spec"
] | Load a protobuf model specification from file
Parameters
----------
filename: str
Location on disk (a valid filepath) from which the file is loaded
as a protobuf spec.
Returns
-------
model_spec: Model_pb
Protobuf representation of the model
Examples
--------
.. sourcecode:: python
>>> spec = coremltools.utils.load_spec('HousePricer.mlmodel')
See Also
--------
save_spec | [
"Load",
"a",
"protobuf",
"model",
"specification",
"from",
"file"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L62-L93 |
28,869 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | _get_nn_layers | def _get_nn_layers(spec):
"""
Returns a list of neural network layers if the model contains any.
Parameters
----------
spec: Model_pb
A model protobuf specification.
Returns
-------
[NN layer]
list of all layers (including layers from elements of a pipeline
"""
layers = []
if spec.WhichOneof('Type') == 'pipeline':
layers = []
for model_spec in spec.pipeline.models:
if not layers:
return _get_nn_layers(model_spec)
else:
layers.extend(_get_nn_layers(model_spec))
elif spec.WhichOneof('Type') in ['pipelineClassifier',
'pipelineRegressor']:
layers = []
for model_spec in spec.pipeline.models:
if not layers:
return _get_nn_layers(model_spec)
else:
layers.extend(_get_nn_layers(model_spec))
elif spec.neuralNetwork.layers:
layers = spec.neuralNetwork.layers
elif spec.neuralNetworkClassifier.layers:
layers = spec.neuralNetworkClassifier.layers
elif spec.neuralNetworkRegressor.layers:
layers = spec.neuralNetworkRegressor.layers
return layers | python | def _get_nn_layers(spec):
"""
Returns a list of neural network layers if the model contains any.
Parameters
----------
spec: Model_pb
A model protobuf specification.
Returns
-------
[NN layer]
list of all layers (including layers from elements of a pipeline
"""
layers = []
if spec.WhichOneof('Type') == 'pipeline':
layers = []
for model_spec in spec.pipeline.models:
if not layers:
return _get_nn_layers(model_spec)
else:
layers.extend(_get_nn_layers(model_spec))
elif spec.WhichOneof('Type') in ['pipelineClassifier',
'pipelineRegressor']:
layers = []
for model_spec in spec.pipeline.models:
if not layers:
return _get_nn_layers(model_spec)
else:
layers.extend(_get_nn_layers(model_spec))
elif spec.neuralNetwork.layers:
layers = spec.neuralNetwork.layers
elif spec.neuralNetworkClassifier.layers:
layers = spec.neuralNetworkClassifier.layers
elif spec.neuralNetworkRegressor.layers:
layers = spec.neuralNetworkRegressor.layers
return layers | [
"def",
"_get_nn_layers",
"(",
"spec",
")",
":",
"layers",
"=",
"[",
"]",
"if",
"spec",
".",
"WhichOneof",
"(",
"'Type'",
")",
"==",
"'pipeline'",
":",
"layers",
"=",
"[",
"]",
"for",
"model_spec",
"in",
"spec",
".",
"pipeline",
".",
"models",
":",
"if",
"not",
"layers",
":",
"return",
"_get_nn_layers",
"(",
"model_spec",
")",
"else",
":",
"layers",
".",
"extend",
"(",
"_get_nn_layers",
"(",
"model_spec",
")",
")",
"elif",
"spec",
".",
"WhichOneof",
"(",
"'Type'",
")",
"in",
"[",
"'pipelineClassifier'",
",",
"'pipelineRegressor'",
"]",
":",
"layers",
"=",
"[",
"]",
"for",
"model_spec",
"in",
"spec",
".",
"pipeline",
".",
"models",
":",
"if",
"not",
"layers",
":",
"return",
"_get_nn_layers",
"(",
"model_spec",
")",
"else",
":",
"layers",
".",
"extend",
"(",
"_get_nn_layers",
"(",
"model_spec",
")",
")",
"elif",
"spec",
".",
"neuralNetwork",
".",
"layers",
":",
"layers",
"=",
"spec",
".",
"neuralNetwork",
".",
"layers",
"elif",
"spec",
".",
"neuralNetworkClassifier",
".",
"layers",
":",
"layers",
"=",
"spec",
".",
"neuralNetworkClassifier",
".",
"layers",
"elif",
"spec",
".",
"neuralNetworkRegressor",
".",
"layers",
":",
"layers",
"=",
"spec",
".",
"neuralNetworkRegressor",
".",
"layers",
"return",
"layers"
] | Returns a list of neural network layers if the model contains any.
Parameters
----------
spec: Model_pb
A model protobuf specification.
Returns
-------
[NN layer]
list of all layers (including layers from elements of a pipeline | [
"Returns",
"a",
"list",
"of",
"neural",
"network",
"layers",
"if",
"the",
"model",
"contains",
"any",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L96-L137 |
28,870 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | evaluate_classifier_with_probabilities | def evaluate_classifier_with_probabilities(model, data,
probabilities='probabilities',
verbose = False):
"""
Evaluate a classifier specification for testing.
Parameters
----------
filename: [str | Model]
File from where to load the model from (OR) a loaded
version of the MLModel.
data: [str | Dataframe]
Test data on which to evaluate the models (dataframe,
or path to a csv file).
probabilities: str
Column to interpret as the probabilities column
verbose: bool
Verbosity levels of the predictions.
"""
model = _get_model(model)
if verbose:
print("")
print("Other Framework\t\tPredicted")
max_probability_error, num_key_mismatch = 0, 0
for _,row in data.iterrows():
predicted_values = model.predict(dict(row))[_to_unicode(probabilities)]
other_values = row[probabilities]
if set(predicted_values.keys()) != set(other_values.keys()):
if verbose:
print("Different classes: ", str(predicted_values.keys()), str(other_values.keys()))
num_key_mismatch += 1
continue
for cur_class, cur_predicted_class_values in predicted_values.items():
delta = cur_predicted_class_values - other_values[cur_class]
if verbose:
print(delta, cur_predicted_class_values, other_values[cur_class])
max_probability_error = max(abs(delta), max_probability_error)
if verbose:
print("")
ret = {
"num_samples": len(data),
"max_probability_error": max_probability_error,
"num_key_mismatch": num_key_mismatch
}
if verbose:
print("results: %s" % ret)
return ret | python | def evaluate_classifier_with_probabilities(model, data,
probabilities='probabilities',
verbose = False):
"""
Evaluate a classifier specification for testing.
Parameters
----------
filename: [str | Model]
File from where to load the model from (OR) a loaded
version of the MLModel.
data: [str | Dataframe]
Test data on which to evaluate the models (dataframe,
or path to a csv file).
probabilities: str
Column to interpret as the probabilities column
verbose: bool
Verbosity levels of the predictions.
"""
model = _get_model(model)
if verbose:
print("")
print("Other Framework\t\tPredicted")
max_probability_error, num_key_mismatch = 0, 0
for _,row in data.iterrows():
predicted_values = model.predict(dict(row))[_to_unicode(probabilities)]
other_values = row[probabilities]
if set(predicted_values.keys()) != set(other_values.keys()):
if verbose:
print("Different classes: ", str(predicted_values.keys()), str(other_values.keys()))
num_key_mismatch += 1
continue
for cur_class, cur_predicted_class_values in predicted_values.items():
delta = cur_predicted_class_values - other_values[cur_class]
if verbose:
print(delta, cur_predicted_class_values, other_values[cur_class])
max_probability_error = max(abs(delta), max_probability_error)
if verbose:
print("")
ret = {
"num_samples": len(data),
"max_probability_error": max_probability_error,
"num_key_mismatch": num_key_mismatch
}
if verbose:
print("results: %s" % ret)
return ret | [
"def",
"evaluate_classifier_with_probabilities",
"(",
"model",
",",
"data",
",",
"probabilities",
"=",
"'probabilities'",
",",
"verbose",
"=",
"False",
")",
":",
"model",
"=",
"_get_model",
"(",
"model",
")",
"if",
"verbose",
":",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"Other Framework\\t\\tPredicted\"",
")",
"max_probability_error",
",",
"num_key_mismatch",
"=",
"0",
",",
"0",
"for",
"_",
",",
"row",
"in",
"data",
".",
"iterrows",
"(",
")",
":",
"predicted_values",
"=",
"model",
".",
"predict",
"(",
"dict",
"(",
"row",
")",
")",
"[",
"_to_unicode",
"(",
"probabilities",
")",
"]",
"other_values",
"=",
"row",
"[",
"probabilities",
"]",
"if",
"set",
"(",
"predicted_values",
".",
"keys",
"(",
")",
")",
"!=",
"set",
"(",
"other_values",
".",
"keys",
"(",
")",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Different classes: \"",
",",
"str",
"(",
"predicted_values",
".",
"keys",
"(",
")",
")",
",",
"str",
"(",
"other_values",
".",
"keys",
"(",
")",
")",
")",
"num_key_mismatch",
"+=",
"1",
"continue",
"for",
"cur_class",
",",
"cur_predicted_class_values",
"in",
"predicted_values",
".",
"items",
"(",
")",
":",
"delta",
"=",
"cur_predicted_class_values",
"-",
"other_values",
"[",
"cur_class",
"]",
"if",
"verbose",
":",
"print",
"(",
"delta",
",",
"cur_predicted_class_values",
",",
"other_values",
"[",
"cur_class",
"]",
")",
"max_probability_error",
"=",
"max",
"(",
"abs",
"(",
"delta",
")",
",",
"max_probability_error",
")",
"if",
"verbose",
":",
"print",
"(",
"\"\"",
")",
"ret",
"=",
"{",
"\"num_samples\"",
":",
"len",
"(",
"data",
")",
",",
"\"max_probability_error\"",
":",
"max_probability_error",
",",
"\"num_key_mismatch\"",
":",
"num_key_mismatch",
"}",
"if",
"verbose",
":",
"print",
"(",
"\"results: %s\"",
"%",
"ret",
")",
"return",
"ret"
] | Evaluate a classifier specification for testing.
Parameters
----------
filename: [str | Model]
File from where to load the model from (OR) a loaded
version of the MLModel.
data: [str | Dataframe]
Test data on which to evaluate the models (dataframe,
or path to a csv file).
probabilities: str
Column to interpret as the probabilities column
verbose: bool
Verbosity levels of the predictions. | [
"Evaluate",
"a",
"classifier",
"specification",
"for",
"testing",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L512-L571 |
28,871 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | rename_feature | def rename_feature(spec, current_name, new_name, rename_inputs=True,
rename_outputs=True):
"""
Rename a feature in the specification.
Parameters
----------
spec: Model_pb
The specification containing the feature to rename.
current_name: str
Current name of the feature. If this feature doesn't exist, the rename
is a no-op.
new_name: str
New name of the feature.
rename_inputs: bool
Search for `current_name` only in the input features (i.e ignore output
features)
rename_outputs: bool
Search for `current_name` only in the output features (i.e ignore input
features)
Examples
--------
.. sourcecode:: python
# In-place rename of spec
>>> coremltools.utils.rename_feature(spec, 'old_feature', 'new_feature_name')
"""
from coremltools.models import MLModel
if not rename_inputs and not rename_outputs:
return
changed_input = False
changed_output = False
if rename_inputs:
for input in spec.description.input:
if input.name == current_name:
input.name = new_name
changed_input = True
if rename_outputs:
for output in spec.description.output:
if output.name == current_name:
output.name = new_name
changed_output = True
if spec.description.predictedFeatureName == current_name:
spec.description.predictedFeatureName = new_name
if spec.description.predictedProbabilitiesName == current_name:
spec.description.predictedProbabilitiesName = new_name
if not changed_input and not changed_output:
return
# Rename internally in NN model
nn = None
for nn_type in ['neuralNetwork','neuralNetworkClassifier','neuralNetworkRegressor']:
if spec.HasField(nn_type):
nn = getattr(spec,nn_type)
if nn is not None:
for layer in nn.layers:
if rename_inputs:
for index,name in enumerate(layer.input):
if name == current_name:
layer.input[index] = new_name
if rename_outputs:
for index,name in enumerate(layer.output):
if name == current_name:
layer.output[index] = new_name
# Rename internally for feature vectorizer
if spec.HasField('featureVectorizer') and rename_inputs:
for input in spec.featureVectorizer.inputList:
if input.inputColumn == current_name:
input.inputColumn = new_name
changed_input = True
# Rename for pipeline models
pipeline = None
if spec.HasField('pipeline'):
pipeline = spec.pipeline
elif spec.HasField('pipelineClassifier'):
pipeline = spec.pipelineClassifier.pipeline
elif spec.HasField('pipelineRegressor'):
pipeline = spec.pipelineRegressor.pipeline
if pipeline is not None:
for index,model in enumerate(pipeline.models):
rename_feature(model,
current_name,
new_name,
rename_inputs or (index != 0),
rename_outputs or (index < len(spec.pipeline.models))) | python | def rename_feature(spec, current_name, new_name, rename_inputs=True,
rename_outputs=True):
"""
Rename a feature in the specification.
Parameters
----------
spec: Model_pb
The specification containing the feature to rename.
current_name: str
Current name of the feature. If this feature doesn't exist, the rename
is a no-op.
new_name: str
New name of the feature.
rename_inputs: bool
Search for `current_name` only in the input features (i.e ignore output
features)
rename_outputs: bool
Search for `current_name` only in the output features (i.e ignore input
features)
Examples
--------
.. sourcecode:: python
# In-place rename of spec
>>> coremltools.utils.rename_feature(spec, 'old_feature', 'new_feature_name')
"""
from coremltools.models import MLModel
if not rename_inputs and not rename_outputs:
return
changed_input = False
changed_output = False
if rename_inputs:
for input in spec.description.input:
if input.name == current_name:
input.name = new_name
changed_input = True
if rename_outputs:
for output in spec.description.output:
if output.name == current_name:
output.name = new_name
changed_output = True
if spec.description.predictedFeatureName == current_name:
spec.description.predictedFeatureName = new_name
if spec.description.predictedProbabilitiesName == current_name:
spec.description.predictedProbabilitiesName = new_name
if not changed_input and not changed_output:
return
# Rename internally in NN model
nn = None
for nn_type in ['neuralNetwork','neuralNetworkClassifier','neuralNetworkRegressor']:
if spec.HasField(nn_type):
nn = getattr(spec,nn_type)
if nn is not None:
for layer in nn.layers:
if rename_inputs:
for index,name in enumerate(layer.input):
if name == current_name:
layer.input[index] = new_name
if rename_outputs:
for index,name in enumerate(layer.output):
if name == current_name:
layer.output[index] = new_name
# Rename internally for feature vectorizer
if spec.HasField('featureVectorizer') and rename_inputs:
for input in spec.featureVectorizer.inputList:
if input.inputColumn == current_name:
input.inputColumn = new_name
changed_input = True
# Rename for pipeline models
pipeline = None
if spec.HasField('pipeline'):
pipeline = spec.pipeline
elif spec.HasField('pipelineClassifier'):
pipeline = spec.pipelineClassifier.pipeline
elif spec.HasField('pipelineRegressor'):
pipeline = spec.pipelineRegressor.pipeline
if pipeline is not None:
for index,model in enumerate(pipeline.models):
rename_feature(model,
current_name,
new_name,
rename_inputs or (index != 0),
rename_outputs or (index < len(spec.pipeline.models))) | [
"def",
"rename_feature",
"(",
"spec",
",",
"current_name",
",",
"new_name",
",",
"rename_inputs",
"=",
"True",
",",
"rename_outputs",
"=",
"True",
")",
":",
"from",
"coremltools",
".",
"models",
"import",
"MLModel",
"if",
"not",
"rename_inputs",
"and",
"not",
"rename_outputs",
":",
"return",
"changed_input",
"=",
"False",
"changed_output",
"=",
"False",
"if",
"rename_inputs",
":",
"for",
"input",
"in",
"spec",
".",
"description",
".",
"input",
":",
"if",
"input",
".",
"name",
"==",
"current_name",
":",
"input",
".",
"name",
"=",
"new_name",
"changed_input",
"=",
"True",
"if",
"rename_outputs",
":",
"for",
"output",
"in",
"spec",
".",
"description",
".",
"output",
":",
"if",
"output",
".",
"name",
"==",
"current_name",
":",
"output",
".",
"name",
"=",
"new_name",
"changed_output",
"=",
"True",
"if",
"spec",
".",
"description",
".",
"predictedFeatureName",
"==",
"current_name",
":",
"spec",
".",
"description",
".",
"predictedFeatureName",
"=",
"new_name",
"if",
"spec",
".",
"description",
".",
"predictedProbabilitiesName",
"==",
"current_name",
":",
"spec",
".",
"description",
".",
"predictedProbabilitiesName",
"=",
"new_name",
"if",
"not",
"changed_input",
"and",
"not",
"changed_output",
":",
"return",
"# Rename internally in NN model",
"nn",
"=",
"None",
"for",
"nn_type",
"in",
"[",
"'neuralNetwork'",
",",
"'neuralNetworkClassifier'",
",",
"'neuralNetworkRegressor'",
"]",
":",
"if",
"spec",
".",
"HasField",
"(",
"nn_type",
")",
":",
"nn",
"=",
"getattr",
"(",
"spec",
",",
"nn_type",
")",
"if",
"nn",
"is",
"not",
"None",
":",
"for",
"layer",
"in",
"nn",
".",
"layers",
":",
"if",
"rename_inputs",
":",
"for",
"index",
",",
"name",
"in",
"enumerate",
"(",
"layer",
".",
"input",
")",
":",
"if",
"name",
"==",
"current_name",
":",
"layer",
".",
"input",
"[",
"index",
"]",
"=",
"new_name",
"if",
"rename_outputs",
":",
"for",
"index",
",",
"name",
"in",
"enumerate",
"(",
"layer",
".",
"output",
")",
":",
"if",
"name",
"==",
"current_name",
":",
"layer",
".",
"output",
"[",
"index",
"]",
"=",
"new_name",
"# Rename internally for feature vectorizer",
"if",
"spec",
".",
"HasField",
"(",
"'featureVectorizer'",
")",
"and",
"rename_inputs",
":",
"for",
"input",
"in",
"spec",
".",
"featureVectorizer",
".",
"inputList",
":",
"if",
"input",
".",
"inputColumn",
"==",
"current_name",
":",
"input",
".",
"inputColumn",
"=",
"new_name",
"changed_input",
"=",
"True",
"# Rename for pipeline models",
"pipeline",
"=",
"None",
"if",
"spec",
".",
"HasField",
"(",
"'pipeline'",
")",
":",
"pipeline",
"=",
"spec",
".",
"pipeline",
"elif",
"spec",
".",
"HasField",
"(",
"'pipelineClassifier'",
")",
":",
"pipeline",
"=",
"spec",
".",
"pipelineClassifier",
".",
"pipeline",
"elif",
"spec",
".",
"HasField",
"(",
"'pipelineRegressor'",
")",
":",
"pipeline",
"=",
"spec",
".",
"pipelineRegressor",
".",
"pipeline",
"if",
"pipeline",
"is",
"not",
"None",
":",
"for",
"index",
",",
"model",
"in",
"enumerate",
"(",
"pipeline",
".",
"models",
")",
":",
"rename_feature",
"(",
"model",
",",
"current_name",
",",
"new_name",
",",
"rename_inputs",
"or",
"(",
"index",
"!=",
"0",
")",
",",
"rename_outputs",
"or",
"(",
"index",
"<",
"len",
"(",
"spec",
".",
"pipeline",
".",
"models",
")",
")",
")"
] | Rename a feature in the specification.
Parameters
----------
spec: Model_pb
The specification containing the feature to rename.
current_name: str
Current name of the feature. If this feature doesn't exist, the rename
is a no-op.
new_name: str
New name of the feature.
rename_inputs: bool
Search for `current_name` only in the input features (i.e ignore output
features)
rename_outputs: bool
Search for `current_name` only in the output features (i.e ignore input
features)
Examples
--------
.. sourcecode:: python
# In-place rename of spec
>>> coremltools.utils.rename_feature(spec, 'old_feature', 'new_feature_name') | [
"Rename",
"a",
"feature",
"in",
"the",
"specification",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L574-L674 |
28,872 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | _sanitize_value | def _sanitize_value(x):
"""
Performs cleaning steps on the data so various type comparisons can
be performed correctly.
"""
if isinstance(x, _six.string_types + _six.integer_types + (float,)):
return x
elif _HAS_SKLEARN and _sp.issparse(x):
return x.todense()
elif isinstance(x, _np.ndarray):
return x
elif isinstance(x, tuple):
return (_sanitize_value(v) for v in x)
elif isinstance(x, list):
return [_sanitize_value(v) for v in x]
elif isinstance(x, dict):
return dict( (_sanitize_value(k), _sanitize_value(v)) for k, v in x.items())
else:
assert False, str(x) | python | def _sanitize_value(x):
"""
Performs cleaning steps on the data so various type comparisons can
be performed correctly.
"""
if isinstance(x, _six.string_types + _six.integer_types + (float,)):
return x
elif _HAS_SKLEARN and _sp.issparse(x):
return x.todense()
elif isinstance(x, _np.ndarray):
return x
elif isinstance(x, tuple):
return (_sanitize_value(v) for v in x)
elif isinstance(x, list):
return [_sanitize_value(v) for v in x]
elif isinstance(x, dict):
return dict( (_sanitize_value(k), _sanitize_value(v)) for k, v in x.items())
else:
assert False, str(x) | [
"def",
"_sanitize_value",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"_six",
".",
"string_types",
"+",
"_six",
".",
"integer_types",
"+",
"(",
"float",
",",
")",
")",
":",
"return",
"x",
"elif",
"_HAS_SKLEARN",
"and",
"_sp",
".",
"issparse",
"(",
"x",
")",
":",
"return",
"x",
".",
"todense",
"(",
")",
"elif",
"isinstance",
"(",
"x",
",",
"_np",
".",
"ndarray",
")",
":",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"tuple",
")",
":",
"return",
"(",
"_sanitize_value",
"(",
"v",
")",
"for",
"v",
"in",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"[",
"_sanitize_value",
"(",
"v",
")",
"for",
"v",
"in",
"x",
"]",
"elif",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"_sanitize_value",
"(",
"k",
")",
",",
"_sanitize_value",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"x",
".",
"items",
"(",
")",
")",
"else",
":",
"assert",
"False",
",",
"str",
"(",
"x",
")"
] | Performs cleaning steps on the data so various type comparisons can
be performed correctly. | [
"Performs",
"cleaning",
"steps",
"on",
"the",
"data",
"so",
"various",
"type",
"comparisons",
"can",
"be",
"performed",
"correctly",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L677-L695 |
28,873 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | _element_equal | def _element_equal(x, y):
"""
Performs a robust equality test between elements.
"""
if isinstance(x, _np.ndarray) or isinstance(y, _np.ndarray):
try:
return (abs(_np.asarray(x) - _np.asarray(y)) < 1e-5).all()
except:
return False
elif isinstance(x, dict):
return (isinstance(y, dict)
and _element_equal(x.keys(), y.keys())
and all(_element_equal(x[k], y[k]) for k in x.keys()))
elif isinstance(x, float):
return abs(x - y) < 1e-5 * (abs(x) + abs(y))
elif isinstance(x, (list, tuple)):
return x == y
else:
return bool(x == y) | python | def _element_equal(x, y):
"""
Performs a robust equality test between elements.
"""
if isinstance(x, _np.ndarray) or isinstance(y, _np.ndarray):
try:
return (abs(_np.asarray(x) - _np.asarray(y)) < 1e-5).all()
except:
return False
elif isinstance(x, dict):
return (isinstance(y, dict)
and _element_equal(x.keys(), y.keys())
and all(_element_equal(x[k], y[k]) for k in x.keys()))
elif isinstance(x, float):
return abs(x - y) < 1e-5 * (abs(x) + abs(y))
elif isinstance(x, (list, tuple)):
return x == y
else:
return bool(x == y) | [
"def",
"_element_equal",
"(",
"x",
",",
"y",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"_np",
".",
"ndarray",
")",
"or",
"isinstance",
"(",
"y",
",",
"_np",
".",
"ndarray",
")",
":",
"try",
":",
"return",
"(",
"abs",
"(",
"_np",
".",
"asarray",
"(",
"x",
")",
"-",
"_np",
".",
"asarray",
"(",
"y",
")",
")",
"<",
"1e-5",
")",
".",
"all",
"(",
")",
"except",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"return",
"(",
"isinstance",
"(",
"y",
",",
"dict",
")",
"and",
"_element_equal",
"(",
"x",
".",
"keys",
"(",
")",
",",
"y",
".",
"keys",
"(",
")",
")",
"and",
"all",
"(",
"_element_equal",
"(",
"x",
"[",
"k",
"]",
",",
"y",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"x",
".",
"keys",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"x",
",",
"float",
")",
":",
"return",
"abs",
"(",
"x",
"-",
"y",
")",
"<",
"1e-5",
"*",
"(",
"abs",
"(",
"x",
")",
"+",
"abs",
"(",
"y",
")",
")",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"x",
"==",
"y",
"else",
":",
"return",
"bool",
"(",
"x",
"==",
"y",
")"
] | Performs a robust equality test between elements. | [
"Performs",
"a",
"robust",
"equality",
"test",
"between",
"elements",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L698-L716 |
28,874 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | evaluate_transformer | def evaluate_transformer(model, input_data, reference_output,
verbose=False):
"""
Evaluate a transformer specification for testing.
Parameters
----------
spec: [str | MLModel]
File from where to load the Model from (OR) a loaded
version of MLModel.
input_data: list[dict]
Test data on which to evaluate the models.
reference_output: list[dict]
Expected results for the model.
verbose: bool
Verbosity levels of the predictions.
Examples
--------
.. sourcecode:: python
>>> input_data = [{'input_1': 1, 'input_2': 2}, {'input_1': 3, 'input_2': 3}]
>>> expected_output = [{'input_1': 2.5, 'input_2': 2.0}, {'input_1': 1.3, 'input_2': 2.3}]
>>> metrics = coremltools.utils.evaluate_transformer(scaler_spec, input_data, expected_output)
See Also
--------
evaluate_regressor, evaluate_classifier
"""
model = _get_model(model)
if verbose:
print(model)
print("")
print("Other Framework\t\tPredicted")
num_errors = 0
for index, row in enumerate(input_data):
assert isinstance(row, dict)
sanitized_row = _sanitize_value(row)
ref_data = _sanitize_value(reference_output[index])
if verbose:
print("Input:\n\t", str(row))
print("Correct output:\n\t", str(ref_data))
predicted = _sanitize_value(model.predict(sanitized_row))
assert isinstance(ref_data, dict)
assert isinstance(predicted, dict)
predicted_trimmed = dict( (k, predicted[k]) for k in ref_data.keys())
if verbose:
print("Predicted:\n\t", str(predicted_trimmed))
if not _element_equal(predicted_trimmed, ref_data):
num_errors += 1
ret = {
"num_samples": len(input_data),
"num_errors": num_errors
}
if verbose:
print("results: %s" % ret)
return ret | python | def evaluate_transformer(model, input_data, reference_output,
verbose=False):
"""
Evaluate a transformer specification for testing.
Parameters
----------
spec: [str | MLModel]
File from where to load the Model from (OR) a loaded
version of MLModel.
input_data: list[dict]
Test data on which to evaluate the models.
reference_output: list[dict]
Expected results for the model.
verbose: bool
Verbosity levels of the predictions.
Examples
--------
.. sourcecode:: python
>>> input_data = [{'input_1': 1, 'input_2': 2}, {'input_1': 3, 'input_2': 3}]
>>> expected_output = [{'input_1': 2.5, 'input_2': 2.0}, {'input_1': 1.3, 'input_2': 2.3}]
>>> metrics = coremltools.utils.evaluate_transformer(scaler_spec, input_data, expected_output)
See Also
--------
evaluate_regressor, evaluate_classifier
"""
model = _get_model(model)
if verbose:
print(model)
print("")
print("Other Framework\t\tPredicted")
num_errors = 0
for index, row in enumerate(input_data):
assert isinstance(row, dict)
sanitized_row = _sanitize_value(row)
ref_data = _sanitize_value(reference_output[index])
if verbose:
print("Input:\n\t", str(row))
print("Correct output:\n\t", str(ref_data))
predicted = _sanitize_value(model.predict(sanitized_row))
assert isinstance(ref_data, dict)
assert isinstance(predicted, dict)
predicted_trimmed = dict( (k, predicted[k]) for k in ref_data.keys())
if verbose:
print("Predicted:\n\t", str(predicted_trimmed))
if not _element_equal(predicted_trimmed, ref_data):
num_errors += 1
ret = {
"num_samples": len(input_data),
"num_errors": num_errors
}
if verbose:
print("results: %s" % ret)
return ret | [
"def",
"evaluate_transformer",
"(",
"model",
",",
"input_data",
",",
"reference_output",
",",
"verbose",
"=",
"False",
")",
":",
"model",
"=",
"_get_model",
"(",
"model",
")",
"if",
"verbose",
":",
"print",
"(",
"model",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"Other Framework\\t\\tPredicted\"",
")",
"num_errors",
"=",
"0",
"for",
"index",
",",
"row",
"in",
"enumerate",
"(",
"input_data",
")",
":",
"assert",
"isinstance",
"(",
"row",
",",
"dict",
")",
"sanitized_row",
"=",
"_sanitize_value",
"(",
"row",
")",
"ref_data",
"=",
"_sanitize_value",
"(",
"reference_output",
"[",
"index",
"]",
")",
"if",
"verbose",
":",
"print",
"(",
"\"Input:\\n\\t\"",
",",
"str",
"(",
"row",
")",
")",
"print",
"(",
"\"Correct output:\\n\\t\"",
",",
"str",
"(",
"ref_data",
")",
")",
"predicted",
"=",
"_sanitize_value",
"(",
"model",
".",
"predict",
"(",
"sanitized_row",
")",
")",
"assert",
"isinstance",
"(",
"ref_data",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"predicted",
",",
"dict",
")",
"predicted_trimmed",
"=",
"dict",
"(",
"(",
"k",
",",
"predicted",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"ref_data",
".",
"keys",
"(",
")",
")",
"if",
"verbose",
":",
"print",
"(",
"\"Predicted:\\n\\t\"",
",",
"str",
"(",
"predicted_trimmed",
")",
")",
"if",
"not",
"_element_equal",
"(",
"predicted_trimmed",
",",
"ref_data",
")",
":",
"num_errors",
"+=",
"1",
"ret",
"=",
"{",
"\"num_samples\"",
":",
"len",
"(",
"input_data",
")",
",",
"\"num_errors\"",
":",
"num_errors",
"}",
"if",
"verbose",
":",
"print",
"(",
"\"results: %s\"",
"%",
"ret",
")",
"return",
"ret"
] | Evaluate a transformer specification for testing.
Parameters
----------
spec: [str | MLModel]
File from where to load the Model from (OR) a loaded
version of MLModel.
input_data: list[dict]
Test data on which to evaluate the models.
reference_output: list[dict]
Expected results for the model.
verbose: bool
Verbosity levels of the predictions.
Examples
--------
.. sourcecode:: python
>>> input_data = [{'input_1': 1, 'input_2': 2}, {'input_1': 3, 'input_2': 3}]
>>> expected_output = [{'input_1': 2.5, 'input_2': 2.0}, {'input_1': 1.3, 'input_2': 2.3}]
>>> metrics = coremltools.utils.evaluate_transformer(scaler_spec, input_data, expected_output)
See Also
--------
evaluate_regressor, evaluate_classifier | [
"Evaluate",
"a",
"transformer",
"specification",
"for",
"testing",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L719-L786 |
28,875 | apple/turicreate | src/unity/python/turicreate/toolkits/graph_analytics/degree_counting.py | create | def create(graph, verbose=True):
"""
Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel
"""
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('"graph" input must be a SGraph object.')
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.degree_count.create(
{'graph': graph.__proxy__})
return DegreeCountingModel(params['model']) | python | def create(graph, verbose=True):
"""
Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel
"""
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('"graph" input must be a SGraph object.')
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.degree_count.create(
{'graph': graph.__proxy__})
return DegreeCountingModel(params['model']) | [
"def",
"create",
"(",
"graph",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"turicreate",
".",
"_cython",
".",
"cy_server",
"import",
"QuietProgress",
"if",
"not",
"isinstance",
"(",
"graph",
",",
"_SGraph",
")",
":",
"raise",
"TypeError",
"(",
"'\"graph\" input must be a SGraph object.'",
")",
"with",
"QuietProgress",
"(",
"verbose",
")",
":",
"params",
"=",
"_tc",
".",
"extensions",
".",
"_toolkits",
".",
"graph",
".",
"degree_count",
".",
"create",
"(",
"{",
"'graph'",
":",
"graph",
".",
"__proxy__",
"}",
")",
"return",
"DegreeCountingModel",
"(",
"params",
"[",
"'model'",
"]",
")"
] | Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel | [
"Compute",
"the",
"in",
"degree",
"out",
"degree",
"and",
"total",
"degree",
"of",
"each",
"vertex",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/graph_analytics/degree_counting.py#L57-L119 |
28,876 | apple/turicreate | deps/src/boost_1_68_0/tools/litre/cplusplus.py | Example.replace_emphasis | def replace_emphasis(self, s, index = 0):
"""replace the index'th emphasized text with s"""
e = self.emphasized[index]
self.body[e[0]:e[1]] = [s]
del self.emphasized[index] | python | def replace_emphasis(self, s, index = 0):
"""replace the index'th emphasized text with s"""
e = self.emphasized[index]
self.body[e[0]:e[1]] = [s]
del self.emphasized[index] | [
"def",
"replace_emphasis",
"(",
"self",
",",
"s",
",",
"index",
"=",
"0",
")",
":",
"e",
"=",
"self",
".",
"emphasized",
"[",
"index",
"]",
"self",
".",
"body",
"[",
"e",
"[",
"0",
"]",
":",
"e",
"[",
"1",
"]",
"]",
"=",
"[",
"s",
"]",
"del",
"self",
".",
"emphasized",
"[",
"index",
"]"
] | replace the index'th emphasized text with s | [
"replace",
"the",
"index",
"th",
"emphasized",
"text",
"with",
"s"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/litre/cplusplus.py#L90-L94 |
28,877 | apple/turicreate | deps/src/boost_1_68_0/tools/litre/cplusplus.py | CPlusPlusTranslator._execute | def _execute(self, code):
"""Override of litre._execute; sets up variable context before
evaluating code
"""
self.globals['example'] = self.example
eval(code, self.globals) | python | def _execute(self, code):
"""Override of litre._execute; sets up variable context before
evaluating code
"""
self.globals['example'] = self.example
eval(code, self.globals) | [
"def",
"_execute",
"(",
"self",
",",
"code",
")",
":",
"self",
".",
"globals",
"[",
"'example'",
"]",
"=",
"self",
".",
"example",
"eval",
"(",
"code",
",",
"self",
".",
"globals",
")"
] | Override of litre._execute; sets up variable context before
evaluating code | [
"Override",
"of",
"litre",
".",
"_execute",
";",
"sets",
"up",
"variable",
"context",
"before",
"evaluating",
"code"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/litre/cplusplus.py#L320-L325 |
28,878 | apple/turicreate | deps/src/boost_1_68_0/tools/litre/cplusplus.py | CPlusPlusTranslator.compile | def compile(
self
, howmany = 1
, pop = -1
, expect_error = False
, extension = '.o'
, options = ['-c']
, built_handler = lambda built_file: None
, source_file = None
, source_suffix = '.cpp'
# C-style comments by default; handles C++ and YACC
, make_comment = lambda text: '/*\n%s\n*/' % text
, built_file = None
, command = None
):
"""
Compile examples on the stack, whose topmost item is the last example
seen but not yet handled so far.
:howmany: How many of the topmost examples on the stack to compile.
You can pass a number, or 'all' to indicate that all examples should
be compiled.
:pop: How many of the topmost examples to discard. By default, all of
the examples that are compiled are discarded.
:expect_error: Whether a compilation error is to be expected. Any value
> 1 will cause the expected diagnostic's text to be dumped for
diagnostic purposes. It's common to expect an error but see a
completely unrelated one because of bugs in the example (you can get
this behavior for all examples by setting show_expected_error_output
in your config).
:extension: The extension of the file to build (set to .exe for
run)
:options: Compiler flags
:built_file: A path to use for the built file. By default, a temp
filename is conjured up
:built_handler: A function that's called with the name of the built file
upon success.
:source_file: The full name of the source file to write
:source_suffix: If source_file is None, the suffix to use for the source file
:make_comment: A function that transforms text into an appropriate comment.
:command: A function that is passed (includes, opts, target, source), where
opts is a string representing compiler options, target is the name of
the file to build, and source is the name of the file into which the
example code is written. By default, the function formats
litre.config.compiler with its argument tuple.
"""
# Grab one example by default
if howmany == 'all':
howmany = len(self.stack)
source = '\n'.join(
self.prefix
+ [str(x) for x in self.stack[-howmany:]]
)
source = reduce(lambda s, f: f(s), self.preprocessors, source)
if pop:
if pop < 0:
pop = howmany
del self.stack[-pop:]
if len(self.stack):
self.example = self.stack[-1]
cpp = self._source_file_path(source_file, source_suffix)
if built_file is None:
built_file = self._output_file_path(source_file, extension)
opts = ' '.join(options)
includes = ' '.join(['-I%s' % d for d in self.includes])
if not command:
command = self.config.compiler
if type(command) == str:
command = lambda i, o, t, s, c = command: c % (i, o, t, s)
cmd = command(includes, opts, expand_vars(built_file), expand_vars(cpp))
if expect_error and self.config.show_expected_error_output:
expect_error += 1
comment_cmd = command(includes, opts, built_file, os.path.basename(cpp))
comment = make_comment(config.comment_text(comment_cmd, expect_error))
self._write_source(cpp, '\n'.join([comment, source]))
#print 'wrote in', cpp
#print 'trying command', cmd
status, output = syscmd(cmd, expect_error)
if status or expect_error > 1:
print
if expect_error and expect_error < 2:
print 'Compilation failure expected, but none seen'
print '------------ begin offending source ------------'
print open(cpp).read()
print '------------ end offending source ------------'
if self.config.save_cpp:
print 'saved in', repr(cpp)
else:
self._remove_source(cpp)
sys.stdout.flush()
else:
print '.',
sys.stdout.flush()
built_handler(built_file)
self._remove_source(cpp)
try:
self._unlink(built_file)
except:
if not expect_error:
print 'failed to unlink', built_file
return status | python | def compile(
self
, howmany = 1
, pop = -1
, expect_error = False
, extension = '.o'
, options = ['-c']
, built_handler = lambda built_file: None
, source_file = None
, source_suffix = '.cpp'
# C-style comments by default; handles C++ and YACC
, make_comment = lambda text: '/*\n%s\n*/' % text
, built_file = None
, command = None
):
"""
Compile examples on the stack, whose topmost item is the last example
seen but not yet handled so far.
:howmany: How many of the topmost examples on the stack to compile.
You can pass a number, or 'all' to indicate that all examples should
be compiled.
:pop: How many of the topmost examples to discard. By default, all of
the examples that are compiled are discarded.
:expect_error: Whether a compilation error is to be expected. Any value
> 1 will cause the expected diagnostic's text to be dumped for
diagnostic purposes. It's common to expect an error but see a
completely unrelated one because of bugs in the example (you can get
this behavior for all examples by setting show_expected_error_output
in your config).
:extension: The extension of the file to build (set to .exe for
run)
:options: Compiler flags
:built_file: A path to use for the built file. By default, a temp
filename is conjured up
:built_handler: A function that's called with the name of the built file
upon success.
:source_file: The full name of the source file to write
:source_suffix: If source_file is None, the suffix to use for the source file
:make_comment: A function that transforms text into an appropriate comment.
:command: A function that is passed (includes, opts, target, source), where
opts is a string representing compiler options, target is the name of
the file to build, and source is the name of the file into which the
example code is written. By default, the function formats
litre.config.compiler with its argument tuple.
"""
# Grab one example by default
if howmany == 'all':
howmany = len(self.stack)
source = '\n'.join(
self.prefix
+ [str(x) for x in self.stack[-howmany:]]
)
source = reduce(lambda s, f: f(s), self.preprocessors, source)
if pop:
if pop < 0:
pop = howmany
del self.stack[-pop:]
if len(self.stack):
self.example = self.stack[-1]
cpp = self._source_file_path(source_file, source_suffix)
if built_file is None:
built_file = self._output_file_path(source_file, extension)
opts = ' '.join(options)
includes = ' '.join(['-I%s' % d for d in self.includes])
if not command:
command = self.config.compiler
if type(command) == str:
command = lambda i, o, t, s, c = command: c % (i, o, t, s)
cmd = command(includes, opts, expand_vars(built_file), expand_vars(cpp))
if expect_error and self.config.show_expected_error_output:
expect_error += 1
comment_cmd = command(includes, opts, built_file, os.path.basename(cpp))
comment = make_comment(config.comment_text(comment_cmd, expect_error))
self._write_source(cpp, '\n'.join([comment, source]))
#print 'wrote in', cpp
#print 'trying command', cmd
status, output = syscmd(cmd, expect_error)
if status or expect_error > 1:
print
if expect_error and expect_error < 2:
print 'Compilation failure expected, but none seen'
print '------------ begin offending source ------------'
print open(cpp).read()
print '------------ end offending source ------------'
if self.config.save_cpp:
print 'saved in', repr(cpp)
else:
self._remove_source(cpp)
sys.stdout.flush()
else:
print '.',
sys.stdout.flush()
built_handler(built_file)
self._remove_source(cpp)
try:
self._unlink(built_file)
except:
if not expect_error:
print 'failed to unlink', built_file
return status | [
"def",
"compile",
"(",
"self",
",",
"howmany",
"=",
"1",
",",
"pop",
"=",
"-",
"1",
",",
"expect_error",
"=",
"False",
",",
"extension",
"=",
"'.o'",
",",
"options",
"=",
"[",
"'-c'",
"]",
",",
"built_handler",
"=",
"lambda",
"built_file",
":",
"None",
",",
"source_file",
"=",
"None",
",",
"source_suffix",
"=",
"'.cpp'",
"# C-style comments by default; handles C++ and YACC",
",",
"make_comment",
"=",
"lambda",
"text",
":",
"'/*\\n%s\\n*/'",
"%",
"text",
",",
"built_file",
"=",
"None",
",",
"command",
"=",
"None",
")",
":",
"# Grab one example by default",
"if",
"howmany",
"==",
"'all'",
":",
"howmany",
"=",
"len",
"(",
"self",
".",
"stack",
")",
"source",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"prefix",
"+",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"stack",
"[",
"-",
"howmany",
":",
"]",
"]",
")",
"source",
"=",
"reduce",
"(",
"lambda",
"s",
",",
"f",
":",
"f",
"(",
"s",
")",
",",
"self",
".",
"preprocessors",
",",
"source",
")",
"if",
"pop",
":",
"if",
"pop",
"<",
"0",
":",
"pop",
"=",
"howmany",
"del",
"self",
".",
"stack",
"[",
"-",
"pop",
":",
"]",
"if",
"len",
"(",
"self",
".",
"stack",
")",
":",
"self",
".",
"example",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"cpp",
"=",
"self",
".",
"_source_file_path",
"(",
"source_file",
",",
"source_suffix",
")",
"if",
"built_file",
"is",
"None",
":",
"built_file",
"=",
"self",
".",
"_output_file_path",
"(",
"source_file",
",",
"extension",
")",
"opts",
"=",
"' '",
".",
"join",
"(",
"options",
")",
"includes",
"=",
"' '",
".",
"join",
"(",
"[",
"'-I%s'",
"%",
"d",
"for",
"d",
"in",
"self",
".",
"includes",
"]",
")",
"if",
"not",
"command",
":",
"command",
"=",
"self",
".",
"config",
".",
"compiler",
"if",
"type",
"(",
"command",
")",
"==",
"str",
":",
"command",
"=",
"lambda",
"i",
",",
"o",
",",
"t",
",",
"s",
",",
"c",
"=",
"command",
":",
"c",
"%",
"(",
"i",
",",
"o",
",",
"t",
",",
"s",
")",
"cmd",
"=",
"command",
"(",
"includes",
",",
"opts",
",",
"expand_vars",
"(",
"built_file",
")",
",",
"expand_vars",
"(",
"cpp",
")",
")",
"if",
"expect_error",
"and",
"self",
".",
"config",
".",
"show_expected_error_output",
":",
"expect_error",
"+=",
"1",
"comment_cmd",
"=",
"command",
"(",
"includes",
",",
"opts",
",",
"built_file",
",",
"os",
".",
"path",
".",
"basename",
"(",
"cpp",
")",
")",
"comment",
"=",
"make_comment",
"(",
"config",
".",
"comment_text",
"(",
"comment_cmd",
",",
"expect_error",
")",
")",
"self",
".",
"_write_source",
"(",
"cpp",
",",
"'\\n'",
".",
"join",
"(",
"[",
"comment",
",",
"source",
"]",
")",
")",
"#print 'wrote in', cpp",
"#print 'trying command', cmd",
"status",
",",
"output",
"=",
"syscmd",
"(",
"cmd",
",",
"expect_error",
")",
"if",
"status",
"or",
"expect_error",
">",
"1",
":",
"print",
"if",
"expect_error",
"and",
"expect_error",
"<",
"2",
":",
"print",
"'Compilation failure expected, but none seen'",
"print",
"'------------ begin offending source ------------'",
"print",
"open",
"(",
"cpp",
")",
".",
"read",
"(",
")",
"print",
"'------------ end offending source ------------'",
"if",
"self",
".",
"config",
".",
"save_cpp",
":",
"print",
"'saved in'",
",",
"repr",
"(",
"cpp",
")",
"else",
":",
"self",
".",
"_remove_source",
"(",
"cpp",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"else",
":",
"print",
"'.'",
",",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"built_handler",
"(",
"built_file",
")",
"self",
".",
"_remove_source",
"(",
"cpp",
")",
"try",
":",
"self",
".",
"_unlink",
"(",
"built_file",
")",
"except",
":",
"if",
"not",
"expect_error",
":",
"print",
"'failed to unlink'",
",",
"built_file",
"return",
"status"
] | Compile examples on the stack, whose topmost item is the last example
seen but not yet handled so far.
:howmany: How many of the topmost examples on the stack to compile.
You can pass a number, or 'all' to indicate that all examples should
be compiled.
:pop: How many of the topmost examples to discard. By default, all of
the examples that are compiled are discarded.
:expect_error: Whether a compilation error is to be expected. Any value
> 1 will cause the expected diagnostic's text to be dumped for
diagnostic purposes. It's common to expect an error but see a
completely unrelated one because of bugs in the example (you can get
this behavior for all examples by setting show_expected_error_output
in your config).
:extension: The extension of the file to build (set to .exe for
run)
:options: Compiler flags
:built_file: A path to use for the built file. By default, a temp
filename is conjured up
:built_handler: A function that's called with the name of the built file
upon success.
:source_file: The full name of the source file to write
:source_suffix: If source_file is None, the suffix to use for the source file
:make_comment: A function that transforms text into an appropriate comment.
:command: A function that is passed (includes, opts, target, source), where
opts is a string representing compiler options, target is the name of
the file to build, and source is the name of the file into which the
example code is written. By default, the function formats
litre.config.compiler with its argument tuple. | [
"Compile",
"examples",
"on",
"the",
"stack",
"whose",
"topmost",
"item",
"is",
"the",
"last",
"example",
"seen",
"but",
"not",
"yet",
"handled",
"so",
"far",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/litre/cplusplus.py#L357-L490 |
28,879 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load | def load (self, jamfile_location):
"""Loads jamfile at the given location. After loading, project global
file and jamfile needed by the loaded one will be loaded recursively.
If the jamfile at that location is loaded already, does nothing.
Returns the project module for the Jamfile."""
assert isinstance(jamfile_location, basestring)
absolute = os.path.join(os.getcwd(), jamfile_location)
absolute = os.path.normpath(absolute)
jamfile_location = b2.util.path.relpath(os.getcwd(), absolute)
mname = self.module_name(jamfile_location)
# If Jamfile is already loaded, do not try again.
if not mname in self.jamfile_modules:
if "--debug-loading" in self.manager.argv():
print "Loading Jamfile at '%s'" % jamfile_location
self.load_jamfile(jamfile_location, mname)
# We want to make sure that child project are loaded only
# after parent projects. In particular, because parent projects
# define attributes which are inherited by children, and we do not
# want children to be loaded before parents has defined everything.
#
# While "build-project" and "use-project" can potentially refer
# to child projects from parent projects, we do not immediately
# load child projects when seing those attributes. Instead,
# we record the minimal information that will be used only later.
self.load_used_projects(mname)
return mname | python | def load (self, jamfile_location):
"""Loads jamfile at the given location. After loading, project global
file and jamfile needed by the loaded one will be loaded recursively.
If the jamfile at that location is loaded already, does nothing.
Returns the project module for the Jamfile."""
assert isinstance(jamfile_location, basestring)
absolute = os.path.join(os.getcwd(), jamfile_location)
absolute = os.path.normpath(absolute)
jamfile_location = b2.util.path.relpath(os.getcwd(), absolute)
mname = self.module_name(jamfile_location)
# If Jamfile is already loaded, do not try again.
if not mname in self.jamfile_modules:
if "--debug-loading" in self.manager.argv():
print "Loading Jamfile at '%s'" % jamfile_location
self.load_jamfile(jamfile_location, mname)
# We want to make sure that child project are loaded only
# after parent projects. In particular, because parent projects
# define attributes which are inherited by children, and we do not
# want children to be loaded before parents has defined everything.
#
# While "build-project" and "use-project" can potentially refer
# to child projects from parent projects, we do not immediately
# load child projects when seing those attributes. Instead,
# we record the minimal information that will be used only later.
self.load_used_projects(mname)
return mname | [
"def",
"load",
"(",
"self",
",",
"jamfile_location",
")",
":",
"assert",
"isinstance",
"(",
"jamfile_location",
",",
"basestring",
")",
"absolute",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"jamfile_location",
")",
"absolute",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"absolute",
")",
"jamfile_location",
"=",
"b2",
".",
"util",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"absolute",
")",
"mname",
"=",
"self",
".",
"module_name",
"(",
"jamfile_location",
")",
"# If Jamfile is already loaded, do not try again.",
"if",
"not",
"mname",
"in",
"self",
".",
"jamfile_modules",
":",
"if",
"\"--debug-loading\"",
"in",
"self",
".",
"manager",
".",
"argv",
"(",
")",
":",
"print",
"\"Loading Jamfile at '%s'\"",
"%",
"jamfile_location",
"self",
".",
"load_jamfile",
"(",
"jamfile_location",
",",
"mname",
")",
"# We want to make sure that child project are loaded only",
"# after parent projects. In particular, because parent projects",
"# define attributes which are inherited by children, and we do not",
"# want children to be loaded before parents has defined everything.",
"#",
"# While \"build-project\" and \"use-project\" can potentially refer",
"# to child projects from parent projects, we do not immediately",
"# load child projects when seing those attributes. Instead,",
"# we record the minimal information that will be used only later.",
"self",
".",
"load_used_projects",
"(",
"mname",
")",
"return",
"mname"
] | Loads jamfile at the given location. After loading, project global
file and jamfile needed by the loaded one will be loaded recursively.
If the jamfile at that location is loaded already, does nothing.
Returns the project module for the Jamfile. | [
"Loads",
"jamfile",
"at",
"the",
"given",
"location",
".",
"After",
"loading",
"project",
"global",
"file",
"and",
"jamfile",
"needed",
"by",
"the",
"loaded",
"one",
"will",
"be",
"loaded",
"recursively",
".",
"If",
"the",
"jamfile",
"at",
"that",
"location",
"is",
"loaded",
"already",
"does",
"nothing",
".",
"Returns",
"the",
"project",
"module",
"for",
"the",
"Jamfile",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L132-L164 |
28,880 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load_parent | def load_parent(self, location):
"""Loads parent of Jamfile at 'location'.
Issues an error if nothing is found."""
assert isinstance(location, basestring)
found = b2.util.path.glob_in_parents(
location, self.JAMROOT + self.JAMFILE)
if not found:
print "error: Could not find parent for project at '%s'" % location
print "error: Did not find Jamfile.jam or Jamroot.jam in any parent directory."
sys.exit(1)
return self.load(os.path.dirname(found[0])) | python | def load_parent(self, location):
"""Loads parent of Jamfile at 'location'.
Issues an error if nothing is found."""
assert isinstance(location, basestring)
found = b2.util.path.glob_in_parents(
location, self.JAMROOT + self.JAMFILE)
if not found:
print "error: Could not find parent for project at '%s'" % location
print "error: Did not find Jamfile.jam or Jamroot.jam in any parent directory."
sys.exit(1)
return self.load(os.path.dirname(found[0])) | [
"def",
"load_parent",
"(",
"self",
",",
"location",
")",
":",
"assert",
"isinstance",
"(",
"location",
",",
"basestring",
")",
"found",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob_in_parents",
"(",
"location",
",",
"self",
".",
"JAMROOT",
"+",
"self",
".",
"JAMFILE",
")",
"if",
"not",
"found",
":",
"print",
"\"error: Could not find parent for project at '%s'\"",
"%",
"location",
"print",
"\"error: Did not find Jamfile.jam or Jamroot.jam in any parent directory.\"",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"self",
".",
"load",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"found",
"[",
"0",
"]",
")",
")"
] | Loads parent of Jamfile at 'location'.
Issues an error if nothing is found. | [
"Loads",
"parent",
"of",
"Jamfile",
"at",
"location",
".",
"Issues",
"an",
"error",
"if",
"nothing",
"is",
"found",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L178-L190 |
28,881 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.find | def find(self, name, current_location):
"""Given 'name' which can be project-id or plain directory name,
return project module corresponding to that id or directory.
Returns nothing of project is not found."""
assert isinstance(name, basestring)
assert isinstance(current_location, basestring)
project_module = None
# Try interpreting name as project id.
if name[0] == '/':
project_module = self.id2module.get(name)
if not project_module:
location = os.path.join(current_location, name)
# If no project is registered for the given location, try to
# load it. First see if we have Jamfile. If not we might have project
# root, willing to act as Jamfile. In that case, project-root
# must be placed in the directory referred by id.
project_module = self.module_name(location)
if not project_module in self.jamfile_modules:
if b2.util.path.glob([location], self.JAMROOT + self.JAMFILE):
project_module = self.load(location)
else:
project_module = None
return project_module | python | def find(self, name, current_location):
"""Given 'name' which can be project-id or plain directory name,
return project module corresponding to that id or directory.
Returns nothing of project is not found."""
assert isinstance(name, basestring)
assert isinstance(current_location, basestring)
project_module = None
# Try interpreting name as project id.
if name[0] == '/':
project_module = self.id2module.get(name)
if not project_module:
location = os.path.join(current_location, name)
# If no project is registered for the given location, try to
# load it. First see if we have Jamfile. If not we might have project
# root, willing to act as Jamfile. In that case, project-root
# must be placed in the directory referred by id.
project_module = self.module_name(location)
if not project_module in self.jamfile_modules:
if b2.util.path.glob([location], self.JAMROOT + self.JAMFILE):
project_module = self.load(location)
else:
project_module = None
return project_module | [
"def",
"find",
"(",
"self",
",",
"name",
",",
"current_location",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"current_location",
",",
"basestring",
")",
"project_module",
"=",
"None",
"# Try interpreting name as project id.",
"if",
"name",
"[",
"0",
"]",
"==",
"'/'",
":",
"project_module",
"=",
"self",
".",
"id2module",
".",
"get",
"(",
"name",
")",
"if",
"not",
"project_module",
":",
"location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_location",
",",
"name",
")",
"# If no project is registered for the given location, try to",
"# load it. First see if we have Jamfile. If not we might have project",
"# root, willing to act as Jamfile. In that case, project-root",
"# must be placed in the directory referred by id.",
"project_module",
"=",
"self",
".",
"module_name",
"(",
"location",
")",
"if",
"not",
"project_module",
"in",
"self",
".",
"jamfile_modules",
":",
"if",
"b2",
".",
"util",
".",
"path",
".",
"glob",
"(",
"[",
"location",
"]",
",",
"self",
".",
"JAMROOT",
"+",
"self",
".",
"JAMFILE",
")",
":",
"project_module",
"=",
"self",
".",
"load",
"(",
"location",
")",
"else",
":",
"project_module",
"=",
"None",
"return",
"project_module"
] | Given 'name' which can be project-id or plain directory name,
return project module corresponding to that id or directory.
Returns nothing of project is not found. | [
"Given",
"name",
"which",
"can",
"be",
"project",
"-",
"id",
"or",
"plain",
"directory",
"name",
"return",
"project",
"module",
"corresponding",
"to",
"that",
"id",
"or",
"directory",
".",
"Returns",
"nothing",
"of",
"project",
"is",
"not",
"found",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L192-L219 |
28,882 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.module_name | def module_name(self, jamfile_location):
"""Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location."""
assert isinstance(jamfile_location, basestring)
module = self.location2module.get(jamfile_location)
if not module:
# Root the path, so that locations are always umbiguious.
# Without this, we can't decide if '../../exe/program1' and '.'
# are the same paths, or not.
jamfile_location = os.path.realpath(
os.path.join(os.getcwd(), jamfile_location))
module = "Jamfile<%s>" % jamfile_location
self.location2module[jamfile_location] = module
return module | python | def module_name(self, jamfile_location):
"""Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location."""
assert isinstance(jamfile_location, basestring)
module = self.location2module.get(jamfile_location)
if not module:
# Root the path, so that locations are always umbiguious.
# Without this, we can't decide if '../../exe/program1' and '.'
# are the same paths, or not.
jamfile_location = os.path.realpath(
os.path.join(os.getcwd(), jamfile_location))
module = "Jamfile<%s>" % jamfile_location
self.location2module[jamfile_location] = module
return module | [
"def",
"module_name",
"(",
"self",
",",
"jamfile_location",
")",
":",
"assert",
"isinstance",
"(",
"jamfile_location",
",",
"basestring",
")",
"module",
"=",
"self",
".",
"location2module",
".",
"get",
"(",
"jamfile_location",
")",
"if",
"not",
"module",
":",
"# Root the path, so that locations are always umbiguious.",
"# Without this, we can't decide if '../../exe/program1' and '.'",
"# are the same paths, or not.",
"jamfile_location",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"jamfile_location",
")",
")",
"module",
"=",
"\"Jamfile<%s>\"",
"%",
"jamfile_location",
"self",
".",
"location2module",
"[",
"jamfile_location",
"]",
"=",
"module",
"return",
"module"
] | Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location. | [
"Returns",
"the",
"name",
"of",
"module",
"corresponding",
"to",
"jamfile",
"-",
"location",
".",
"If",
"no",
"module",
"corresponds",
"to",
"location",
"yet",
"associates",
"default",
"module",
"name",
"with",
"that",
"location",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L221-L235 |
28,883 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load_standalone | def load_standalone(self, jamfile_module, file):
"""Loads 'file' as standalone project that has no location
associated with it. This is mostly useful for user-config.jam,
which should be able to define targets, but although it has
some location in filesystem, we do not want any build to
happen in user's HOME, for example.
The caller is required to never call this method twice on
the same file.
"""
assert isinstance(jamfile_module, basestring)
assert isinstance(file, basestring)
self.used_projects[jamfile_module] = []
bjam.call("load", jamfile_module, file)
self.load_used_projects(jamfile_module) | python | def load_standalone(self, jamfile_module, file):
"""Loads 'file' as standalone project that has no location
associated with it. This is mostly useful for user-config.jam,
which should be able to define targets, but although it has
some location in filesystem, we do not want any build to
happen in user's HOME, for example.
The caller is required to never call this method twice on
the same file.
"""
assert isinstance(jamfile_module, basestring)
assert isinstance(file, basestring)
self.used_projects[jamfile_module] = []
bjam.call("load", jamfile_module, file)
self.load_used_projects(jamfile_module) | [
"def",
"load_standalone",
"(",
"self",
",",
"jamfile_module",
",",
"file",
")",
":",
"assert",
"isinstance",
"(",
"jamfile_module",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"file",
",",
"basestring",
")",
"self",
".",
"used_projects",
"[",
"jamfile_module",
"]",
"=",
"[",
"]",
"bjam",
".",
"call",
"(",
"\"load\"",
",",
"jamfile_module",
",",
"file",
")",
"self",
".",
"load_used_projects",
"(",
"jamfile_module",
")"
] | Loads 'file' as standalone project that has no location
associated with it. This is mostly useful for user-config.jam,
which should be able to define targets, but although it has
some location in filesystem, we do not want any build to
happen in user's HOME, for example.
The caller is required to never call this method twice on
the same file. | [
"Loads",
"file",
"as",
"standalone",
"project",
"that",
"has",
"no",
"location",
"associated",
"with",
"it",
".",
"This",
"is",
"mostly",
"useful",
"for",
"user",
"-",
"config",
".",
"jam",
"which",
"should",
"be",
"able",
"to",
"define",
"targets",
"but",
"although",
"it",
"has",
"some",
"location",
"in",
"filesystem",
"we",
"do",
"not",
"want",
"any",
"build",
"to",
"happen",
"in",
"user",
"s",
"HOME",
"for",
"example",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L387-L402 |
28,884 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.initialize | def initialize(self, module_name, location=None, basename=None, standalone_path=''):
"""Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side.
"""
assert isinstance(module_name, basestring)
assert isinstance(location, basestring) or location is None
assert isinstance(basename, basestring) or basename is None
jamroot = False
parent_module = None
if module_name == "test-config":
# No parent
pass
elif module_name == "site-config":
parent_module = "test-config"
elif module_name == "user-config":
parent_module = "site-config"
elif module_name == "project-config":
parent_module = "user-config"
elif location and not self.is_jamroot(basename):
# We search for parent/project-root only if jamfile was specified
# --- i.e
# if the project is not standalone.
parent_module = self.load_parent(location)
elif location:
# It's either jamroot, or standalone project.
# If it's jamroot, inherit from user-config.
# If project-config module exist, inherit from it.
parent_module = 'user-config'
if 'project-config' in self.module2attributes:
parent_module = 'project-config'
jamroot = True
# TODO: need to consider if standalone projects can do anything but defining
# prebuilt targets. If so, we need to give more sensible "location", so that
# source paths are correct.
if not location:
location = ""
# the call to load_parent() above can end up loading this module again
# make sure we don't reinitialize the module's attributes
if module_name not in self.module2attributes:
if "--debug-loading" in self.manager.argv():
print "Initializing project '%s'" % module_name
attributes = ProjectAttributes(self.manager, location, module_name)
self.module2attributes[module_name] = attributes
python_standalone = False
if location:
attributes.set("source-location", [location], exact=1)
elif not module_name in ["test-config", "site-config", "user-config", "project-config"]:
# This is a standalone project with known location. Set source location
# so that it can declare targets. This is intended so that you can put
# a .jam file in your sources and use it via 'using'. Standard modules
# (in 'tools' subdir) may not assume source dir is set.
source_location = standalone_path
if not source_location:
source_location = self.loaded_tool_module_path_.get(module_name)
if not source_location:
self.manager.errors()('Standalone module path not found for "{}"'
.format(module_name))
attributes.set("source-location", [source_location], exact=1)
python_standalone = True
attributes.set("requirements", property_set.empty(), exact=True)
attributes.set("usage-requirements", property_set.empty(), exact=True)
attributes.set("default-build", property_set.empty(), exact=True)
attributes.set("projects-to-build", [], exact=True)
attributes.set("project-root", None, exact=True)
attributes.set("build-dir", None, exact=True)
self.project_rules_.init_project(module_name, python_standalone)
if parent_module:
self.inherit_attributes(module_name, parent_module)
attributes.set("parent-module", parent_module, exact=1)
if jamroot:
attributes.set("project-root", location, exact=1)
parent = None
if parent_module:
parent = self.target(parent_module)
if module_name not in self.module2target:
target = b2.build.targets.ProjectTarget(self.manager,
module_name, module_name, parent,
self.attribute(module_name, "requirements"),
# FIXME: why we need to pass this? It's not
# passed in jam code.
self.attribute(module_name, "default-build"))
self.module2target[module_name] = target
self.current_project = self.target(module_name) | python | def initialize(self, module_name, location=None, basename=None, standalone_path=''):
"""Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side.
"""
assert isinstance(module_name, basestring)
assert isinstance(location, basestring) or location is None
assert isinstance(basename, basestring) or basename is None
jamroot = False
parent_module = None
if module_name == "test-config":
# No parent
pass
elif module_name == "site-config":
parent_module = "test-config"
elif module_name == "user-config":
parent_module = "site-config"
elif module_name == "project-config":
parent_module = "user-config"
elif location and not self.is_jamroot(basename):
# We search for parent/project-root only if jamfile was specified
# --- i.e
# if the project is not standalone.
parent_module = self.load_parent(location)
elif location:
# It's either jamroot, or standalone project.
# If it's jamroot, inherit from user-config.
# If project-config module exist, inherit from it.
parent_module = 'user-config'
if 'project-config' in self.module2attributes:
parent_module = 'project-config'
jamroot = True
# TODO: need to consider if standalone projects can do anything but defining
# prebuilt targets. If so, we need to give more sensible "location", so that
# source paths are correct.
if not location:
location = ""
# the call to load_parent() above can end up loading this module again
# make sure we don't reinitialize the module's attributes
if module_name not in self.module2attributes:
if "--debug-loading" in self.manager.argv():
print "Initializing project '%s'" % module_name
attributes = ProjectAttributes(self.manager, location, module_name)
self.module2attributes[module_name] = attributes
python_standalone = False
if location:
attributes.set("source-location", [location], exact=1)
elif not module_name in ["test-config", "site-config", "user-config", "project-config"]:
# This is a standalone project with known location. Set source location
# so that it can declare targets. This is intended so that you can put
# a .jam file in your sources and use it via 'using'. Standard modules
# (in 'tools' subdir) may not assume source dir is set.
source_location = standalone_path
if not source_location:
source_location = self.loaded_tool_module_path_.get(module_name)
if not source_location:
self.manager.errors()('Standalone module path not found for "{}"'
.format(module_name))
attributes.set("source-location", [source_location], exact=1)
python_standalone = True
attributes.set("requirements", property_set.empty(), exact=True)
attributes.set("usage-requirements", property_set.empty(), exact=True)
attributes.set("default-build", property_set.empty(), exact=True)
attributes.set("projects-to-build", [], exact=True)
attributes.set("project-root", None, exact=True)
attributes.set("build-dir", None, exact=True)
self.project_rules_.init_project(module_name, python_standalone)
if parent_module:
self.inherit_attributes(module_name, parent_module)
attributes.set("parent-module", parent_module, exact=1)
if jamroot:
attributes.set("project-root", location, exact=1)
parent = None
if parent_module:
parent = self.target(parent_module)
if module_name not in self.module2target:
target = b2.build.targets.ProjectTarget(self.manager,
module_name, module_name, parent,
self.attribute(module_name, "requirements"),
# FIXME: why we need to pass this? It's not
# passed in jam code.
self.attribute(module_name, "default-build"))
self.module2target[module_name] = target
self.current_project = self.target(module_name) | [
"def",
"initialize",
"(",
"self",
",",
"module_name",
",",
"location",
"=",
"None",
",",
"basename",
"=",
"None",
",",
"standalone_path",
"=",
"''",
")",
":",
"assert",
"isinstance",
"(",
"module_name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"location",
",",
"basestring",
")",
"or",
"location",
"is",
"None",
"assert",
"isinstance",
"(",
"basename",
",",
"basestring",
")",
"or",
"basename",
"is",
"None",
"jamroot",
"=",
"False",
"parent_module",
"=",
"None",
"if",
"module_name",
"==",
"\"test-config\"",
":",
"# No parent",
"pass",
"elif",
"module_name",
"==",
"\"site-config\"",
":",
"parent_module",
"=",
"\"test-config\"",
"elif",
"module_name",
"==",
"\"user-config\"",
":",
"parent_module",
"=",
"\"site-config\"",
"elif",
"module_name",
"==",
"\"project-config\"",
":",
"parent_module",
"=",
"\"user-config\"",
"elif",
"location",
"and",
"not",
"self",
".",
"is_jamroot",
"(",
"basename",
")",
":",
"# We search for parent/project-root only if jamfile was specified",
"# --- i.e",
"# if the project is not standalone.",
"parent_module",
"=",
"self",
".",
"load_parent",
"(",
"location",
")",
"elif",
"location",
":",
"# It's either jamroot, or standalone project.",
"# If it's jamroot, inherit from user-config.",
"# If project-config module exist, inherit from it.",
"parent_module",
"=",
"'user-config'",
"if",
"'project-config'",
"in",
"self",
".",
"module2attributes",
":",
"parent_module",
"=",
"'project-config'",
"jamroot",
"=",
"True",
"# TODO: need to consider if standalone projects can do anything but defining",
"# prebuilt targets. If so, we need to give more sensible \"location\", so that",
"# source paths are correct.",
"if",
"not",
"location",
":",
"location",
"=",
"\"\"",
"# the call to load_parent() above can end up loading this module again",
"# make sure we don't reinitialize the module's attributes",
"if",
"module_name",
"not",
"in",
"self",
".",
"module2attributes",
":",
"if",
"\"--debug-loading\"",
"in",
"self",
".",
"manager",
".",
"argv",
"(",
")",
":",
"print",
"\"Initializing project '%s'\"",
"%",
"module_name",
"attributes",
"=",
"ProjectAttributes",
"(",
"self",
".",
"manager",
",",
"location",
",",
"module_name",
")",
"self",
".",
"module2attributes",
"[",
"module_name",
"]",
"=",
"attributes",
"python_standalone",
"=",
"False",
"if",
"location",
":",
"attributes",
".",
"set",
"(",
"\"source-location\"",
",",
"[",
"location",
"]",
",",
"exact",
"=",
"1",
")",
"elif",
"not",
"module_name",
"in",
"[",
"\"test-config\"",
",",
"\"site-config\"",
",",
"\"user-config\"",
",",
"\"project-config\"",
"]",
":",
"# This is a standalone project with known location. Set source location",
"# so that it can declare targets. This is intended so that you can put",
"# a .jam file in your sources and use it via 'using'. Standard modules",
"# (in 'tools' subdir) may not assume source dir is set.",
"source_location",
"=",
"standalone_path",
"if",
"not",
"source_location",
":",
"source_location",
"=",
"self",
".",
"loaded_tool_module_path_",
".",
"get",
"(",
"module_name",
")",
"if",
"not",
"source_location",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"'Standalone module path not found for \"{}\"'",
".",
"format",
"(",
"module_name",
")",
")",
"attributes",
".",
"set",
"(",
"\"source-location\"",
",",
"[",
"source_location",
"]",
",",
"exact",
"=",
"1",
")",
"python_standalone",
"=",
"True",
"attributes",
".",
"set",
"(",
"\"requirements\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"usage-requirements\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"default-build\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"projects-to-build\"",
",",
"[",
"]",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"None",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"build-dir\"",
",",
"None",
",",
"exact",
"=",
"True",
")",
"self",
".",
"project_rules_",
".",
"init_project",
"(",
"module_name",
",",
"python_standalone",
")",
"if",
"parent_module",
":",
"self",
".",
"inherit_attributes",
"(",
"module_name",
",",
"parent_module",
")",
"attributes",
".",
"set",
"(",
"\"parent-module\"",
",",
"parent_module",
",",
"exact",
"=",
"1",
")",
"if",
"jamroot",
":",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"location",
",",
"exact",
"=",
"1",
")",
"parent",
"=",
"None",
"if",
"parent_module",
":",
"parent",
"=",
"self",
".",
"target",
"(",
"parent_module",
")",
"if",
"module_name",
"not",
"in",
"self",
".",
"module2target",
":",
"target",
"=",
"b2",
".",
"build",
".",
"targets",
".",
"ProjectTarget",
"(",
"self",
".",
"manager",
",",
"module_name",
",",
"module_name",
",",
"parent",
",",
"self",
".",
"attribute",
"(",
"module_name",
",",
"\"requirements\"",
")",
",",
"# FIXME: why we need to pass this? It's not",
"# passed in jam code.",
"self",
".",
"attribute",
"(",
"module_name",
",",
"\"default-build\"",
")",
")",
"self",
".",
"module2target",
"[",
"module_name",
"]",
"=",
"target",
"self",
".",
"current_project",
"=",
"self",
".",
"target",
"(",
"module_name",
")"
] | Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side. | [
"Initialize",
"the",
"module",
"for",
"a",
"project",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L412-L509 |
28,885 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.inherit_attributes | def inherit_attributes(self, project_module, parent_module):
"""Make 'project-module' inherit attributes of project
root and parent module."""
assert isinstance(project_module, basestring)
assert isinstance(parent_module, basestring)
attributes = self.module2attributes[project_module]
pattributes = self.module2attributes[parent_module]
# Parent module might be locationless user-config.
# FIXME:
#if [ modules.binding $(parent-module) ]
#{
# $(attributes).set parent : [ path.parent
# [ path.make [ modules.binding $(parent-module) ] ] ] ;
# }
attributes.set("project-root", pattributes.get("project-root"), exact=True)
attributes.set("default-build", pattributes.get("default-build"), exact=True)
attributes.set("requirements", pattributes.get("requirements"), exact=True)
attributes.set("usage-requirements",
pattributes.get("usage-requirements"), exact=1)
parent_build_dir = pattributes.get("build-dir")
if parent_build_dir:
# Have to compute relative path from parent dir to our dir
# Convert both paths to absolute, since we cannot
# find relative path from ".." to "."
location = attributes.get("location")
parent_location = pattributes.get("location")
our_dir = os.path.join(os.getcwd(), location)
parent_dir = os.path.join(os.getcwd(), parent_location)
build_dir = os.path.join(parent_build_dir,
os.path.relpath(our_dir, parent_dir))
attributes.set("build-dir", build_dir, exact=True) | python | def inherit_attributes(self, project_module, parent_module):
"""Make 'project-module' inherit attributes of project
root and parent module."""
assert isinstance(project_module, basestring)
assert isinstance(parent_module, basestring)
attributes = self.module2attributes[project_module]
pattributes = self.module2attributes[parent_module]
# Parent module might be locationless user-config.
# FIXME:
#if [ modules.binding $(parent-module) ]
#{
# $(attributes).set parent : [ path.parent
# [ path.make [ modules.binding $(parent-module) ] ] ] ;
# }
attributes.set("project-root", pattributes.get("project-root"), exact=True)
attributes.set("default-build", pattributes.get("default-build"), exact=True)
attributes.set("requirements", pattributes.get("requirements"), exact=True)
attributes.set("usage-requirements",
pattributes.get("usage-requirements"), exact=1)
parent_build_dir = pattributes.get("build-dir")
if parent_build_dir:
# Have to compute relative path from parent dir to our dir
# Convert both paths to absolute, since we cannot
# find relative path from ".." to "."
location = attributes.get("location")
parent_location = pattributes.get("location")
our_dir = os.path.join(os.getcwd(), location)
parent_dir = os.path.join(os.getcwd(), parent_location)
build_dir = os.path.join(parent_build_dir,
os.path.relpath(our_dir, parent_dir))
attributes.set("build-dir", build_dir, exact=True) | [
"def",
"inherit_attributes",
"(",
"self",
",",
"project_module",
",",
"parent_module",
")",
":",
"assert",
"isinstance",
"(",
"project_module",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"parent_module",
",",
"basestring",
")",
"attributes",
"=",
"self",
".",
"module2attributes",
"[",
"project_module",
"]",
"pattributes",
"=",
"self",
".",
"module2attributes",
"[",
"parent_module",
"]",
"# Parent module might be locationless user-config.",
"# FIXME:",
"#if [ modules.binding $(parent-module) ]",
"#{",
"# $(attributes).set parent : [ path.parent",
"# [ path.make [ modules.binding $(parent-module) ] ] ] ;",
"# }",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"pattributes",
".",
"get",
"(",
"\"project-root\"",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"default-build\"",
",",
"pattributes",
".",
"get",
"(",
"\"default-build\"",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"requirements\"",
",",
"pattributes",
".",
"get",
"(",
"\"requirements\"",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"usage-requirements\"",
",",
"pattributes",
".",
"get",
"(",
"\"usage-requirements\"",
")",
",",
"exact",
"=",
"1",
")",
"parent_build_dir",
"=",
"pattributes",
".",
"get",
"(",
"\"build-dir\"",
")",
"if",
"parent_build_dir",
":",
"# Have to compute relative path from parent dir to our dir",
"# Convert both paths to absolute, since we cannot",
"# find relative path from \"..\" to \".\"",
"location",
"=",
"attributes",
".",
"get",
"(",
"\"location\"",
")",
"parent_location",
"=",
"pattributes",
".",
"get",
"(",
"\"location\"",
")",
"our_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"location",
")",
"parent_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"parent_location",
")",
"build_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"parent_build_dir",
",",
"os",
".",
"path",
".",
"relpath",
"(",
"our_dir",
",",
"parent_dir",
")",
")",
"attributes",
".",
"set",
"(",
"\"build-dir\"",
",",
"build_dir",
",",
"exact",
"=",
"True",
")"
] | Make 'project-module' inherit attributes of project
root and parent module. | [
"Make",
"project",
"-",
"module",
"inherit",
"attributes",
"of",
"project",
"root",
"and",
"parent",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L511-L549 |
28,886 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.register_id | def register_id(self, id, module):
"""Associate the given id with the given project module."""
assert isinstance(id, basestring)
assert isinstance(module, basestring)
self.id2module[id] = module | python | def register_id(self, id, module):
"""Associate the given id with the given project module."""
assert isinstance(id, basestring)
assert isinstance(module, basestring)
self.id2module[id] = module | [
"def",
"register_id",
"(",
"self",
",",
"id",
",",
"module",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"module",
",",
"basestring",
")",
"self",
".",
"id2module",
"[",
"id",
"]",
"=",
"module"
] | Associate the given id with the given project module. | [
"Associate",
"the",
"given",
"id",
"with",
"the",
"given",
"project",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L551-L555 |
28,887 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.push_current | def push_current(self, project):
"""Temporary changes the current project to 'project'. Should
be followed by 'pop-current'."""
if __debug__:
from .targets import ProjectTarget
assert isinstance(project, ProjectTarget)
self.saved_current_project.append(self.current_project)
self.current_project = project | python | def push_current(self, project):
"""Temporary changes the current project to 'project'. Should
be followed by 'pop-current'."""
if __debug__:
from .targets import ProjectTarget
assert isinstance(project, ProjectTarget)
self.saved_current_project.append(self.current_project)
self.current_project = project | [
"def",
"push_current",
"(",
"self",
",",
"project",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"targets",
"import",
"ProjectTarget",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"self",
".",
"saved_current_project",
".",
"append",
"(",
"self",
".",
"current_project",
")",
"self",
".",
"current_project",
"=",
"project"
] | Temporary changes the current project to 'project'. Should
be followed by 'pop-current'. | [
"Temporary",
"changes",
"the",
"current",
"project",
"to",
"project",
".",
"Should",
"be",
"followed",
"by",
"pop",
"-",
"current",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L572-L579 |
28,888 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.target | def target(self, project_module):
"""Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring)
if project_module not in self.module2target:
self.module2target[project_module] = \
b2.build.targets.ProjectTarget(project_module, project_module,
self.attribute(project_module, "requirements"))
return self.module2target[project_module] | python | def target(self, project_module):
"""Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring)
if project_module not in self.module2target:
self.module2target[project_module] = \
b2.build.targets.ProjectTarget(project_module, project_module,
self.attribute(project_module, "requirements"))
return self.module2target[project_module] | [
"def",
"target",
"(",
"self",
",",
"project_module",
")",
":",
"assert",
"isinstance",
"(",
"project_module",
",",
"basestring",
")",
"if",
"project_module",
"not",
"in",
"self",
".",
"module2target",
":",
"self",
".",
"module2target",
"[",
"project_module",
"]",
"=",
"b2",
".",
"build",
".",
"targets",
".",
"ProjectTarget",
"(",
"project_module",
",",
"project_module",
",",
"self",
".",
"attribute",
"(",
"project_module",
",",
"\"requirements\"",
")",
")",
"return",
"self",
".",
"module2target",
"[",
"project_module",
"]"
] | Returns the project target corresponding to the 'project-module'. | [
"Returns",
"the",
"project",
"target",
"corresponding",
"to",
"the",
"project",
"-",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L611-L619 |
28,889 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.add_rule | def add_rule(self, name, callable_):
"""Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'."""
assert isinstance(name, basestring)
assert callable(callable_)
self.project_rules_.add_rule(name, callable_) | python | def add_rule(self, name, callable_):
"""Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'."""
assert isinstance(name, basestring)
assert callable(callable_)
self.project_rules_.add_rule(name, callable_) | [
"def",
"add_rule",
"(",
"self",
",",
"name",
",",
"callable_",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"callable",
"(",
"callable_",
")",
"self",
".",
"project_rules_",
".",
"add_rule",
"(",
"name",
",",
"callable_",
")"
] | Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'. | [
"Makes",
"rule",
"name",
"available",
"to",
"all",
"subsequently",
"loaded",
"Jamfiles",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L639-L645 |
28,890 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load_module | def load_module(self, name, extra_path=None):
"""Load a Python module that should be useable from Jamfiles.
There are generally two types of modules Jamfiles might want to
use:
- Core Boost.Build. Those are imported using plain names, e.g.
'toolset', so this function checks if we have module named
b2.package.module already.
- Python modules in the same directory as Jamfile. We don't
want to even temporary add Jamfile's directory to sys.path,
since then we might get naming conflicts between standard
Python modules and those.
"""
assert isinstance(name, basestring)
assert is_iterable_typed(extra_path, basestring) or extra_path is None
# See if we loaded module of this name already
existing = self.loaded_tool_modules_.get(name)
if existing:
return existing
# check the extra path as well as any paths outside
# of the b2 package and import the module if it exists
b2_path = os.path.normpath(b2.__path__[0])
# normalize the pathing in the BOOST_BUILD_PATH.
# this allows for using startswith() to determine
# if a path is a subdirectory of the b2 root_path
paths = [os.path.normpath(p) for p in self.manager.boost_build_path()]
# remove all paths that start with b2's root_path
paths = [p for p in paths if not p.startswith(b2_path)]
# add any extra paths
paths.extend(extra_path)
try:
# find_module is used so that the pyc's can be used.
# an ImportError is raised if not found
f, location, description = imp.find_module(name, paths)
except ImportError:
# if the module is not found in the b2 package,
# this error will be handled later
pass
else:
# we've found the module, now let's try loading it.
# it's possible that the module itself contains an ImportError
# which is why we're loading it in this else clause so that the
# proper error message is shown to the end user.
# TODO: does this module name really need to be mangled like this?
mname = name + "__for_jamfile"
self.loaded_tool_module_path_[mname] = location
module = imp.load_module(mname, f, location, description)
self.loaded_tool_modules_[name] = module
return module
# the cache is created here due to possibly importing packages
# that end up calling get_manager() which might fail
if not self.__python_module_cache:
self.__build_python_module_cache()
underscore_name = name.replace('-', '_')
# check to see if the module is within the b2 package
# and already loaded
mname = self.__python_module_cache.get(underscore_name)
if mname in sys.modules:
return sys.modules[mname]
# otherwise, if the module name is within the cache,
# the module exists within the BOOST_BUILD_PATH,
# load it.
elif mname:
# in some cases, self.loaded_tool_module_path_ needs to
# have the path to the file during the import
# (project.initialize() for example),
# so the path needs to be set *before* importing the module.
path = os.path.join(b2.__path__[0], *mname.split('.')[1:])
self.loaded_tool_module_path_[mname] = path
# mname is guaranteed to be importable since it was
# found within the cache
__import__(mname)
module = sys.modules[mname]
self.loaded_tool_modules_[name] = module
return module
self.manager.errors()("Cannot find module '%s'" % name) | python | def load_module(self, name, extra_path=None):
"""Load a Python module that should be useable from Jamfiles.
There are generally two types of modules Jamfiles might want to
use:
- Core Boost.Build. Those are imported using plain names, e.g.
'toolset', so this function checks if we have module named
b2.package.module already.
- Python modules in the same directory as Jamfile. We don't
want to even temporary add Jamfile's directory to sys.path,
since then we might get naming conflicts between standard
Python modules and those.
"""
assert isinstance(name, basestring)
assert is_iterable_typed(extra_path, basestring) or extra_path is None
# See if we loaded module of this name already
existing = self.loaded_tool_modules_.get(name)
if existing:
return existing
# check the extra path as well as any paths outside
# of the b2 package and import the module if it exists
b2_path = os.path.normpath(b2.__path__[0])
# normalize the pathing in the BOOST_BUILD_PATH.
# this allows for using startswith() to determine
# if a path is a subdirectory of the b2 root_path
paths = [os.path.normpath(p) for p in self.manager.boost_build_path()]
# remove all paths that start with b2's root_path
paths = [p for p in paths if not p.startswith(b2_path)]
# add any extra paths
paths.extend(extra_path)
try:
# find_module is used so that the pyc's can be used.
# an ImportError is raised if not found
f, location, description = imp.find_module(name, paths)
except ImportError:
# if the module is not found in the b2 package,
# this error will be handled later
pass
else:
# we've found the module, now let's try loading it.
# it's possible that the module itself contains an ImportError
# which is why we're loading it in this else clause so that the
# proper error message is shown to the end user.
# TODO: does this module name really need to be mangled like this?
mname = name + "__for_jamfile"
self.loaded_tool_module_path_[mname] = location
module = imp.load_module(mname, f, location, description)
self.loaded_tool_modules_[name] = module
return module
# the cache is created here due to possibly importing packages
# that end up calling get_manager() which might fail
if not self.__python_module_cache:
self.__build_python_module_cache()
underscore_name = name.replace('-', '_')
# check to see if the module is within the b2 package
# and already loaded
mname = self.__python_module_cache.get(underscore_name)
if mname in sys.modules:
return sys.modules[mname]
# otherwise, if the module name is within the cache,
# the module exists within the BOOST_BUILD_PATH,
# load it.
elif mname:
# in some cases, self.loaded_tool_module_path_ needs to
# have the path to the file during the import
# (project.initialize() for example),
# so the path needs to be set *before* importing the module.
path = os.path.join(b2.__path__[0], *mname.split('.')[1:])
self.loaded_tool_module_path_[mname] = path
# mname is guaranteed to be importable since it was
# found within the cache
__import__(mname)
module = sys.modules[mname]
self.loaded_tool_modules_[name] = module
return module
self.manager.errors()("Cannot find module '%s'" % name) | [
"def",
"load_module",
"(",
"self",
",",
"name",
",",
"extra_path",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"extra_path",
",",
"basestring",
")",
"or",
"extra_path",
"is",
"None",
"# See if we loaded module of this name already",
"existing",
"=",
"self",
".",
"loaded_tool_modules_",
".",
"get",
"(",
"name",
")",
"if",
"existing",
":",
"return",
"existing",
"# check the extra path as well as any paths outside",
"# of the b2 package and import the module if it exists",
"b2_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"b2",
".",
"__path__",
"[",
"0",
"]",
")",
"# normalize the pathing in the BOOST_BUILD_PATH.",
"# this allows for using startswith() to determine",
"# if a path is a subdirectory of the b2 root_path",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"p",
")",
"for",
"p",
"in",
"self",
".",
"manager",
".",
"boost_build_path",
"(",
")",
"]",
"# remove all paths that start with b2's root_path",
"paths",
"=",
"[",
"p",
"for",
"p",
"in",
"paths",
"if",
"not",
"p",
".",
"startswith",
"(",
"b2_path",
")",
"]",
"# add any extra paths",
"paths",
".",
"extend",
"(",
"extra_path",
")",
"try",
":",
"# find_module is used so that the pyc's can be used.",
"# an ImportError is raised if not found",
"f",
",",
"location",
",",
"description",
"=",
"imp",
".",
"find_module",
"(",
"name",
",",
"paths",
")",
"except",
"ImportError",
":",
"# if the module is not found in the b2 package,",
"# this error will be handled later",
"pass",
"else",
":",
"# we've found the module, now let's try loading it.",
"# it's possible that the module itself contains an ImportError",
"# which is why we're loading it in this else clause so that the",
"# proper error message is shown to the end user.",
"# TODO: does this module name really need to be mangled like this?",
"mname",
"=",
"name",
"+",
"\"__for_jamfile\"",
"self",
".",
"loaded_tool_module_path_",
"[",
"mname",
"]",
"=",
"location",
"module",
"=",
"imp",
".",
"load_module",
"(",
"mname",
",",
"f",
",",
"location",
",",
"description",
")",
"self",
".",
"loaded_tool_modules_",
"[",
"name",
"]",
"=",
"module",
"return",
"module",
"# the cache is created here due to possibly importing packages",
"# that end up calling get_manager() which might fail",
"if",
"not",
"self",
".",
"__python_module_cache",
":",
"self",
".",
"__build_python_module_cache",
"(",
")",
"underscore_name",
"=",
"name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"# check to see if the module is within the b2 package",
"# and already loaded",
"mname",
"=",
"self",
".",
"__python_module_cache",
".",
"get",
"(",
"underscore_name",
")",
"if",
"mname",
"in",
"sys",
".",
"modules",
":",
"return",
"sys",
".",
"modules",
"[",
"mname",
"]",
"# otherwise, if the module name is within the cache,",
"# the module exists within the BOOST_BUILD_PATH,",
"# load it.",
"elif",
"mname",
":",
"# in some cases, self.loaded_tool_module_path_ needs to",
"# have the path to the file during the import",
"# (project.initialize() for example),",
"# so the path needs to be set *before* importing the module.",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"b2",
".",
"__path__",
"[",
"0",
"]",
",",
"*",
"mname",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
")",
"self",
".",
"loaded_tool_module_path_",
"[",
"mname",
"]",
"=",
"path",
"# mname is guaranteed to be importable since it was",
"# found within the cache",
"__import__",
"(",
"mname",
")",
"module",
"=",
"sys",
".",
"modules",
"[",
"mname",
"]",
"self",
".",
"loaded_tool_modules_",
"[",
"name",
"]",
"=",
"module",
"return",
"module",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"\"Cannot find module '%s'\"",
"%",
"name",
")"
] | Load a Python module that should be useable from Jamfiles.
There are generally two types of modules Jamfiles might want to
use:
- Core Boost.Build. Those are imported using plain names, e.g.
'toolset', so this function checks if we have module named
b2.package.module already.
- Python modules in the same directory as Jamfile. We don't
want to even temporary add Jamfile's directory to sys.path,
since then we might get naming conflicts between standard
Python modules and those. | [
"Load",
"a",
"Python",
"module",
"that",
"should",
"be",
"useable",
"from",
"Jamfiles",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L726-L806 |
28,891 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectAttributes.dump | def dump(self):
"""Prints the project attributes."""
id = self.get("id")
if not id:
id = "(none)"
else:
id = id[0]
parent = self.get("parent")
if not parent:
parent = "(none)"
else:
parent = parent[0]
print "'%s'" % id
print "Parent project:%s", parent
print "Requirements:%s", self.get("requirements")
print "Default build:%s", string.join(self.get("debuild-build"))
print "Source location:%s", string.join(self.get("source-location"))
print "Projects to build:%s", string.join(self.get("projects-to-build").sort()); | python | def dump(self):
"""Prints the project attributes."""
id = self.get("id")
if not id:
id = "(none)"
else:
id = id[0]
parent = self.get("parent")
if not parent:
parent = "(none)"
else:
parent = parent[0]
print "'%s'" % id
print "Parent project:%s", parent
print "Requirements:%s", self.get("requirements")
print "Default build:%s", string.join(self.get("debuild-build"))
print "Source location:%s", string.join(self.get("source-location"))
print "Projects to build:%s", string.join(self.get("projects-to-build").sort()); | [
"def",
"dump",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"get",
"(",
"\"id\"",
")",
"if",
"not",
"id",
":",
"id",
"=",
"\"(none)\"",
"else",
":",
"id",
"=",
"id",
"[",
"0",
"]",
"parent",
"=",
"self",
".",
"get",
"(",
"\"parent\"",
")",
"if",
"not",
"parent",
":",
"parent",
"=",
"\"(none)\"",
"else",
":",
"parent",
"=",
"parent",
"[",
"0",
"]",
"print",
"\"'%s'\"",
"%",
"id",
"print",
"\"Parent project:%s\"",
",",
"parent",
"print",
"\"Requirements:%s\"",
",",
"self",
".",
"get",
"(",
"\"requirements\"",
")",
"print",
"\"Default build:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"debuild-build\"",
")",
")",
"print",
"\"Source location:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"source-location\"",
")",
")",
"print",
"\"Projects to build:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"projects-to-build\"",
")",
".",
"sort",
"(",
")",
")"
] | Prints the project attributes. | [
"Prints",
"the",
"project",
"attributes",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L954-L973 |
28,892 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRules.make_wrapper | def make_wrapper(self, callable_):
"""Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'."""
assert callable(callable_)
def wrapper(*args, **kw):
return self.call_and_report_errors(callable_, *args, **kw)
return wrapper | python | def make_wrapper(self, callable_):
"""Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'."""
assert callable(callable_)
def wrapper(*args, **kw):
return self.call_and_report_errors(callable_, *args, **kw)
return wrapper | [
"def",
"make_wrapper",
"(",
"self",
",",
"callable_",
")",
":",
"assert",
"callable",
"(",
"callable_",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"call_and_report_errors",
"(",
"callable_",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"wrapper"
] | Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'. | [
"Given",
"a",
"free",
"-",
"standing",
"function",
"callable",
"return",
"a",
"new",
"callable",
"that",
"will",
"call",
"callable",
"and",
"report",
"all",
"exceptins",
"using",
"call_and_report_errors",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1044-L1051 |
28,893 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRules.constant | def constant(self, name, value):
"""Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
self.registry.current().add_constant(name[0], value) | python | def constant(self, name, value):
"""Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
self.registry.current().add_constant(name[0], value) | [
"def",
"constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"self",
".",
"registry",
".",
"current",
"(",
")",
".",
"add_constant",
"(",
"name",
"[",
"0",
"]",
",",
"value",
")"
] | Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile. | [
"Declare",
"and",
"set",
"a",
"project",
"global",
"constant",
".",
"Project",
"global",
"constants",
"are",
"normal",
"variables",
"but",
"should",
"not",
"be",
"changed",
".",
"They",
"are",
"applied",
"to",
"every",
"child",
"Jamfile",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1136-L1142 |
28,894 | apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRules.path_constant | def path_constant(self, name, value):
"""Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
if len(value) > 1:
self.registry.manager.errors()("path constant should have one element")
self.registry.current().add_constant(name[0], value, path=1) | python | def path_constant(self, name, value):
"""Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
if len(value) > 1:
self.registry.manager.errors()("path constant should have one element")
self.registry.current().add_constant(name[0], value, path=1) | [
"def",
"path_constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"if",
"len",
"(",
"value",
")",
">",
"1",
":",
"self",
".",
"registry",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"\"path constant should have one element\"",
")",
"self",
".",
"registry",
".",
"current",
"(",
")",
".",
"add_constant",
"(",
"name",
"[",
"0",
"]",
",",
"value",
",",
"path",
"=",
"1",
")"
] | Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root. | [
"Declare",
"and",
"set",
"a",
"project",
"global",
"constant",
"whose",
"value",
"is",
"a",
"path",
".",
"The",
"path",
"is",
"adjusted",
"to",
"be",
"relative",
"to",
"the",
"invocation",
"directory",
".",
"The",
"given",
"value",
"path",
"is",
"taken",
"to",
"be",
"either",
"absolute",
"or",
"relative",
"to",
"this",
"project",
"root",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1144-L1153 |
28,895 | apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/array_feature_extractor.py | create_array_feature_extractor | def create_array_feature_extractor(input_features, output_name, extract_indices,
output_type = None):
"""
Creates a feature extractor from an input array feature, return
input_features is a list of one (name, array) tuple.
extract_indices is either an integer or a list. If it's an integer,
the output type is by default a double (but may also be an integer).
If a list, the output type is an array.
"""
# Make sure that our starting stuff is in the proper form.
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# Create the model.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
if isinstance(extract_indices, _integer_types):
extract_indices = [extract_indices]
if output_type is None:
output_type = datatypes.Double()
elif isinstance(extract_indices, (list, tuple)):
if not all(isinstance(x, _integer_types) for x in extract_indices):
raise TypeError("extract_indices must be an integer or a list of integers.")
if output_type is None:
output_type = datatypes.Array(len(extract_indices))
else:
raise TypeError("extract_indices must be an integer or a list of integers.")
output_features = [(output_name, output_type)]
for idx in extract_indices:
assert idx < input_features[0][1].num_elements
spec.arrayFeatureExtractor.extractIndex.append(idx)
set_transform_interface_params(spec, input_features, output_features)
return spec | python | def create_array_feature_extractor(input_features, output_name, extract_indices,
output_type = None):
"""
Creates a feature extractor from an input array feature, return
input_features is a list of one (name, array) tuple.
extract_indices is either an integer or a list. If it's an integer,
the output type is by default a double (but may also be an integer).
If a list, the output type is an array.
"""
# Make sure that our starting stuff is in the proper form.
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# Create the model.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
if isinstance(extract_indices, _integer_types):
extract_indices = [extract_indices]
if output_type is None:
output_type = datatypes.Double()
elif isinstance(extract_indices, (list, tuple)):
if not all(isinstance(x, _integer_types) for x in extract_indices):
raise TypeError("extract_indices must be an integer or a list of integers.")
if output_type is None:
output_type = datatypes.Array(len(extract_indices))
else:
raise TypeError("extract_indices must be an integer or a list of integers.")
output_features = [(output_name, output_type)]
for idx in extract_indices:
assert idx < input_features[0][1].num_elements
spec.arrayFeatureExtractor.extractIndex.append(idx)
set_transform_interface_params(spec, input_features, output_features)
return spec | [
"def",
"create_array_feature_extractor",
"(",
"input_features",
",",
"output_name",
",",
"extract_indices",
",",
"output_type",
"=",
"None",
")",
":",
"# Make sure that our starting stuff is in the proper form.",
"assert",
"len",
"(",
"input_features",
")",
"==",
"1",
"assert",
"isinstance",
"(",
"input_features",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"datatypes",
".",
"Array",
")",
"# Create the model.",
"spec",
"=",
"_Model_pb2",
".",
"Model",
"(",
")",
"spec",
".",
"specificationVersion",
"=",
"SPECIFICATION_VERSION",
"if",
"isinstance",
"(",
"extract_indices",
",",
"_integer_types",
")",
":",
"extract_indices",
"=",
"[",
"extract_indices",
"]",
"if",
"output_type",
"is",
"None",
":",
"output_type",
"=",
"datatypes",
".",
"Double",
"(",
")",
"elif",
"isinstance",
"(",
"extract_indices",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"_integer_types",
")",
"for",
"x",
"in",
"extract_indices",
")",
":",
"raise",
"TypeError",
"(",
"\"extract_indices must be an integer or a list of integers.\"",
")",
"if",
"output_type",
"is",
"None",
":",
"output_type",
"=",
"datatypes",
".",
"Array",
"(",
"len",
"(",
"extract_indices",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"extract_indices must be an integer or a list of integers.\"",
")",
"output_features",
"=",
"[",
"(",
"output_name",
",",
"output_type",
")",
"]",
"for",
"idx",
"in",
"extract_indices",
":",
"assert",
"idx",
"<",
"input_features",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"num_elements",
"spec",
".",
"arrayFeatureExtractor",
".",
"extractIndex",
".",
"append",
"(",
"idx",
")",
"set_transform_interface_params",
"(",
"spec",
",",
"input_features",
",",
"output_features",
")",
"return",
"spec"
] | Creates a feature extractor from an input array feature, return
input_features is a list of one (name, array) tuple.
extract_indices is either an integer or a list. If it's an integer,
the output type is by default a double (but may also be an integer).
If a list, the output type is an array. | [
"Creates",
"a",
"feature",
"extractor",
"from",
"an",
"input",
"array",
"feature",
"return"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/array_feature_extractor.py#L16-L59 |
28,896 | apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.add_input | def add_input(self, input):
'''
Add a single build XML output file to our data.
'''
events = xml.dom.pulldom.parse(input)
context = []
for (event,node) in events:
if event == xml.dom.pulldom.START_ELEMENT:
context.append(node)
if node.nodeType == xml.dom.Node.ELEMENT_NODE:
x_f = self.x_name_(*context)
if x_f:
events.expandNode(node)
# expanding eats the end element, hence walking us out one level
context.pop()
# call handler
(x_f[1])(node)
elif event == xml.dom.pulldom.END_ELEMENT:
context.pop() | python | def add_input(self, input):
'''
Add a single build XML output file to our data.
'''
events = xml.dom.pulldom.parse(input)
context = []
for (event,node) in events:
if event == xml.dom.pulldom.START_ELEMENT:
context.append(node)
if node.nodeType == xml.dom.Node.ELEMENT_NODE:
x_f = self.x_name_(*context)
if x_f:
events.expandNode(node)
# expanding eats the end element, hence walking us out one level
context.pop()
# call handler
(x_f[1])(node)
elif event == xml.dom.pulldom.END_ELEMENT:
context.pop() | [
"def",
"add_input",
"(",
"self",
",",
"input",
")",
":",
"events",
"=",
"xml",
".",
"dom",
".",
"pulldom",
".",
"parse",
"(",
"input",
")",
"context",
"=",
"[",
"]",
"for",
"(",
"event",
",",
"node",
")",
"in",
"events",
":",
"if",
"event",
"==",
"xml",
".",
"dom",
".",
"pulldom",
".",
"START_ELEMENT",
":",
"context",
".",
"append",
"(",
"node",
")",
"if",
"node",
".",
"nodeType",
"==",
"xml",
".",
"dom",
".",
"Node",
".",
"ELEMENT_NODE",
":",
"x_f",
"=",
"self",
".",
"x_name_",
"(",
"*",
"context",
")",
"if",
"x_f",
":",
"events",
".",
"expandNode",
"(",
"node",
")",
"# expanding eats the end element, hence walking us out one level",
"context",
".",
"pop",
"(",
")",
"# call handler",
"(",
"x_f",
"[",
"1",
"]",
")",
"(",
"node",
")",
"elif",
"event",
"==",
"xml",
".",
"dom",
".",
"pulldom",
".",
"END_ELEMENT",
":",
"context",
".",
"pop",
"(",
")"
] | Add a single build XML output file to our data. | [
"Add",
"a",
"single",
"build",
"XML",
"output",
"file",
"to",
"our",
"data",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L85-L103 |
28,897 | apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.x_build_targets_target | def x_build_targets_target( self, node ):
'''
Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to.
'''
target_node = node
name = self.get_child_data(target_node,tag='name',strip=True)
path = self.get_child_data(target_node,tag='path',strip=True)
jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
#~ Map for jam targets to virtual targets.
self.target[jam_target] = {
'name' : name,
'path' : path
}
#~ Create the ancestry.
dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
while dep_node:
child = self.get_data(dep_node,strip=True)
child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
self.parent[child_jam_target] = jam_target
dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
return None | python | def x_build_targets_target( self, node ):
'''
Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to.
'''
target_node = node
name = self.get_child_data(target_node,tag='name',strip=True)
path = self.get_child_data(target_node,tag='path',strip=True)
jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
#~ Map for jam targets to virtual targets.
self.target[jam_target] = {
'name' : name,
'path' : path
}
#~ Create the ancestry.
dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
while dep_node:
child = self.get_data(dep_node,strip=True)
child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
self.parent[child_jam_target] = jam_target
dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
return None | [
"def",
"x_build_targets_target",
"(",
"self",
",",
"node",
")",
":",
"target_node",
"=",
"node",
"name",
"=",
"self",
".",
"get_child_data",
"(",
"target_node",
",",
"tag",
"=",
"'name'",
",",
"strip",
"=",
"True",
")",
"path",
"=",
"self",
".",
"get_child_data",
"(",
"target_node",
",",
"tag",
"=",
"'path'",
",",
"strip",
"=",
"True",
")",
"jam_target",
"=",
"self",
".",
"get_child_data",
"(",
"target_node",
",",
"tag",
"=",
"'jam-target'",
",",
"strip",
"=",
"True",
")",
"#~ Map for jam targets to virtual targets.",
"self",
".",
"target",
"[",
"jam_target",
"]",
"=",
"{",
"'name'",
":",
"name",
",",
"'path'",
":",
"path",
"}",
"#~ Create the ancestry.",
"dep_node",
"=",
"self",
".",
"get_child",
"(",
"self",
".",
"get_child",
"(",
"target_node",
",",
"tag",
"=",
"'dependencies'",
")",
",",
"tag",
"=",
"'dependency'",
")",
"while",
"dep_node",
":",
"child",
"=",
"self",
".",
"get_data",
"(",
"dep_node",
",",
"strip",
"=",
"True",
")",
"child_jam_target",
"=",
"'<p%s>%s'",
"%",
"(",
"path",
",",
"child",
".",
"split",
"(",
"'//'",
",",
"1",
")",
"[",
"1",
"]",
")",
"self",
".",
"parent",
"[",
"child_jam_target",
"]",
"=",
"jam_target",
"dep_node",
"=",
"self",
".",
"get_sibling",
"(",
"dep_node",
".",
"nextSibling",
",",
"tag",
"=",
"'dependency'",
")",
"return",
"None"
] | Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to. | [
"Process",
"the",
"target",
"dependency",
"DAG",
"into",
"an",
"ancestry",
"tree",
"so",
"we",
"can",
"look",
"up",
"which",
"top",
"-",
"level",
"library",
"and",
"test",
"targets",
"specific",
"build",
"actions",
"correspond",
"to",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L146-L167 |
28,898 | apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.x_build_action | def x_build_action( self, node ):
'''
Given a build action log, process into the corresponding test log and
specific test log sub-part.
'''
action_node = node
name = self.get_child(action_node,tag='name')
if name:
name = self.get_data(name)
#~ Based on the action, we decide what sub-section the log
#~ should go into.
action_type = None
if re.match('[^%]+%[^.]+[.](compile)',name):
action_type = 'compile'
elif re.match('[^%]+%[^.]+[.](link|archive)',name):
action_type = 'link'
elif re.match('[^%]+%testing[.](capture-output)',name):
action_type = 'run'
elif re.match('[^%]+%testing[.](expect-failure|expect-success)',name):
action_type = 'result'
else:
# TODO: Enable to see what other actions can be included in the test results.
# action_type = None
action_type = 'other'
#~ print "+ [%s] %s %s :: %s" %(action_type,name,'','')
if action_type:
#~ Get the corresponding test.
(target,test) = self.get_test(action_node,type=action_type)
#~ Skip action that have no corresponding test as they are
#~ regular build actions and don't need to show up in the
#~ regression results.
if not test:
##print "??? [%s] %s %s :: %s" %(action_type,name,target,test)
return None
##print "+++ [%s] %s %s :: %s" %(action_type,name,target,test)
#~ Collect some basic info about the action.
action = {
'command' : self.get_action_command(action_node,action_type),
'output' : self.get_action_output(action_node,action_type),
'info' : self.get_action_info(action_node,action_type)
}
#~ For the test result status we find the appropriate node
#~ based on the type of test. Then adjust the result status
#~ accordingly. This makes the result status reflect the
#~ expectation as the result pages post processing does not
#~ account for this inversion.
action['type'] = action_type
if action_type == 'result':
if re.match(r'^compile',test['test-type']):
action['type'] = 'compile'
elif re.match(r'^link',test['test-type']):
action['type'] = 'link'
elif re.match(r'^run',test['test-type']):
action['type'] = 'run'
#~ The result sub-part we will add this result to.
if action_node.getAttribute('status') == '0':
action['result'] = 'succeed'
else:
action['result'] = 'fail'
# Add the action to the test.
test['actions'].append(action)
# Set the test result if this is the result action for the test.
if action_type == 'result':
test['result'] = action['result']
return None | python | def x_build_action( self, node ):
'''
Given a build action log, process into the corresponding test log and
specific test log sub-part.
'''
action_node = node
name = self.get_child(action_node,tag='name')
if name:
name = self.get_data(name)
#~ Based on the action, we decide what sub-section the log
#~ should go into.
action_type = None
if re.match('[^%]+%[^.]+[.](compile)',name):
action_type = 'compile'
elif re.match('[^%]+%[^.]+[.](link|archive)',name):
action_type = 'link'
elif re.match('[^%]+%testing[.](capture-output)',name):
action_type = 'run'
elif re.match('[^%]+%testing[.](expect-failure|expect-success)',name):
action_type = 'result'
else:
# TODO: Enable to see what other actions can be included in the test results.
# action_type = None
action_type = 'other'
#~ print "+ [%s] %s %s :: %s" %(action_type,name,'','')
if action_type:
#~ Get the corresponding test.
(target,test) = self.get_test(action_node,type=action_type)
#~ Skip action that have no corresponding test as they are
#~ regular build actions and don't need to show up in the
#~ regression results.
if not test:
##print "??? [%s] %s %s :: %s" %(action_type,name,target,test)
return None
##print "+++ [%s] %s %s :: %s" %(action_type,name,target,test)
#~ Collect some basic info about the action.
action = {
'command' : self.get_action_command(action_node,action_type),
'output' : self.get_action_output(action_node,action_type),
'info' : self.get_action_info(action_node,action_type)
}
#~ For the test result status we find the appropriate node
#~ based on the type of test. Then adjust the result status
#~ accordingly. This makes the result status reflect the
#~ expectation as the result pages post processing does not
#~ account for this inversion.
action['type'] = action_type
if action_type == 'result':
if re.match(r'^compile',test['test-type']):
action['type'] = 'compile'
elif re.match(r'^link',test['test-type']):
action['type'] = 'link'
elif re.match(r'^run',test['test-type']):
action['type'] = 'run'
#~ The result sub-part we will add this result to.
if action_node.getAttribute('status') == '0':
action['result'] = 'succeed'
else:
action['result'] = 'fail'
# Add the action to the test.
test['actions'].append(action)
# Set the test result if this is the result action for the test.
if action_type == 'result':
test['result'] = action['result']
return None | [
"def",
"x_build_action",
"(",
"self",
",",
"node",
")",
":",
"action_node",
"=",
"node",
"name",
"=",
"self",
".",
"get_child",
"(",
"action_node",
",",
"tag",
"=",
"'name'",
")",
"if",
"name",
":",
"name",
"=",
"self",
".",
"get_data",
"(",
"name",
")",
"#~ Based on the action, we decide what sub-section the log",
"#~ should go into.",
"action_type",
"=",
"None",
"if",
"re",
".",
"match",
"(",
"'[^%]+%[^.]+[.](compile)'",
",",
"name",
")",
":",
"action_type",
"=",
"'compile'",
"elif",
"re",
".",
"match",
"(",
"'[^%]+%[^.]+[.](link|archive)'",
",",
"name",
")",
":",
"action_type",
"=",
"'link'",
"elif",
"re",
".",
"match",
"(",
"'[^%]+%testing[.](capture-output)'",
",",
"name",
")",
":",
"action_type",
"=",
"'run'",
"elif",
"re",
".",
"match",
"(",
"'[^%]+%testing[.](expect-failure|expect-success)'",
",",
"name",
")",
":",
"action_type",
"=",
"'result'",
"else",
":",
"# TODO: Enable to see what other actions can be included in the test results.",
"# action_type = None",
"action_type",
"=",
"'other'",
"#~ print \"+ [%s] %s %s :: %s\" %(action_type,name,'','')",
"if",
"action_type",
":",
"#~ Get the corresponding test.",
"(",
"target",
",",
"test",
")",
"=",
"self",
".",
"get_test",
"(",
"action_node",
",",
"type",
"=",
"action_type",
")",
"#~ Skip action that have no corresponding test as they are",
"#~ regular build actions and don't need to show up in the",
"#~ regression results.",
"if",
"not",
"test",
":",
"##print \"??? [%s] %s %s :: %s\" %(action_type,name,target,test)",
"return",
"None",
"##print \"+++ [%s] %s %s :: %s\" %(action_type,name,target,test)",
"#~ Collect some basic info about the action.",
"action",
"=",
"{",
"'command'",
":",
"self",
".",
"get_action_command",
"(",
"action_node",
",",
"action_type",
")",
",",
"'output'",
":",
"self",
".",
"get_action_output",
"(",
"action_node",
",",
"action_type",
")",
",",
"'info'",
":",
"self",
".",
"get_action_info",
"(",
"action_node",
",",
"action_type",
")",
"}",
"#~ For the test result status we find the appropriate node",
"#~ based on the type of test. Then adjust the result status",
"#~ accordingly. This makes the result status reflect the",
"#~ expectation as the result pages post processing does not",
"#~ account for this inversion.",
"action",
"[",
"'type'",
"]",
"=",
"action_type",
"if",
"action_type",
"==",
"'result'",
":",
"if",
"re",
".",
"match",
"(",
"r'^compile'",
",",
"test",
"[",
"'test-type'",
"]",
")",
":",
"action",
"[",
"'type'",
"]",
"=",
"'compile'",
"elif",
"re",
".",
"match",
"(",
"r'^link'",
",",
"test",
"[",
"'test-type'",
"]",
")",
":",
"action",
"[",
"'type'",
"]",
"=",
"'link'",
"elif",
"re",
".",
"match",
"(",
"r'^run'",
",",
"test",
"[",
"'test-type'",
"]",
")",
":",
"action",
"[",
"'type'",
"]",
"=",
"'run'",
"#~ The result sub-part we will add this result to.",
"if",
"action_node",
".",
"getAttribute",
"(",
"'status'",
")",
"==",
"'0'",
":",
"action",
"[",
"'result'",
"]",
"=",
"'succeed'",
"else",
":",
"action",
"[",
"'result'",
"]",
"=",
"'fail'",
"# Add the action to the test.",
"test",
"[",
"'actions'",
"]",
".",
"append",
"(",
"action",
")",
"# Set the test result if this is the result action for the test.",
"if",
"action_type",
"==",
"'result'",
":",
"test",
"[",
"'result'",
"]",
"=",
"action",
"[",
"'result'",
"]",
"return",
"None"
] | Given a build action log, process into the corresponding test log and
specific test log sub-part. | [
"Given",
"a",
"build",
"action",
"log",
"process",
"into",
"the",
"corresponding",
"test",
"log",
"and",
"specific",
"test",
"log",
"sub",
"-",
"part",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L169-L233 |
28,899 | apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.x_build_timestamp | def x_build_timestamp( self, node ):
'''
The time-stamp goes to the corresponding attribute in the result.
'''
self.timestamps.append(self.get_data(node).strip())
return None | python | def x_build_timestamp( self, node ):
'''
The time-stamp goes to the corresponding attribute in the result.
'''
self.timestamps.append(self.get_data(node).strip())
return None | [
"def",
"x_build_timestamp",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"timestamps",
".",
"append",
"(",
"self",
".",
"get_data",
"(",
"node",
")",
".",
"strip",
"(",
")",
")",
"return",
"None"
] | The time-stamp goes to the corresponding attribute in the result. | [
"The",
"time",
"-",
"stamp",
"goes",
"to",
"the",
"corresponding",
"attribute",
"in",
"the",
"result",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L235-L240 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.