nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/RemoteConsole/ly_remote_console/ly_remote_console/remote_console_commands.py | python | _default_disconnect | () | On a disconnect a user can overwrite the functionality with any function, this one will just print to the
logger a line 'Disconnecting from the Port.'
:return: None | On a disconnect a user can overwrite the functionality with any function, this one will just print to the
logger a line 'Disconnecting from the Port.'
:return: None | [
"On",
"a",
"disconnect",
"a",
"user",
"can",
"overwrite",
"the",
"functionality",
"with",
"any",
"function",
"this",
"one",
"will",
"just",
"print",
"to",
"the",
"logger",
"a",
"line",
"Disconnecting",
"from",
"the",
"Port",
".",
":",
"return",
":",
"None"
] | def _default_disconnect():
# type: () -> None
"""
On a disconnect a user can overwrite the functionality with any function, this one will just print to the
logger a line 'Disconnecting from the Port.'
:return: None
"""
logger.info('Disconnecting from the Port') | [
"def",
"_default_disconnect",
"(",
")",
":",
"# type: () -> None",
"logger",
".",
"info",
"(",
"'Disconnecting from the Port'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/RemoteConsole/ly_remote_console/ly_remote_console/remote_console_commands.py#L87-L94 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py | python | host_memory_extents | (obj) | return mviewbuf.memoryview_get_extents(obj) | Returns (start, end) the start and end pointer of the array (half open). | Returns (start, end) the start and end pointer of the array (half open). | [
"Returns",
"(",
"start",
"end",
")",
"the",
"start",
"and",
"end",
"pointer",
"of",
"the",
"array",
"(",
"half",
"open",
")",
"."
] | def host_memory_extents(obj):
"Returns (start, end) the start and end pointer of the array (half open)."
obj = _workaround_for_datetime(obj)
return mviewbuf.memoryview_get_extents(obj) | [
"def",
"host_memory_extents",
"(",
"obj",
")",
":",
"obj",
"=",
"_workaround_for_datetime",
"(",
"obj",
")",
"return",
"mviewbuf",
".",
"memoryview_get_extents",
"(",
"obj",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py#L1821-L1824 | |
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/input.py | python | SequenceFileStream.transform_from_node | (self, load_node, pipeline) | return pcollection.PCollection(transformed.node().leave_scope(), pipeline) | 内部方法 | 内部方法 | [
"内部方法"
] | def transform_from_node(self, load_node, pipeline):
""" 内部方法 """
transformed = load_node.repeatedly() \
.process_by(_KVFromBinaryRecord()) \
.as_type(serde.tuple_of(serde.StrSerde(), serde.StrSerde())) \
.set_effective_key_num(0) \
.input(0).allow_partial_processing() \
.done()
transformed.set_size(load_node.size())
transformed = pcollection.PCollection(transformed, pipeline)
tserde = self._options.get('serde', pipeline.default_objector())
if self.kv_deserializer is not None:
transformed = transformed.map(self.kv_deserializer, serde = tserde)
else:
is_serialize = False
deserialize = entity.SerdeWrapper(tserde, is_serialize, 1)
transformed = transformed.map(deserialize, serde = tserde)
return pcollection.PCollection(transformed.node().leave_scope(), pipeline) | [
"def",
"transform_from_node",
"(",
"self",
",",
"load_node",
",",
"pipeline",
")",
":",
"transformed",
"=",
"load_node",
".",
"repeatedly",
"(",
")",
".",
"process_by",
"(",
"_KVFromBinaryRecord",
"(",
")",
")",
".",
"as_type",
"(",
"serde",
".",
"tuple_of",
"(",
"serde",
".",
"StrSerde",
"(",
")",
",",
"serde",
".",
"StrSerde",
"(",
")",
")",
")",
".",
"set_effective_key_num",
"(",
"0",
")",
".",
"input",
"(",
"0",
")",
".",
"allow_partial_processing",
"(",
")",
".",
"done",
"(",
")",
"transformed",
".",
"set_size",
"(",
"load_node",
".",
"size",
"(",
")",
")",
"transformed",
"=",
"pcollection",
".",
"PCollection",
"(",
"transformed",
",",
"pipeline",
")",
"tserde",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'serde'",
",",
"pipeline",
".",
"default_objector",
"(",
")",
")",
"if",
"self",
".",
"kv_deserializer",
"is",
"not",
"None",
":",
"transformed",
"=",
"transformed",
".",
"map",
"(",
"self",
".",
"kv_deserializer",
",",
"serde",
"=",
"tserde",
")",
"else",
":",
"is_serialize",
"=",
"False",
"deserialize",
"=",
"entity",
".",
"SerdeWrapper",
"(",
"tserde",
",",
"is_serialize",
",",
"1",
")",
"transformed",
"=",
"transformed",
".",
"map",
"(",
"deserialize",
",",
"serde",
"=",
"tserde",
")",
"return",
"pcollection",
".",
"PCollection",
"(",
"transformed",
".",
"node",
"(",
")",
".",
"leave_scope",
"(",
")",
",",
"pipeline",
")"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/input.py#L742-L764 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/value_object/read/media/datfile/empiresdat.py | python | EmpiresDatWrapper.get_data_format_members | (cls, game_version) | return data_format | Return the members in this struct. | Return the members in this struct. | [
"Return",
"the",
"members",
"in",
"this",
"struct",
"."
] | def get_data_format_members(cls, game_version):
"""
Return the members in this struct.
"""
data_format = [
(READ_GEN, "empiresdat", StorageType.ARRAY_CONTAINER, SubdataMember(
ref_type=EmpiresDat,
length=1,
)),
]
return data_format | [
"def",
"get_data_format_members",
"(",
"cls",
",",
"game_version",
")",
":",
"data_format",
"=",
"[",
"(",
"READ_GEN",
",",
"\"empiresdat\"",
",",
"StorageType",
".",
"ARRAY_CONTAINER",
",",
"SubdataMember",
"(",
"ref_type",
"=",
"EmpiresDat",
",",
"length",
"=",
"1",
",",
")",
")",
",",
"]",
"return",
"data_format"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/value_object/read/media/datfile/empiresdat.py#L341-L352 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/internal/enum_type_wrapper.py | python | EnumTypeWrapper.Name | (self, number) | Returns a string containing the name of an enum value. | Returns a string containing the name of an enum value. | [
"Returns",
"a",
"string",
"containing",
"the",
"name",
"of",
"an",
"enum",
"value",
"."
] | def Name(self, number): # pylint: disable=invalid-name
"""Returns a string containing the name of an enum value."""
try:
return self._enum_type.values_by_number[number].name
except KeyError:
pass # fall out to break exception chaining
if not isinstance(number, six.integer_types):
raise TypeError(
'Enum value for {} must be an int, but got {} {!r}.'.format(
self._enum_type.name, type(number), number))
else:
# repr here to handle the odd case when you pass in a boolean.
raise ValueError('Enum {} has no name defined for value {!r}'.format(
self._enum_type.name, number)) | [
"def",
"Name",
"(",
"self",
",",
"number",
")",
":",
"# pylint: disable=invalid-name",
"try",
":",
"return",
"self",
".",
"_enum_type",
".",
"values_by_number",
"[",
"number",
"]",
".",
"name",
"except",
"KeyError",
":",
"pass",
"# fall out to break exception chaining",
"if",
"not",
"isinstance",
"(",
"number",
",",
"six",
".",
"integer_types",
")",
":",
"raise",
"TypeError",
"(",
"'Enum value for {} must be an int, but got {} {!r}.'",
".",
"format",
"(",
"self",
".",
"_enum_type",
".",
"name",
",",
"type",
"(",
"number",
")",
",",
"number",
")",
")",
"else",
":",
"# repr here to handle the odd case when you pass in a boolean.",
"raise",
"ValueError",
"(",
"'Enum {} has no name defined for value {!r}'",
".",
"format",
"(",
"self",
".",
"_enum_type",
".",
"name",
",",
"number",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/enum_type_wrapper.py#L53-L67 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/inspect.py | python | _signature_is_functionlike | (obj) | return (isinstance(code, types.CodeType) and
isinstance(name, str) and
(defaults is None or isinstance(defaults, tuple)) and
(kwdefaults is None or isinstance(kwdefaults, dict)) and
isinstance(annotations, dict)) | Private helper to test if `obj` is a duck type of FunctionType.
A good example of such objects are functions compiled with
Cython, which have all attributes that a pure Python function
would have, but have their code statically compiled. | Private helper to test if `obj` is a duck type of FunctionType.
A good example of such objects are functions compiled with
Cython, which have all attributes that a pure Python function
would have, but have their code statically compiled. | [
"Private",
"helper",
"to",
"test",
"if",
"obj",
"is",
"a",
"duck",
"type",
"of",
"FunctionType",
".",
"A",
"good",
"example",
"of",
"such",
"objects",
"are",
"functions",
"compiled",
"with",
"Cython",
"which",
"have",
"all",
"attributes",
"that",
"a",
"pure",
"Python",
"function",
"would",
"have",
"but",
"have",
"their",
"code",
"statically",
"compiled",
"."
] | def _signature_is_functionlike(obj):
"""Private helper to test if `obj` is a duck type of FunctionType.
A good example of such objects are functions compiled with
Cython, which have all attributes that a pure Python function
would have, but have their code statically compiled.
"""
if not callable(obj) or isclass(obj):
# All function-like objects are obviously callables,
# and not classes.
return False
name = getattr(obj, '__name__', None)
code = getattr(obj, '__code__', None)
defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
annotations = getattr(obj, '__annotations__', None)
return (isinstance(code, types.CodeType) and
isinstance(name, str) and
(defaults is None or isinstance(defaults, tuple)) and
(kwdefaults is None or isinstance(kwdefaults, dict)) and
isinstance(annotations, dict)) | [
"def",
"_signature_is_functionlike",
"(",
"obj",
")",
":",
"if",
"not",
"callable",
"(",
"obj",
")",
"or",
"isclass",
"(",
"obj",
")",
":",
"# All function-like objects are obviously callables,",
"# and not classes.",
"return",
"False",
"name",
"=",
"getattr",
"(",
"obj",
",",
"'__name__'",
",",
"None",
")",
"code",
"=",
"getattr",
"(",
"obj",
",",
"'__code__'",
",",
"None",
")",
"defaults",
"=",
"getattr",
"(",
"obj",
",",
"'__defaults__'",
",",
"_void",
")",
"# Important to use _void ...",
"kwdefaults",
"=",
"getattr",
"(",
"obj",
",",
"'__kwdefaults__'",
",",
"_void",
")",
"# ... and not None here",
"annotations",
"=",
"getattr",
"(",
"obj",
",",
"'__annotations__'",
",",
"None",
")",
"return",
"(",
"isinstance",
"(",
"code",
",",
"types",
".",
"CodeType",
")",
"and",
"isinstance",
"(",
"name",
",",
"str",
")",
"and",
"(",
"defaults",
"is",
"None",
"or",
"isinstance",
"(",
"defaults",
",",
"tuple",
")",
")",
"and",
"(",
"kwdefaults",
"is",
"None",
"or",
"isinstance",
"(",
"kwdefaults",
",",
"dict",
")",
")",
"and",
"isinstance",
"(",
"annotations",
",",
"dict",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/inspect.py#L1837-L1859 | |
xieyufei1993/FOTS | 9881966697fd5e2936d2cca8aa04309e4b64f77c | data/dataset.py | python | image_label | (txt_root, image_list, img_name, index,
input_size=512, random_scale=np.array([0.5, 1, 2.0, 3.0]),
background_ratio=3. / 8) | return images, score_maps, geo_maps, training_masks | get image's corresponding matrix and ground truth | get image's corresponding matrix and ground truth | [
"get",
"image",
"s",
"corresponding",
"matrix",
"and",
"ground",
"truth"
] | def image_label(txt_root, image_list, img_name, index,
input_size=512, random_scale=np.array([0.5, 1, 2.0, 3.0]),
background_ratio=3. / 8):
'''
get image's corresponding matrix and ground truth
'''
try:
im_fn = image_list[index]
im_name = img_name[index]
im = cv2.imread(im_fn)
h, w, _ = im.shape
#txt_fn = im_name.replace(im_name.split('.')[1], 'txt')
#print(txt_fn)
if os.path.exists(txt_root + "/"+im_name[0:-4] + '.txt'):
txt_fn = im_name[0:-4] + '.txt'
elif os.path.exists(txt_root + "/"+im_name[0:-5] + '.txt'):
txt_fn = im_name[0:-5] + '.txt'
txt_fn = os.path.join(txt_root, txt_fn)
text_polys, text_tags = load_annoataion(txt_fn)
text_polys, text_tags = check_and_validate_polys(text_polys, text_tags, (h, w))
rd_scale = np.random.choice(random_scale)
im = cv2.resize(im, dsize=None, fx=rd_scale, fy=rd_scale)
text_polys *= rd_scale
# random crop a area from image
if np.random.rand() < background_ratio:
# crop background
im, text_polys, text_tags = crop_area(im, text_polys, text_tags, crop_background=True)
new_h, new_w, _ = im.shape
max_h_w_i = np.max([new_h, new_w, input_size])
im_padded = np.zeros((max_h_w_i, max_h_w_i, 3), dtype=np.uint8)
im_padded[:new_h, :new_w, :] = im.copy()
im = cv2.resize(im_padded, dsize=(input_size, input_size))
score_map = np.zeros((input_size, input_size), dtype=np.uint8)
geo_map_channels = 5
geo_map = np.zeros((input_size, input_size, geo_map_channels), dtype=np.float32)
training_mask = np.ones((input_size, input_size), dtype=np.uint8)
else:
im, text_polys, text_tags = crop_area(im, text_polys, text_tags, crop_background=False)
h, w, _ = im.shape
# pad the image to the training input size or the longer side of image
new_h, new_w, _ = im.shape
max_h_w_i = np.max([new_h, new_w, input_size])
im_padded = np.zeros((max_h_w_i, max_h_w_i, 3), dtype=np.uint8)
im_padded[:new_h, :new_w, :] = im.copy()
im = im_padded
new_h, new_w, _ = im.shape
resize_h = input_size
resize_w = input_size
im = cv2.resize(im, dsize=(resize_w, resize_h))
resize_ratio_3_x = resize_w / float(new_w)
resize_ratio_3_y = resize_h / float(new_h)
text_polys[:, :, 0] *= resize_ratio_3_x
text_polys[:, :, 1] *= resize_ratio_3_y
new_h, new_w, _ = im.shape
score_map, geo_map, training_mask = generate_rbox((new_h, new_w), text_polys, text_tags)
images = im[:, :, ::-1].astype(np.float32)
score_maps = score_map[::4, ::4, np.newaxis].astype(np.float32)
geo_maps = geo_map[::4, ::4, :].astype(np.float32)
training_masks = training_mask[::4, ::4, np.newaxis].astype(np.float32)
except Exception as e:
images, score_maps, geo_maps, training_masks = None, None, None, None
return images, score_maps, geo_maps, training_masks | [
"def",
"image_label",
"(",
"txt_root",
",",
"image_list",
",",
"img_name",
",",
"index",
",",
"input_size",
"=",
"512",
",",
"random_scale",
"=",
"np",
".",
"array",
"(",
"[",
"0.5",
",",
"1",
",",
"2.0",
",",
"3.0",
"]",
")",
",",
"background_ratio",
"=",
"3.",
"/",
"8",
")",
":",
"try",
":",
"im_fn",
"=",
"image_list",
"[",
"index",
"]",
"im_name",
"=",
"img_name",
"[",
"index",
"]",
"im",
"=",
"cv2",
".",
"imread",
"(",
"im_fn",
")",
"h",
",",
"w",
",",
"_",
"=",
"im",
".",
"shape",
"#txt_fn = im_name.replace(im_name.split('.')[1], 'txt')",
"#print(txt_fn)",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"txt_root",
"+",
"\"/\"",
"+",
"im_name",
"[",
"0",
":",
"-",
"4",
"]",
"+",
"'.txt'",
")",
":",
"txt_fn",
"=",
"im_name",
"[",
"0",
":",
"-",
"4",
"]",
"+",
"'.txt'",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"txt_root",
"+",
"\"/\"",
"+",
"im_name",
"[",
"0",
":",
"-",
"5",
"]",
"+",
"'.txt'",
")",
":",
"txt_fn",
"=",
"im_name",
"[",
"0",
":",
"-",
"5",
"]",
"+",
"'.txt'",
"txt_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"txt_root",
",",
"txt_fn",
")",
"text_polys",
",",
"text_tags",
"=",
"load_annoataion",
"(",
"txt_fn",
")",
"text_polys",
",",
"text_tags",
"=",
"check_and_validate_polys",
"(",
"text_polys",
",",
"text_tags",
",",
"(",
"h",
",",
"w",
")",
")",
"rd_scale",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"random_scale",
")",
"im",
"=",
"cv2",
".",
"resize",
"(",
"im",
",",
"dsize",
"=",
"None",
",",
"fx",
"=",
"rd_scale",
",",
"fy",
"=",
"rd_scale",
")",
"text_polys",
"*=",
"rd_scale",
"# random crop a area from image",
"if",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"background_ratio",
":",
"# crop background",
"im",
",",
"text_polys",
",",
"text_tags",
"=",
"crop_area",
"(",
"im",
",",
"text_polys",
",",
"text_tags",
",",
"crop_background",
"=",
"True",
")",
"new_h",
",",
"new_w",
",",
"_",
"=",
"im",
".",
"shape",
"max_h_w_i",
"=",
"np",
".",
"max",
"(",
"[",
"new_h",
",",
"new_w",
",",
"input_size",
"]",
")",
"im_padded",
"=",
"np",
".",
"zeros",
"(",
"(",
"max_h_w_i",
",",
"max_h_w_i",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"im_padded",
"[",
":",
"new_h",
",",
":",
"new_w",
",",
":",
"]",
"=",
"im",
".",
"copy",
"(",
")",
"im",
"=",
"cv2",
".",
"resize",
"(",
"im_padded",
",",
"dsize",
"=",
"(",
"input_size",
",",
"input_size",
")",
")",
"score_map",
"=",
"np",
".",
"zeros",
"(",
"(",
"input_size",
",",
"input_size",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"geo_map_channels",
"=",
"5",
"geo_map",
"=",
"np",
".",
"zeros",
"(",
"(",
"input_size",
",",
"input_size",
",",
"geo_map_channels",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"training_mask",
"=",
"np",
".",
"ones",
"(",
"(",
"input_size",
",",
"input_size",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"else",
":",
"im",
",",
"text_polys",
",",
"text_tags",
"=",
"crop_area",
"(",
"im",
",",
"text_polys",
",",
"text_tags",
",",
"crop_background",
"=",
"False",
")",
"h",
",",
"w",
",",
"_",
"=",
"im",
".",
"shape",
"# pad the image to the training input size or the longer side of image",
"new_h",
",",
"new_w",
",",
"_",
"=",
"im",
".",
"shape",
"max_h_w_i",
"=",
"np",
".",
"max",
"(",
"[",
"new_h",
",",
"new_w",
",",
"input_size",
"]",
")",
"im_padded",
"=",
"np",
".",
"zeros",
"(",
"(",
"max_h_w_i",
",",
"max_h_w_i",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"im_padded",
"[",
":",
"new_h",
",",
":",
"new_w",
",",
":",
"]",
"=",
"im",
".",
"copy",
"(",
")",
"im",
"=",
"im_padded",
"new_h",
",",
"new_w",
",",
"_",
"=",
"im",
".",
"shape",
"resize_h",
"=",
"input_size",
"resize_w",
"=",
"input_size",
"im",
"=",
"cv2",
".",
"resize",
"(",
"im",
",",
"dsize",
"=",
"(",
"resize_w",
",",
"resize_h",
")",
")",
"resize_ratio_3_x",
"=",
"resize_w",
"/",
"float",
"(",
"new_w",
")",
"resize_ratio_3_y",
"=",
"resize_h",
"/",
"float",
"(",
"new_h",
")",
"text_polys",
"[",
":",
",",
":",
",",
"0",
"]",
"*=",
"resize_ratio_3_x",
"text_polys",
"[",
":",
",",
":",
",",
"1",
"]",
"*=",
"resize_ratio_3_y",
"new_h",
",",
"new_w",
",",
"_",
"=",
"im",
".",
"shape",
"score_map",
",",
"geo_map",
",",
"training_mask",
"=",
"generate_rbox",
"(",
"(",
"new_h",
",",
"new_w",
")",
",",
"text_polys",
",",
"text_tags",
")",
"images",
"=",
"im",
"[",
":",
",",
":",
",",
":",
":",
"-",
"1",
"]",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"score_maps",
"=",
"score_map",
"[",
":",
":",
"4",
",",
":",
":",
"4",
",",
"np",
".",
"newaxis",
"]",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"geo_maps",
"=",
"geo_map",
"[",
":",
":",
"4",
",",
":",
":",
"4",
",",
":",
"]",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"training_masks",
"=",
"training_mask",
"[",
":",
":",
"4",
",",
":",
":",
"4",
",",
"np",
".",
"newaxis",
"]",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"except",
"Exception",
"as",
"e",
":",
"images",
",",
"score_maps",
",",
"geo_maps",
",",
"training_masks",
"=",
"None",
",",
"None",
",",
"None",
",",
"None",
"return",
"images",
",",
"score_maps",
",",
"geo_maps",
",",
"training_masks"
] | https://github.com/xieyufei1993/FOTS/blob/9881966697fd5e2936d2cca8aa04309e4b64f77c/data/dataset.py#L566-L633 | |
goldeneye-source/ges-code | 2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d | thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py | python | _AddByteSizeMethod | (message_descriptor, cls) | Helper for _AddMessageMethods(). | Helper for _AddMessageMethods(). | [
"Helper",
"for",
"_AddMessageMethods",
"()",
"."
] | def _AddByteSizeMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def ByteSize(self):
if not self._cached_byte_size_dirty:
return self._cached_byte_size
size = 0
for field_descriptor, field_value in self.ListFields():
size += field_descriptor._sizer(field_value)
self._cached_byte_size = size
self._cached_byte_size_dirty = False
self._listener_for_children.dirty = False
return size
cls.ByteSize = ByteSize | [
"def",
"_AddByteSizeMethod",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"def",
"ByteSize",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_cached_byte_size_dirty",
":",
"return",
"self",
".",
"_cached_byte_size",
"size",
"=",
"0",
"for",
"field_descriptor",
",",
"field_value",
"in",
"self",
".",
"ListFields",
"(",
")",
":",
"size",
"+=",
"field_descriptor",
".",
"_sizer",
"(",
"field_value",
")",
"self",
".",
"_cached_byte_size",
"=",
"size",
"self",
".",
"_cached_byte_size_dirty",
"=",
"False",
"self",
".",
"_listener_for_children",
".",
"dirty",
"=",
"False",
"return",
"size",
"cls",
".",
"ByteSize",
"=",
"ByteSize"
] | https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L768-L784 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | TurtleScreen.getcanvas | (self) | return self.cv | Return the Canvas of this TurtleScreen.
No argument.
Example (for a Screen instance named screen):
>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas instance at 0x010742D8> | Return the Canvas of this TurtleScreen. | [
"Return",
"the",
"Canvas",
"of",
"this",
"TurtleScreen",
"."
] | def getcanvas(self):
"""Return the Canvas of this TurtleScreen.
No argument.
Example (for a Screen instance named screen):
>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas instance at 0x010742D8>
"""
return self.cv | [
"def",
"getcanvas",
"(",
"self",
")",
":",
"return",
"self",
".",
"cv"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L1327-L1337 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/nn/api/remote_module.py | python | _recursive_script_module_receiver | (
recursive_script_module_serialized,
) | return m | Deserializes a RecursiveScirptModule that does not contain a script RemoteModule. | Deserializes a RecursiveScirptModule that does not contain a script RemoteModule. | [
"Deserializes",
"a",
"RecursiveScirptModule",
"that",
"does",
"not",
"contain",
"a",
"script",
"RemoteModule",
"."
] | def _recursive_script_module_receiver(
recursive_script_module_serialized,
):
"""
Deserializes a RecursiveScirptModule that does not contain a script RemoteModule.
"""
f = io.BytesIO(recursive_script_module_serialized)
m = torch.jit.load(f)
return m | [
"def",
"_recursive_script_module_receiver",
"(",
"recursive_script_module_serialized",
",",
")",
":",
"f",
"=",
"io",
".",
"BytesIO",
"(",
"recursive_script_module_serialized",
")",
"m",
"=",
"torch",
".",
"jit",
".",
"load",
"(",
"f",
")",
"return",
"m"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/nn/api/remote_module.py#L707-L715 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/internetcontent/nv_python_libs/common/common_api.py | python | Common.getItemElement | (self, context, arg) | return self.itemElement | Return an item element that was created by a previous call to the checkIfDBItem function | Return an item element that was created by a previous call to the checkIfDBItem function | [
"Return",
"an",
"item",
"element",
"that",
"was",
"created",
"by",
"a",
"previous",
"call",
"to",
"the",
"checkIfDBItem",
"function"
] | def getItemElement(self, context, arg):
''' Return an item element that was created by a previous call to the checkIfDBItem function
'''
return self.itemElement | [
"def",
"getItemElement",
"(",
"self",
",",
"context",
",",
"arg",
")",
":",
"return",
"self",
".",
"itemElement"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/common/common_api.py#L841-L844 | |
NicknineTheEagle/TF2-Base | 20459c5a7fbc995b6bf54fa85c2f62a101e9fb64 | src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py | python | _Tokenizer.ConsumeInt64 | (self) | return result | Consumes a signed 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 64bit integer couldn't be consumed. | Consumes a signed 64bit integer number. | [
"Consumes",
"a",
"signed",
"64bit",
"integer",
"number",
"."
] | def ConsumeInt64(self):
"""Consumes a signed 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 64bit integer couldn't be consumed.
"""
try:
result = self._ParseInteger(self.token, is_signed=True, is_long=True)
except ValueError, e:
raise self._IntegerParseError(e)
self.NextToken()
return result | [
"def",
"ConsumeInt64",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"_ParseInteger",
"(",
"self",
".",
"token",
",",
"is_signed",
"=",
"True",
",",
"is_long",
"=",
"True",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"self",
".",
"_IntegerParseError",
"(",
"e",
")",
"self",
".",
"NextToken",
"(",
")",
"return",
"result"
] | https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py#L442-L456 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/yaml_key_value.py | python | get_yaml_value | (yaml_file, yaml_key) | return str(yaml_dict.get(yaml_key, "")) | Return string value for 'yaml_key' from 'yaml_file'. | Return string value for 'yaml_key' from 'yaml_file'. | [
"Return",
"string",
"value",
"for",
"yaml_key",
"from",
"yaml_file",
"."
] | def get_yaml_value(yaml_file, yaml_key):
"""Return string value for 'yaml_key' from 'yaml_file'."""
with open(yaml_file, "r") as ystream:
yaml_dict = yaml.safe_load(ystream)
return str(yaml_dict.get(yaml_key, "")) | [
"def",
"get_yaml_value",
"(",
"yaml_file",
",",
"yaml_key",
")",
":",
"with",
"open",
"(",
"yaml_file",
",",
"\"r\"",
")",
"as",
"ystream",
":",
"yaml_dict",
"=",
"yaml",
".",
"safe_load",
"(",
"ystream",
")",
"return",
"str",
"(",
"yaml_dict",
".",
"get",
"(",
"yaml_key",
",",
"\"\"",
")",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/yaml_key_value.py#L9-L13 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py | python | index | (s, *args) | return _apply(s.index, args) | index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found. | index(s, sub [,start [,end]]) -> int | [
"index",
"(",
"s",
"sub",
"[",
"start",
"[",
"end",
"]]",
")",
"-",
">",
"int"
] | def index(s, *args):
"""index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found.
"""
return _apply(s.index, args) | [
"def",
"index",
"(",
"s",
",",
"*",
"args",
")",
":",
"return",
"_apply",
"(",
"s",
".",
"index",
",",
"args",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py#L136-L142 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/optparse.py | python | OptionParser.enable_interspersed_args | (self) | Set parsing to not stop on the first non-option, allowing
interspersing switches with command arguments. This is the
default behavior. See also disable_interspersed_args() and the
class documentation description of the attribute
allow_interspersed_args. | Set parsing to not stop on the first non-option, allowing
interspersing switches with command arguments. This is the
default behavior. See also disable_interspersed_args() and the
class documentation description of the attribute
allow_interspersed_args. | [
"Set",
"parsing",
"to",
"not",
"stop",
"on",
"the",
"first",
"non",
"-",
"option",
"allowing",
"interspersing",
"switches",
"with",
"command",
"arguments",
".",
"This",
"is",
"the",
"default",
"behavior",
".",
"See",
"also",
"disable_interspersed_args",
"()",
"and",
"the",
"class",
"documentation",
"description",
"of",
"the",
"attribute",
"allow_interspersed_args",
"."
] | def enable_interspersed_args(self):
"""Set parsing to not stop on the first non-option, allowing
interspersing switches with command arguments. This is the
default behavior. See also disable_interspersed_args() and the
class documentation description of the attribute
allow_interspersed_args."""
self.allow_interspersed_args = True | [
"def",
"enable_interspersed_args",
"(",
"self",
")",
":",
"self",
".",
"allow_interspersed_args",
"=",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/optparse.py#L1275-L1281 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/calendar.py | python | Calendar.monthdays2calendar | (self, year, month) | return [ days[i:i+7] for i in range(0, len(days), 7) ] | Return a matrix representing a month's calendar.
Each row represents a week; week entries are
(day number, weekday number) tuples. Day numbers outside this month
are zero. | Return a matrix representing a month's calendar.
Each row represents a week; week entries are
(day number, weekday number) tuples. Day numbers outside this month
are zero. | [
"Return",
"a",
"matrix",
"representing",
"a",
"month",
"s",
"calendar",
".",
"Each",
"row",
"represents",
"a",
"week",
";",
"week",
"entries",
"are",
"(",
"day",
"number",
"weekday",
"number",
")",
"tuples",
".",
"Day",
"numbers",
"outside",
"this",
"month",
"are",
"zero",
"."
] | def monthdays2calendar(self, year, month):
"""
Return a matrix representing a month's calendar.
Each row represents a week; week entries are
(day number, weekday number) tuples. Day numbers outside this month
are zero.
"""
days = list(self.itermonthdays2(year, month))
return [ days[i:i+7] for i in range(0, len(days), 7) ] | [
"def",
"monthdays2calendar",
"(",
"self",
",",
"year",
",",
"month",
")",
":",
"days",
"=",
"list",
"(",
"self",
".",
"itermonthdays2",
"(",
"year",
",",
"month",
")",
")",
"return",
"[",
"days",
"[",
"i",
":",
"i",
"+",
"7",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"days",
")",
",",
"7",
")",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/calendar.py#L202-L210 | |
zhaoweicai/hwgq | ebc706bee3e2d145de1da4be446ce8de8740738f | scripts/cpp_lint.py | python | ReverseCloseExpression | (clean_lines, linenum, pos) | return (line, 0, -1) | If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum. | If input points to ) or } or ] or >, finds the position that opens it. | [
"If",
"input",
"points",
"to",
")",
"or",
"}",
"or",
"]",
"or",
">",
"finds",
"the",
"position",
"that",
"opens",
"it",
"."
] | def ReverseCloseExpression(clean_lines, linenum, pos):
"""If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
endchar = line[pos]
if endchar not in ')}]>':
return (line, 0, -1)
if endchar == ')': startchar = '('
if endchar == ']': startchar = '['
if endchar == '}': startchar = '{'
if endchar == '>': startchar = '<'
# Check last line
(start_pos, num_open) = FindStartOfExpressionInLine(
line, pos, 0, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Continue scanning backward
while linenum > 0:
linenum -= 1
line = clean_lines.elided[linenum]
(start_pos, num_open) = FindStartOfExpressionInLine(
line, len(line) - 1, num_open, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Did not find startchar before beginning of file, give up
return (line, 0, -1) | [
"def",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"endchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"endchar",
"not",
"in",
"')}]>'",
":",
"return",
"(",
"line",
",",
"0",
",",
"-",
"1",
")",
"if",
"endchar",
"==",
"')'",
":",
"startchar",
"=",
"'('",
"if",
"endchar",
"==",
"']'",
":",
"startchar",
"=",
"'['",
"if",
"endchar",
"==",
"'}'",
":",
"startchar",
"=",
"'{'",
"if",
"endchar",
"==",
"'>'",
":",
"startchar",
"=",
"'<'",
"# Check last line",
"(",
"start_pos",
",",
"num_open",
")",
"=",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"pos",
",",
"0",
",",
"startchar",
",",
"endchar",
")",
"if",
"start_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"start_pos",
")",
"# Continue scanning backward",
"while",
"linenum",
">",
"0",
":",
"linenum",
"-=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"(",
"start_pos",
",",
"num_open",
")",
"=",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"len",
"(",
"line",
")",
"-",
"1",
",",
"num_open",
",",
"startchar",
",",
"endchar",
")",
"if",
"start_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"start_pos",
")",
"# Did not find startchar before beginning of file, give up",
"return",
"(",
"line",
",",
"0",
",",
"-",
"1",
")"
] | https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/scripts/cpp_lint.py#L1327-L1369 | |
tum-vision/fusenet | a1451be2971b348a01b0f525c2a3a7a0e215a591 | tools/extra/parse_log.py | python | parse_log | (path_to_log) | return train_dict_list, test_dict_list | Parse log file
Returns (train_dict_list, train_dict_names, test_dict_list, test_dict_names)
train_dict_list and test_dict_list are lists of dicts that define the table
rows
train_dict_names and test_dict_names are ordered tuples of the column names
for the two dict_lists | Parse log file
Returns (train_dict_list, train_dict_names, test_dict_list, test_dict_names) | [
"Parse",
"log",
"file",
"Returns",
"(",
"train_dict_list",
"train_dict_names",
"test_dict_list",
"test_dict_names",
")"
] | def parse_log(path_to_log):
"""Parse log file
Returns (train_dict_list, train_dict_names, test_dict_list, test_dict_names)
train_dict_list and test_dict_list are lists of dicts that define the table
rows
train_dict_names and test_dict_names are ordered tuples of the column names
for the two dict_lists
"""
regex_iteration = re.compile('Iteration (\d+)')
regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_learning_rate = re.compile('lr = ([-+]?[0-9]*\.?[0-9]+([eE]?[-+]?[0-9]+)?)')
# Pick out lines of interest
iteration = -1
learning_rate = float('NaN')
train_dict_list = []
test_dict_list = []
train_row = None
test_row = None
logfile_year = extract_seconds.get_log_created_year(path_to_log)
with open(path_to_log) as f:
start_time = extract_seconds.get_start_time(f, logfile_year)
for line in f:
iteration_match = regex_iteration.search(line)
if iteration_match:
iteration = float(iteration_match.group(1))
if iteration == -1:
# Only start parsing for other stuff if we've found the first
# iteration
continue
time = extract_seconds.extract_datetime_from_line(line,
logfile_year)
seconds = (time - start_time).total_seconds()
learning_rate_match = regex_learning_rate.search(line)
if learning_rate_match:
learning_rate = float(learning_rate_match.group(1))
train_dict_list, train_row = parse_line_for_net_output(
regex_train_output, train_row, train_dict_list,
line, iteration, seconds, learning_rate
)
test_dict_list, test_row = parse_line_for_net_output(
regex_test_output, test_row, test_dict_list,
line, iteration, seconds, learning_rate
)
fix_initial_nan_learning_rate(train_dict_list)
fix_initial_nan_learning_rate(test_dict_list)
return train_dict_list, test_dict_list | [
"def",
"parse_log",
"(",
"path_to_log",
")",
":",
"regex_iteration",
"=",
"re",
".",
"compile",
"(",
"'Iteration (\\d+)'",
")",
"regex_train_output",
"=",
"re",
".",
"compile",
"(",
"'Train net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'",
")",
"regex_test_output",
"=",
"re",
".",
"compile",
"(",
"'Test net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'",
")",
"regex_learning_rate",
"=",
"re",
".",
"compile",
"(",
"'lr = ([-+]?[0-9]*\\.?[0-9]+([eE]?[-+]?[0-9]+)?)'",
")",
"# Pick out lines of interest",
"iteration",
"=",
"-",
"1",
"learning_rate",
"=",
"float",
"(",
"'NaN'",
")",
"train_dict_list",
"=",
"[",
"]",
"test_dict_list",
"=",
"[",
"]",
"train_row",
"=",
"None",
"test_row",
"=",
"None",
"logfile_year",
"=",
"extract_seconds",
".",
"get_log_created_year",
"(",
"path_to_log",
")",
"with",
"open",
"(",
"path_to_log",
")",
"as",
"f",
":",
"start_time",
"=",
"extract_seconds",
".",
"get_start_time",
"(",
"f",
",",
"logfile_year",
")",
"for",
"line",
"in",
"f",
":",
"iteration_match",
"=",
"regex_iteration",
".",
"search",
"(",
"line",
")",
"if",
"iteration_match",
":",
"iteration",
"=",
"float",
"(",
"iteration_match",
".",
"group",
"(",
"1",
")",
")",
"if",
"iteration",
"==",
"-",
"1",
":",
"# Only start parsing for other stuff if we've found the first",
"# iteration",
"continue",
"time",
"=",
"extract_seconds",
".",
"extract_datetime_from_line",
"(",
"line",
",",
"logfile_year",
")",
"seconds",
"=",
"(",
"time",
"-",
"start_time",
")",
".",
"total_seconds",
"(",
")",
"learning_rate_match",
"=",
"regex_learning_rate",
".",
"search",
"(",
"line",
")",
"if",
"learning_rate_match",
":",
"learning_rate",
"=",
"float",
"(",
"learning_rate_match",
".",
"group",
"(",
"1",
")",
")",
"train_dict_list",
",",
"train_row",
"=",
"parse_line_for_net_output",
"(",
"regex_train_output",
",",
"train_row",
",",
"train_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
"test_dict_list",
",",
"test_row",
"=",
"parse_line_for_net_output",
"(",
"regex_test_output",
",",
"test_row",
",",
"test_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
"fix_initial_nan_learning_rate",
"(",
"train_dict_list",
")",
"fix_initial_nan_learning_rate",
"(",
"test_dict_list",
")",
"return",
"train_dict_list",
",",
"test_dict_list"
] | https://github.com/tum-vision/fusenet/blob/a1451be2971b348a01b0f525c2a3a7a0e215a591/tools/extra/parse_log.py#L17-L74 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py | python | generate | (node, environment, name, filename, stream=None,
defer_init=False, optimized=True) | Generate the python source for a node tree. | Generate the python source for a node tree. | [
"Generate",
"the",
"python",
"source",
"for",
"a",
"node",
"tree",
"."
] | def generate(node, environment, name, filename, stream=None,
defer_init=False, optimized=True):
"""Generate the python source for a node tree."""
if not isinstance(node, nodes.Template):
raise TypeError('Can\'t compile non template nodes')
generator = environment.code_generator_class(environment, name, filename,
stream, defer_init,
optimized)
generator.visit(node)
if stream is None:
return generator.stream.getvalue() | [
"def",
"generate",
"(",
"node",
",",
"environment",
",",
"name",
",",
"filename",
",",
"stream",
"=",
"None",
",",
"defer_init",
"=",
"False",
",",
"optimized",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"Template",
")",
":",
"raise",
"TypeError",
"(",
"'Can\\'t compile non template nodes'",
")",
"generator",
"=",
"environment",
".",
"code_generator_class",
"(",
"environment",
",",
"name",
",",
"filename",
",",
"stream",
",",
"defer_init",
",",
"optimized",
")",
"generator",
".",
"visit",
"(",
"node",
")",
"if",
"stream",
"is",
"None",
":",
"return",
"generator",
".",
"stream",
".",
"getvalue",
"(",
")"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py#L74-L84 | ||
msftguy/ssh-rd | a5f3a79daeac5844edebf01916c9613563f1c390 | _3rd/boost_1_48_0/tools/build/v2/tools/gcc.py | python | init_link_flags | (toolset, linker, condition) | Now, the vendor specific flags.
The parameter linker can be either gnu, darwin, osf, hpux or sun. | Now, the vendor specific flags.
The parameter linker can be either gnu, darwin, osf, hpux or sun. | [
"Now",
"the",
"vendor",
"specific",
"flags",
".",
"The",
"parameter",
"linker",
"can",
"be",
"either",
"gnu",
"darwin",
"osf",
"hpux",
"or",
"sun",
"."
] | def init_link_flags(toolset, linker, condition):
"""
Now, the vendor specific flags.
The parameter linker can be either gnu, darwin, osf, hpux or sun.
"""
toolset_link = toolset + '.link'
if linker == 'gnu':
# Strip the binary when no debugging is needed. We use --strip-all flag
# as opposed to -s since icc (intel's compiler) is generally
# option-compatible with and inherits from the gcc toolset, but does not
# support -s.
# FIXME: what does unchecked translate to?
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition), ['-Wl,--strip-all']) # : unchecked ;
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
flags(toolset_link, 'RPATH_LINK', condition, ['<xdll-path>']) # : unchecked ;
flags(toolset_link, 'START-GROUP', condition, ['-Wl,--start-group'])# : unchecked ;
flags(toolset_link, 'END-GROUP', condition, ['-Wl,--end-group']) # : unchecked ;
# gnu ld has the ability to change the search behaviour for libraries
# referenced by -l switch. These modifiers are -Bstatic and -Bdynamic
# and change search for -l switches that follow them. The following list
# shows the tried variants.
# The search stops at the first variant that has a match.
# *nix: -Bstatic -lxxx
# libxxx.a
#
# *nix: -Bdynamic -lxxx
# libxxx.so
# libxxx.a
#
# windows (mingw,cygwin) -Bstatic -lxxx
# libxxx.a
# xxx.lib
#
# windows (mingw,cygwin) -Bdynamic -lxxx
# libxxx.dll.a
# xxx.dll.a
# libxxx.a
# xxx.lib
# cygxxx.dll (*)
# libxxx.dll
# xxx.dll
# libxxx.a
#
# (*) This is for cygwin
# Please note that -Bstatic and -Bdynamic are not a guarantee that a
# static or dynamic lib indeed gets linked in. The switches only change
# search patterns!
# On *nix mixing shared libs with static runtime is not a good idea.
flags(toolset_link, 'FINDLIBS-ST-PFX',
map(lambda x: x + '/<runtime-link>shared', condition),
['-Wl,-Bstatic']) # : unchecked ;
flags(toolset_link, 'FINDLIBS-SA-PFX',
map(lambda x: x + '/<runtime-link>shared', condition),
['-Wl,-Bdynamic']) # : unchecked ;
# On windows allow mixing of static and dynamic libs with static
# runtime.
flags(toolset_link, 'FINDLIBS-ST-PFX',
map(lambda x: x + '/<runtime-link>static/<target-os>windows', condition),
['-Wl,-Bstatic']) # : unchecked ;
flags(toolset_link, 'FINDLIBS-SA-PFX',
map(lambda x: x + '/<runtime-link>static/<target-os>windows', condition),
['-Wl,-Bdynamic']) # : unchecked ;
flags(toolset_link, 'OPTIONS',
map(lambda x: x + '/<runtime-link>static/<target-os>windows', condition),
['-Wl,-Bstatic']) # : unchecked ;
elif linker == 'darwin':
# On Darwin, the -s option to ld does not work unless we pass -static,
# and passing -static unconditionally is a bad idea. So, don't pass -s.
# at all, darwin.jam will use separate 'strip' invocation.
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
flags(toolset_link, 'RPATH_LINK', condition, ['<xdll-path>']) # : unchecked ;
elif linker == 'osf':
# No --strip-all, just -s.
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition), ['-Wl,-s'])
# : unchecked ;
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
# This does not supports -R.
flags(toolset_link, 'RPATH_OPTION', condition, ['-rpath']) # : unchecked ;
# -rpath-link is not supported at all.
elif linker == 'sun':
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition), ['-Wl,-s'])
# : unchecked ;
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
# Solaris linker does not have a separate -rpath-link, but allows to use
# -L for the same purpose.
flags(toolset_link, 'LINKPATH', condition, ['<xdll-path>']) # : unchecked ;
# This permits shared libraries with non-PIC code on Solaris.
# VP, 2004/09/07: Now that we have -fPIC hardcode in link.dll, the
# following is not needed. Whether -fPIC should be hardcoded, is a
# separate question.
# AH, 2004/10/16: it is still necessary because some tests link against
# static libraries that were compiled without PIC.
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<link>shared', condition), ['-mimpure-text'])
# : unchecked ;
elif linker == 'hpux':
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition),
['-Wl,-s']) # : unchecked ;
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<link>shared', condition),
['-fPIC']) # : unchecked ;
else:
# FIXME:
errors.user_error(
"$(toolset) initialization: invalid linker '$(linker)' " +
"The value '$(linker)' specified for <linker> is not recognized. " +
"Possible values are 'gnu', 'darwin', 'osf', 'hpux' or 'sun'") | [
"def",
"init_link_flags",
"(",
"toolset",
",",
"linker",
",",
"condition",
")",
":",
"toolset_link",
"=",
"toolset",
"+",
"'.link'",
"if",
"linker",
"==",
"'gnu'",
":",
"# Strip the binary when no debugging is needed. We use --strip-all flag",
"# as opposed to -s since icc (intel's compiler) is generally",
"# option-compatible with and inherits from the gcc toolset, but does not",
"# support -s.",
"# FIXME: what does unchecked translate to?",
"flags",
"(",
"toolset_link",
",",
"'OPTIONS'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<debug-symbols>off'",
",",
"condition",
")",
",",
"[",
"'-Wl,--strip-all'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'RPATH'",
",",
"condition",
",",
"[",
"'<dll-path>'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'RPATH_LINK'",
",",
"condition",
",",
"[",
"'<xdll-path>'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'START-GROUP'",
",",
"condition",
",",
"[",
"'-Wl,--start-group'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'END-GROUP'",
",",
"condition",
",",
"[",
"'-Wl,--end-group'",
"]",
")",
"# : unchecked ;",
"# gnu ld has the ability to change the search behaviour for libraries",
"# referenced by -l switch. These modifiers are -Bstatic and -Bdynamic",
"# and change search for -l switches that follow them. The following list",
"# shows the tried variants.",
"# The search stops at the first variant that has a match.",
"# *nix: -Bstatic -lxxx",
"# libxxx.a",
"#",
"# *nix: -Bdynamic -lxxx",
"# libxxx.so",
"# libxxx.a",
"#",
"# windows (mingw,cygwin) -Bstatic -lxxx",
"# libxxx.a",
"# xxx.lib",
"#",
"# windows (mingw,cygwin) -Bdynamic -lxxx",
"# libxxx.dll.a",
"# xxx.dll.a",
"# libxxx.a",
"# xxx.lib",
"# cygxxx.dll (*)",
"# libxxx.dll",
"# xxx.dll",
"# libxxx.a",
"#",
"# (*) This is for cygwin",
"# Please note that -Bstatic and -Bdynamic are not a guarantee that a",
"# static or dynamic lib indeed gets linked in. The switches only change",
"# search patterns!",
"# On *nix mixing shared libs with static runtime is not a good idea.",
"flags",
"(",
"toolset_link",
",",
"'FINDLIBS-ST-PFX'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<runtime-link>shared'",
",",
"condition",
")",
",",
"[",
"'-Wl,-Bstatic'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'FINDLIBS-SA-PFX'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<runtime-link>shared'",
",",
"condition",
")",
",",
"[",
"'-Wl,-Bdynamic'",
"]",
")",
"# : unchecked ;",
"# On windows allow mixing of static and dynamic libs with static",
"# runtime.",
"flags",
"(",
"toolset_link",
",",
"'FINDLIBS-ST-PFX'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<runtime-link>static/<target-os>windows'",
",",
"condition",
")",
",",
"[",
"'-Wl,-Bstatic'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'FINDLIBS-SA-PFX'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<runtime-link>static/<target-os>windows'",
",",
"condition",
")",
",",
"[",
"'-Wl,-Bdynamic'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'OPTIONS'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<runtime-link>static/<target-os>windows'",
",",
"condition",
")",
",",
"[",
"'-Wl,-Bstatic'",
"]",
")",
"# : unchecked ;",
"elif",
"linker",
"==",
"'darwin'",
":",
"# On Darwin, the -s option to ld does not work unless we pass -static,",
"# and passing -static unconditionally is a bad idea. So, don't pass -s.",
"# at all, darwin.jam will use separate 'strip' invocation.",
"flags",
"(",
"toolset_link",
",",
"'RPATH'",
",",
"condition",
",",
"[",
"'<dll-path>'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'RPATH_LINK'",
",",
"condition",
",",
"[",
"'<xdll-path>'",
"]",
")",
"# : unchecked ;",
"elif",
"linker",
"==",
"'osf'",
":",
"# No --strip-all, just -s.",
"flags",
"(",
"toolset_link",
",",
"'OPTIONS'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<debug-symbols>off'",
",",
"condition",
")",
",",
"[",
"'-Wl,-s'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'RPATH'",
",",
"condition",
",",
"[",
"'<dll-path>'",
"]",
")",
"# : unchecked ;",
"# This does not supports -R.",
"flags",
"(",
"toolset_link",
",",
"'RPATH_OPTION'",
",",
"condition",
",",
"[",
"'-rpath'",
"]",
")",
"# : unchecked ;",
"# -rpath-link is not supported at all.",
"elif",
"linker",
"==",
"'sun'",
":",
"flags",
"(",
"toolset_link",
",",
"'OPTIONS'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<debug-symbols>off'",
",",
"condition",
")",
",",
"[",
"'-Wl,-s'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'RPATH'",
",",
"condition",
",",
"[",
"'<dll-path>'",
"]",
")",
"# : unchecked ;",
"# Solaris linker does not have a separate -rpath-link, but allows to use",
"# -L for the same purpose.",
"flags",
"(",
"toolset_link",
",",
"'LINKPATH'",
",",
"condition",
",",
"[",
"'<xdll-path>'",
"]",
")",
"# : unchecked ;",
"# This permits shared libraries with non-PIC code on Solaris.",
"# VP, 2004/09/07: Now that we have -fPIC hardcode in link.dll, the",
"# following is not needed. Whether -fPIC should be hardcoded, is a",
"# separate question.",
"# AH, 2004/10/16: it is still necessary because some tests link against",
"# static libraries that were compiled without PIC.",
"flags",
"(",
"toolset_link",
",",
"'OPTIONS'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<link>shared'",
",",
"condition",
")",
",",
"[",
"'-mimpure-text'",
"]",
")",
"# : unchecked ;",
"elif",
"linker",
"==",
"'hpux'",
":",
"flags",
"(",
"toolset_link",
",",
"'OPTIONS'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<debug-symbols>off'",
",",
"condition",
")",
",",
"[",
"'-Wl,-s'",
"]",
")",
"# : unchecked ;",
"flags",
"(",
"toolset_link",
",",
"'OPTIONS'",
",",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"'/<link>shared'",
",",
"condition",
")",
",",
"[",
"'-fPIC'",
"]",
")",
"# : unchecked ;",
"else",
":",
"# FIXME:",
"errors",
".",
"user_error",
"(",
"\"$(toolset) initialization: invalid linker '$(linker)' \"",
"+",
"\"The value '$(linker)' specified for <linker> is not recognized. \"",
"+",
"\"Possible values are 'gnu', 'darwin', 'osf', 'hpux' or 'sun'\"",
")"
] | https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/tools/gcc.py#L459-L573 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | InputStream.GetC | (*args, **kwargs) | return _core_.InputStream_GetC(*args, **kwargs) | GetC(self) -> char | GetC(self) -> char | [
"GetC",
"(",
"self",
")",
"-",
">",
"char"
] | def GetC(*args, **kwargs):
"""GetC(self) -> char"""
return _core_.InputStream_GetC(*args, **kwargs) | [
"def",
"GetC",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"InputStream_GetC",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L2194-L2196 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py | python | PthDistributions.add | (self, dist) | Add `dist` to the distribution map | Add `dist` to the distribution map | [
"Add",
"dist",
"to",
"the",
"distribution",
"map"
] | def add(self, dist):
"""Add `dist` to the distribution map"""
new_path = (
dist.location not in self.paths and (
dist.location not in self.sitedirs or
# account for '.' being in PYTHONPATH
dist.location == os.getcwd()
)
)
if new_path:
self.paths.append(dist.location)
self.dirty = True
Environment.add(self, dist) | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"new_path",
"=",
"(",
"dist",
".",
"location",
"not",
"in",
"self",
".",
"paths",
"and",
"(",
"dist",
".",
"location",
"not",
"in",
"self",
".",
"sitedirs",
"or",
"# account for '.' being in PYTHONPATH",
"dist",
".",
"location",
"==",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"if",
"new_path",
":",
"self",
".",
"paths",
".",
"append",
"(",
"dist",
".",
"location",
")",
"self",
".",
"dirty",
"=",
"True",
"Environment",
".",
"add",
"(",
"self",
",",
"dist",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py#L1659-L1671 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | GCDC.SetGraphicsContext | (*args, **kwargs) | return _gdi_.GCDC_SetGraphicsContext(*args, **kwargs) | SetGraphicsContext(self, GraphicsContext ctx) | SetGraphicsContext(self, GraphicsContext ctx) | [
"SetGraphicsContext",
"(",
"self",
"GraphicsContext",
"ctx",
")"
] | def SetGraphicsContext(*args, **kwargs):
"""SetGraphicsContext(self, GraphicsContext ctx)"""
return _gdi_.GCDC_SetGraphicsContext(*args, **kwargs) | [
"def",
"SetGraphicsContext",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GCDC_SetGraphicsContext",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L6696-L6698 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py | python | cast | (x, dtype) | return math_ops.cast(x, dtype) | Casts a tensor to a different dtype and returns it.
You can cast a Keras variable but it still returns a Keras tensor.
Arguments:
x: Keras tensor (or variable).
dtype: String, either (`'float16'`, `'float32'`, or `'float64'`).
Returns:
Keras tensor with dtype `dtype`.
Examples:
Cast a float32 variable to a float64 tensor
```python
>>> import tensorflow as tf
>>> from tensorflow.keras import backend as K
>>> input = K.ones(shape=(1,3))
>>> print(input)
>>> cast_input = K.cast(input, dtype='float64')
>>> print(cast_input)
<tf.Variable 'Variable:0' shape=(1, 3) dtype=float32,
numpy=array([[1., 1., 1.]], dtype=float32)>
tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float64)
``` | Casts a tensor to a different dtype and returns it. | [
"Casts",
"a",
"tensor",
"to",
"a",
"different",
"dtype",
"and",
"returns",
"it",
"."
] | def cast(x, dtype):
"""Casts a tensor to a different dtype and returns it.
You can cast a Keras variable but it still returns a Keras tensor.
Arguments:
x: Keras tensor (or variable).
dtype: String, either (`'float16'`, `'float32'`, or `'float64'`).
Returns:
Keras tensor with dtype `dtype`.
Examples:
Cast a float32 variable to a float64 tensor
```python
>>> import tensorflow as tf
>>> from tensorflow.keras import backend as K
>>> input = K.ones(shape=(1,3))
>>> print(input)
>>> cast_input = K.cast(input, dtype='float64')
>>> print(cast_input)
<tf.Variable 'Variable:0' shape=(1, 3) dtype=float32,
numpy=array([[1., 1., 1.]], dtype=float32)>
tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float64)
```
"""
return math_ops.cast(x, dtype) | [
"def",
"cast",
"(",
"x",
",",
"dtype",
")",
":",
"return",
"math_ops",
".",
"cast",
"(",
"x",
",",
"dtype",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L1537-L1565 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/interpolate/fitpack2.py | python | _BivariateSplineBase.get_coeffs | (self) | return self.tck[2] | Return spline coefficients. | Return spline coefficients. | [
"Return",
"spline",
"coefficients",
"."
] | def get_coeffs(self):
""" Return spline coefficients."""
return self.tck[2] | [
"def",
"get_coeffs",
"(",
"self",
")",
":",
"return",
"self",
".",
"tck",
"[",
"2",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/interpolate/fitpack2.py#L787-L789 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/abinsdata.py | python | AbinsData.from_calculation_data | (filename: str,
ab_initio_program: str) | return data | Get AbinsData from ab initio calculation output file.
:param filename: Path to vibration/phonon data file
:param ab_initio_program: Program which generated data file; this should be a key in AbinsData.ab_initio_loaders | Get AbinsData from ab initio calculation output file. | [
"Get",
"AbinsData",
"from",
"ab",
"initio",
"calculation",
"output",
"file",
"."
] | def from_calculation_data(filename: str,
ab_initio_program: str) -> 'AbinsData':
"""
Get AbinsData from ab initio calculation output file.
:param filename: Path to vibration/phonon data file
:param ab_initio_program: Program which generated data file; this should be a key in AbinsData.ab_initio_loaders
"""
from abins.input import all_loaders # Defer import to avoid loops when abins.__init__ imports AbinsData
if ab_initio_program.upper() not in all_loaders:
raise ValueError("No loader available for {}: unknown program. "
"supported loaders: {}".format(ab_initio_program.upper(),
' '.join(all_loaders.keys())))
loader = all_loaders[ab_initio_program.upper()](input_ab_initio_filename=filename)
data = loader.get_formatted_data()
return data | [
"def",
"from_calculation_data",
"(",
"filename",
":",
"str",
",",
"ab_initio_program",
":",
"str",
")",
"->",
"'AbinsData'",
":",
"from",
"abins",
".",
"input",
"import",
"all_loaders",
"# Defer import to avoid loops when abins.__init__ imports AbinsData",
"if",
"ab_initio_program",
".",
"upper",
"(",
")",
"not",
"in",
"all_loaders",
":",
"raise",
"ValueError",
"(",
"\"No loader available for {}: unknown program. \"",
"\"supported loaders: {}\"",
".",
"format",
"(",
"ab_initio_program",
".",
"upper",
"(",
")",
",",
"' '",
".",
"join",
"(",
"all_loaders",
".",
"keys",
"(",
")",
")",
")",
")",
"loader",
"=",
"all_loaders",
"[",
"ab_initio_program",
".",
"upper",
"(",
")",
"]",
"(",
"input_ab_initio_filename",
"=",
"filename",
")",
"data",
"=",
"loader",
".",
"get_formatted_data",
"(",
")",
"return",
"data"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/abinsdata.py#L34-L50 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.semantic_parent | (self) | return self._semantic_parent | Return the semantic parent for this cursor. | Return the semantic parent for this cursor. | [
"Return",
"the",
"semantic",
"parent",
"for",
"this",
"cursor",
"."
] | def semantic_parent(self):
"""Return the semantic parent for this cursor."""
if not hasattr(self, '_semantic_parent'):
self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
return self._semantic_parent | [
"def",
"semantic_parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_semantic_parent'",
")",
":",
"self",
".",
"_semantic_parent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorSemanticParent",
"(",
"self",
")",
"return",
"self",
".",
"_semantic_parent"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1733-L1738 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/nodes.py | python | Node.set_ctx | (self, ctx) | return self | Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context. | Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context. | [
"Reset",
"the",
"context",
"of",
"a",
"node",
"and",
"all",
"child",
"nodes",
".",
"Per",
"default",
"the",
"parser",
"will",
"all",
"generate",
"nodes",
"that",
"have",
"a",
"load",
"context",
"as",
"it",
"s",
"the",
"most",
"common",
"one",
".",
"This",
"method",
"is",
"used",
"in",
"the",
"parser",
"to",
"set",
"assignment",
"targets",
"and",
"other",
"nodes",
"to",
"a",
"store",
"context",
"."
] | def set_ctx(self, ctx):
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self | [
"def",
"set_ctx",
"(",
"self",
",",
"ctx",
")",
":",
"todo",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"todo",
":",
"node",
"=",
"todo",
".",
"popleft",
"(",
")",
"if",
"'ctx'",
"in",
"node",
".",
"fields",
":",
"node",
".",
"ctx",
"=",
"ctx",
"todo",
".",
"extend",
"(",
"node",
".",
"iter_child_nodes",
"(",
")",
")",
"return",
"self"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/nodes.py#L194-L206 | |
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/build/lib.linux-x86_64-2.7/mxnet/initializer.py | python | Initializer._init_weight | (self, name, arr) | Abstruct method to Initialize weight | Abstruct method to Initialize weight | [
"Abstruct",
"method",
"to",
"Initialize",
"weight"
] | def _init_weight(self, name, arr):
"""Abstruct method to Initialize weight"""
raise NotImplementedError("Must override it") | [
"def",
"_init_weight",
"(",
"self",
",",
"name",
",",
"arr",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Must override it\"",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/initializer.py#L74-L76 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Wrapping/Generators/Python/itk/support/extras.py | python | index | (image_or_filter: "itkt.ImageOrImageSource") | return img.GetLargestPossibleRegion().GetIndex() | Return the index of an image, or of the output image of a filter
This method take care of updating the needed information | Return the index of an image, or of the output image of a filter | [
"Return",
"the",
"index",
"of",
"an",
"image",
"or",
"of",
"the",
"output",
"image",
"of",
"a",
"filter"
] | def index(image_or_filter: "itkt.ImageOrImageSource") -> Sequence[int]:
"""Return the index of an image, or of the output image of a filter
This method take care of updating the needed information
"""
import itk
# we don't need the entire output, only its size
image_or_filter.UpdateOutputInformation()
img = itk.output(image_or_filter)
return img.GetLargestPossibleRegion().GetIndex() | [
"def",
"index",
"(",
"image_or_filter",
":",
"\"itkt.ImageOrImageSource\"",
")",
"->",
"Sequence",
"[",
"int",
"]",
":",
"import",
"itk",
"# we don't need the entire output, only its size",
"image_or_filter",
".",
"UpdateOutputInformation",
"(",
")",
"img",
"=",
"itk",
".",
"output",
"(",
"image_or_filter",
")",
"return",
"img",
".",
"GetLargestPossibleRegion",
"(",
")",
".",
"GetIndex",
"(",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Wrapping/Generators/Python/itk/support/extras.py#L227-L237 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/Paste/paste/util/datetimeutil.py | python | normalize_timedelta | (val) | return "%d.%02d" % (hr, mn * 100/60) | produces a normalized string value of the timedelta
This module returns a normalized time span value consisting of the
number of hours in fractional form. For example '1h 15min' is
formatted as 01.25. | produces a normalized string value of the timedelta | [
"produces",
"a",
"normalized",
"string",
"value",
"of",
"the",
"timedelta"
] | def normalize_timedelta(val):
"""
produces a normalized string value of the timedelta
This module returns a normalized time span value consisting of the
number of hours in fractional form. For example '1h 15min' is
formatted as 01.25.
"""
if type(val) == str:
val = parse_timedelta(val)
if not val:
return ''
hr = val.seconds/3600
mn = (val.seconds % 3600)/60
return "%d.%02d" % (hr, mn * 100/60) | [
"def",
"normalize_timedelta",
"(",
"val",
")",
":",
"if",
"type",
"(",
"val",
")",
"==",
"str",
":",
"val",
"=",
"parse_timedelta",
"(",
"val",
")",
"if",
"not",
"val",
":",
"return",
"''",
"hr",
"=",
"val",
".",
"seconds",
"/",
"3600",
"mn",
"=",
"(",
"val",
".",
"seconds",
"%",
"3600",
")",
"/",
"60",
"return",
"\"%d.%02d\"",
"%",
"(",
"hr",
",",
"mn",
"*",
"100",
"/",
"60",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/util/datetimeutil.py#L99-L113 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/urllib/request.py | python | URLopener.retrieve | (self, url, filename=None, reporthook=None, data=None) | return result | retrieve(url) returns (filename, headers) for a local object
or (tempfilename, headers) for a remote object. | retrieve(url) returns (filename, headers) for a local object
or (tempfilename, headers) for a remote object. | [
"retrieve",
"(",
"url",
")",
"returns",
"(",
"filename",
"headers",
")",
"for",
"a",
"local",
"object",
"or",
"(",
"tempfilename",
"headers",
")",
"for",
"a",
"remote",
"object",
"."
] | def retrieve(self, url, filename=None, reporthook=None, data=None):
"""retrieve(url) returns (filename, headers) for a local object
or (tempfilename, headers) for a remote object."""
url = unwrap(_to_bytes(url))
if self.tempcache and url in self.tempcache:
return self.tempcache[url]
type, url1 = _splittype(url)
if filename is None and (not type or type == 'file'):
try:
fp = self.open_local_file(url1)
hdrs = fp.info()
fp.close()
return url2pathname(_splithost(url1)[1]), hdrs
except OSError:
pass
fp = self.open(url, data)
try:
headers = fp.info()
if filename:
tfp = open(filename, 'wb')
else:
garbage, path = _splittype(url)
garbage, path = _splithost(path or "")
path, garbage = _splitquery(path or "")
path, garbage = _splitattr(path or "")
suffix = os.path.splitext(path)[1]
(fd, filename) = tempfile.mkstemp(suffix)
self.__tempfiles.append(filename)
tfp = os.fdopen(fd, 'wb')
try:
result = filename, headers
if self.tempcache is not None:
self.tempcache[url] = result
bs = 1024*8
size = -1
read = 0
blocknum = 0
if "content-length" in headers:
size = int(headers["Content-Length"])
if reporthook:
reporthook(blocknum, bs, size)
while 1:
block = fp.read(bs)
if not block:
break
read += len(block)
tfp.write(block)
blocknum += 1
if reporthook:
reporthook(blocknum, bs, size)
finally:
tfp.close()
finally:
fp.close()
# raise exception if actual size does not match content-length header
if size >= 0 and read < size:
raise ContentTooShortError(
"retrieval incomplete: got only %i out of %i bytes"
% (read, size), result)
return result | [
"def",
"retrieve",
"(",
"self",
",",
"url",
",",
"filename",
"=",
"None",
",",
"reporthook",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"url",
"=",
"unwrap",
"(",
"_to_bytes",
"(",
"url",
")",
")",
"if",
"self",
".",
"tempcache",
"and",
"url",
"in",
"self",
".",
"tempcache",
":",
"return",
"self",
".",
"tempcache",
"[",
"url",
"]",
"type",
",",
"url1",
"=",
"_splittype",
"(",
"url",
")",
"if",
"filename",
"is",
"None",
"and",
"(",
"not",
"type",
"or",
"type",
"==",
"'file'",
")",
":",
"try",
":",
"fp",
"=",
"self",
".",
"open_local_file",
"(",
"url1",
")",
"hdrs",
"=",
"fp",
".",
"info",
"(",
")",
"fp",
".",
"close",
"(",
")",
"return",
"url2pathname",
"(",
"_splithost",
"(",
"url1",
")",
"[",
"1",
"]",
")",
",",
"hdrs",
"except",
"OSError",
":",
"pass",
"fp",
"=",
"self",
".",
"open",
"(",
"url",
",",
"data",
")",
"try",
":",
"headers",
"=",
"fp",
".",
"info",
"(",
")",
"if",
"filename",
":",
"tfp",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"else",
":",
"garbage",
",",
"path",
"=",
"_splittype",
"(",
"url",
")",
"garbage",
",",
"path",
"=",
"_splithost",
"(",
"path",
"or",
"\"\"",
")",
"path",
",",
"garbage",
"=",
"_splitquery",
"(",
"path",
"or",
"\"\"",
")",
"path",
",",
"garbage",
"=",
"_splitattr",
"(",
"path",
"or",
"\"\"",
")",
"suffix",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"(",
"fd",
",",
"filename",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
")",
"self",
".",
"__tempfiles",
".",
"append",
"(",
"filename",
")",
"tfp",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'wb'",
")",
"try",
":",
"result",
"=",
"filename",
",",
"headers",
"if",
"self",
".",
"tempcache",
"is",
"not",
"None",
":",
"self",
".",
"tempcache",
"[",
"url",
"]",
"=",
"result",
"bs",
"=",
"1024",
"*",
"8",
"size",
"=",
"-",
"1",
"read",
"=",
"0",
"blocknum",
"=",
"0",
"if",
"\"content-length\"",
"in",
"headers",
":",
"size",
"=",
"int",
"(",
"headers",
"[",
"\"Content-Length\"",
"]",
")",
"if",
"reporthook",
":",
"reporthook",
"(",
"blocknum",
",",
"bs",
",",
"size",
")",
"while",
"1",
":",
"block",
"=",
"fp",
".",
"read",
"(",
"bs",
")",
"if",
"not",
"block",
":",
"break",
"read",
"+=",
"len",
"(",
"block",
")",
"tfp",
".",
"write",
"(",
"block",
")",
"blocknum",
"+=",
"1",
"if",
"reporthook",
":",
"reporthook",
"(",
"blocknum",
",",
"bs",
",",
"size",
")",
"finally",
":",
"tfp",
".",
"close",
"(",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")",
"# raise exception if actual size does not match content-length header",
"if",
"size",
">=",
"0",
"and",
"read",
"<",
"size",
":",
"raise",
"ContentTooShortError",
"(",
"\"retrieval incomplete: got only %i out of %i bytes\"",
"%",
"(",
"read",
",",
"size",
")",
",",
"result",
")",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/urllib/request.py#L1805-L1866 | |
llvm-mirror/libcxx | 78d6a7767ed57b50122a161b91f59f19c9bd0d19 | utils/libcxx/sym_check/extract.py | python | NMExtractor._want_sym | (sym) | return (sym['type'] not in bad_types
and sym['name'] not in ['__bss_start', '_end', '_edata']) | Check that s is a valid symbol that we want to keep. | Check that s is a valid symbol that we want to keep. | [
"Check",
"that",
"s",
"is",
"a",
"valid",
"symbol",
"that",
"we",
"want",
"to",
"keep",
"."
] | def _want_sym(sym):
"""
Check that s is a valid symbol that we want to keep.
"""
if sym is None or len(sym) < 2:
return False
if sym['name'] in extract_ignore_names:
return False
bad_types = ['t', 'b', 'r', 'd', 'w']
return (sym['type'] not in bad_types
and sym['name'] not in ['__bss_start', '_end', '_edata']) | [
"def",
"_want_sym",
"(",
"sym",
")",
":",
"if",
"sym",
"is",
"None",
"or",
"len",
"(",
"sym",
")",
"<",
"2",
":",
"return",
"False",
"if",
"sym",
"[",
"'name'",
"]",
"in",
"extract_ignore_names",
":",
"return",
"False",
"bad_types",
"=",
"[",
"'t'",
",",
"'b'",
",",
"'r'",
",",
"'d'",
",",
"'w'",
"]",
"return",
"(",
"sym",
"[",
"'type'",
"]",
"not",
"in",
"bad_types",
"and",
"sym",
"[",
"'name'",
"]",
"not",
"in",
"[",
"'__bss_start'",
",",
"'_end'",
",",
"'_edata'",
"]",
")"
] | https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/utils/libcxx/sym_check/extract.py#L84-L94 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | AuiManager.AddPane | (*args, **kwargs) | return _aui.AuiManager_AddPane(*args, **kwargs) | AddPane(self, Window window, AuiPaneInfo paneInfo, Point dropPos) -> bool | AddPane(self, Window window, AuiPaneInfo paneInfo, Point dropPos) -> bool | [
"AddPane",
"(",
"self",
"Window",
"window",
"AuiPaneInfo",
"paneInfo",
"Point",
"dropPos",
")",
"-",
">",
"bool"
] | def AddPane(*args, **kwargs):
"""AddPane(self, Window window, AuiPaneInfo paneInfo, Point dropPos) -> bool"""
return _aui.AuiManager_AddPane(*args, **kwargs) | [
"def",
"AddPane",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiManager_AddPane",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L643-L645 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/dos/load_castep.py | python | parse_castep_file | (file_name, ir_or_raman) | return file_data | Read frequencies from a <>.castep file
@param file_name - file path of the file to read
@return the frequencies, infra red and raman intensities and weights of frequency blocks | Read frequencies from a <>.castep file | [
"Read",
"frequencies",
"from",
"a",
"<",
">",
".",
"castep",
"file"
] | def parse_castep_file(file_name, ir_or_raman):
"""
Read frequencies from a <>.castep file
@param file_name - file path of the file to read
@return the frequencies, infra red and raman intensities and weights of frequency blocks
"""
file_data = {}
# Get Regex strings from load_helper
header_regex = re.compile(load_helper.CASTEP_HEADER_REGEX)
data_regex = re.compile(load_helper.CASTEP_DATA_REGEX)
bond_regex = re.compile(load_helper.CASTEP_BOND_REGEX)
block_count = 0
frequencies, ir_intensities, raman_intensities, weights, q_vectors, bonds = [], [], [], [], [], []
data_lists = (frequencies, ir_intensities, raman_intensities)
with open(file_name, 'rU') as f_handle:
file_data.update(_parse_castep_file_header(f_handle))
while True:
line = f_handle.readline()
# Check we've reached the end of file
if not line:
break
# Check if we've found a block of frequencies
header_match = header_regex.match(line)
if header_match:
block_count += 1
weight, q_vector = load_helper._parse_block_header(header_match, block_count)
weights.append(weight)
q_vectors.append(q_vector)
# Move file pointer forward to start of intensity data
_find_castep_freq_block(f_handle, data_regex)
# Parse block of frequencies
for line_data in _parse_castep_freq_block(f_handle, file_data['num_branches'], ir_or_raman):
for data_list, item in zip(data_lists, line_data):
data_list.append(item)
# Check if we've found a bond
bond_match = bond_regex.match(line)
if bond_match:
bonds.append(_parse_castep_bond(bond_match))
frequencies = np.asarray(frequencies)
ir_intensities = np.asarray(ir_intensities)
raman_intensities = np.asarray(raman_intensities)
warray = np.repeat(weights, file_data['num_branches'])
file_data.update({
'frequencies': frequencies,
'ir_intensities': ir_intensities,
'raman_intensities': raman_intensities,
'weights': warray,
'q_vectors':q_vectors
})
if len(bonds) > 0:
file_data['bonds'] = bonds
return file_data | [
"def",
"parse_castep_file",
"(",
"file_name",
",",
"ir_or_raman",
")",
":",
"file_data",
"=",
"{",
"}",
"# Get Regex strings from load_helper",
"header_regex",
"=",
"re",
".",
"compile",
"(",
"load_helper",
".",
"CASTEP_HEADER_REGEX",
")",
"data_regex",
"=",
"re",
".",
"compile",
"(",
"load_helper",
".",
"CASTEP_DATA_REGEX",
")",
"bond_regex",
"=",
"re",
".",
"compile",
"(",
"load_helper",
".",
"CASTEP_BOND_REGEX",
")",
"block_count",
"=",
"0",
"frequencies",
",",
"ir_intensities",
",",
"raman_intensities",
",",
"weights",
",",
"q_vectors",
",",
"bonds",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"data_lists",
"=",
"(",
"frequencies",
",",
"ir_intensities",
",",
"raman_intensities",
")",
"with",
"open",
"(",
"file_name",
",",
"'rU'",
")",
"as",
"f_handle",
":",
"file_data",
".",
"update",
"(",
"_parse_castep_file_header",
"(",
"f_handle",
")",
")",
"while",
"True",
":",
"line",
"=",
"f_handle",
".",
"readline",
"(",
")",
"# Check we've reached the end of file",
"if",
"not",
"line",
":",
"break",
"# Check if we've found a block of frequencies",
"header_match",
"=",
"header_regex",
".",
"match",
"(",
"line",
")",
"if",
"header_match",
":",
"block_count",
"+=",
"1",
"weight",
",",
"q_vector",
"=",
"load_helper",
".",
"_parse_block_header",
"(",
"header_match",
",",
"block_count",
")",
"weights",
".",
"append",
"(",
"weight",
")",
"q_vectors",
".",
"append",
"(",
"q_vector",
")",
"# Move file pointer forward to start of intensity data",
"_find_castep_freq_block",
"(",
"f_handle",
",",
"data_regex",
")",
"# Parse block of frequencies",
"for",
"line_data",
"in",
"_parse_castep_freq_block",
"(",
"f_handle",
",",
"file_data",
"[",
"'num_branches'",
"]",
",",
"ir_or_raman",
")",
":",
"for",
"data_list",
",",
"item",
"in",
"zip",
"(",
"data_lists",
",",
"line_data",
")",
":",
"data_list",
".",
"append",
"(",
"item",
")",
"# Check if we've found a bond",
"bond_match",
"=",
"bond_regex",
".",
"match",
"(",
"line",
")",
"if",
"bond_match",
":",
"bonds",
".",
"append",
"(",
"_parse_castep_bond",
"(",
"bond_match",
")",
")",
"frequencies",
"=",
"np",
".",
"asarray",
"(",
"frequencies",
")",
"ir_intensities",
"=",
"np",
".",
"asarray",
"(",
"ir_intensities",
")",
"raman_intensities",
"=",
"np",
".",
"asarray",
"(",
"raman_intensities",
")",
"warray",
"=",
"np",
".",
"repeat",
"(",
"weights",
",",
"file_data",
"[",
"'num_branches'",
"]",
")",
"file_data",
".",
"update",
"(",
"{",
"'frequencies'",
":",
"frequencies",
",",
"'ir_intensities'",
":",
"ir_intensities",
",",
"'raman_intensities'",
":",
"raman_intensities",
",",
"'weights'",
":",
"warray",
",",
"'q_vectors'",
":",
"q_vectors",
"}",
")",
"if",
"len",
"(",
"bonds",
")",
">",
"0",
":",
"file_data",
"[",
"'bonds'",
"]",
"=",
"bonds",
"return",
"file_data"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/dos/load_castep.py#L14-L78 | |
ZhanLang/jcfs | cddcb29290e6eada908333e6c8b2d9dbc17bb7bd | code/scintilla/scripts/FileGenerator.py | python | Regenerate | (filename, commentPrefix, *lists) | Regenerate the given file. | Regenerate the given file. | [
"Regenerate",
"the",
"given",
"file",
"."
] | def Regenerate(filename, commentPrefix, *lists):
"""Regenerate the given file.
"""
Generate(filename, filename, commentPrefix, *lists) | [
"def",
"Regenerate",
"(",
"filename",
",",
"commentPrefix",
",",
"*",
"lists",
")",
":",
"Generate",
"(",
"filename",
",",
"filename",
",",
"commentPrefix",
",",
"*",
"lists",
")"
] | https://github.com/ZhanLang/jcfs/blob/cddcb29290e6eada908333e6c8b2d9dbc17bb7bd/code/scintilla/scripts/FileGenerator.py#L135-L138 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/estimator/export/export.py | python | build_parsing_serving_input_receiver_fn | (feature_spec,
default_batch_size=None) | return serving_input_receiver_fn | Build a serving_input_receiver_fn expecting fed tf.Examples.
Creates a serving_input_receiver_fn that expects a serialized tf.Example fed
into a string placeholder. The function parses the tf.Example according to
the provided feature_spec, and returns all parsed Tensors as features.
Args:
feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
A serving_input_receiver_fn suitable for use in serving. | Build a serving_input_receiver_fn expecting fed tf.Examples. | [
"Build",
"a",
"serving_input_receiver_fn",
"expecting",
"fed",
"tf",
".",
"Examples",
"."
] | def build_parsing_serving_input_receiver_fn(feature_spec,
default_batch_size=None):
"""Build a serving_input_receiver_fn expecting fed tf.Examples.
Creates a serving_input_receiver_fn that expects a serialized tf.Example fed
into a string placeholder. The function parses the tf.Example according to
the provided feature_spec, and returns all parsed Tensors as features.
Args:
feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`.
default_batch_size: the number of query examples expected per batch.
Leave unset for variable batch size (recommended).
Returns:
A serving_input_receiver_fn suitable for use in serving.
"""
def serving_input_receiver_fn():
"""An input_fn that expects a serialized tf.Example."""
serialized_tf_example = array_ops.placeholder(dtype=dtypes.string,
shape=[default_batch_size],
name='input_example_tensor')
receiver_tensors = {'examples': serialized_tf_example}
features = parsing_ops.parse_example(serialized_tf_example, feature_spec)
return ServingInputReceiver(features, receiver_tensors)
return serving_input_receiver_fn | [
"def",
"build_parsing_serving_input_receiver_fn",
"(",
"feature_spec",
",",
"default_batch_size",
"=",
"None",
")",
":",
"def",
"serving_input_receiver_fn",
"(",
")",
":",
"\"\"\"An input_fn that expects a serialized tf.Example.\"\"\"",
"serialized_tf_example",
"=",
"array_ops",
".",
"placeholder",
"(",
"dtype",
"=",
"dtypes",
".",
"string",
",",
"shape",
"=",
"[",
"default_batch_size",
"]",
",",
"name",
"=",
"'input_example_tensor'",
")",
"receiver_tensors",
"=",
"{",
"'examples'",
":",
"serialized_tf_example",
"}",
"features",
"=",
"parsing_ops",
".",
"parse_example",
"(",
"serialized_tf_example",
",",
"feature_spec",
")",
"return",
"ServingInputReceiver",
"(",
"features",
",",
"receiver_tensors",
")",
"return",
"serving_input_receiver_fn"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/estimator/export/export.py#L84-L109 | |
wujian16/Cornell-MOE | df299d1be882d2af9796d7a68b3f9505cac7a53e | moe/optimal_learning/python/interfaces/covariance_interface.py | python | CovarianceInterface.covariance | (self, point_one, point_two) | r"""Compute the covariance function of two points, cov(``point_one``, ``point_two``).
.. Note:: comments are copied from the matching method comments of CovarianceInterface in gpp_covariance.hpp
and comments are copied to the matching method comments of
:mod:`moe.optimal_learning.python.python_version.covariance.SquareExponential`.
The covariance function is guaranteed to be symmetric by definition: ``covariance(x, y) = covariance(y, x)``.
This function is also positive definite by definition.
:param point_one: first input, the point ``x``
:type point_one: array of float64 with shape (dim)
:param point_two: second input, the point ``y``
:type point_two: array of float64 with shape (dim)
:return: value of covariance between the input points
:rtype: float64 | r"""Compute the covariance function of two points, cov(``point_one``, ``point_two``). | [
"r",
"Compute",
"the",
"covariance",
"function",
"of",
"two",
"points",
"cov",
"(",
"point_one",
"point_two",
")",
"."
] | def covariance(self, point_one, point_two):
r"""Compute the covariance function of two points, cov(``point_one``, ``point_two``).
.. Note:: comments are copied from the matching method comments of CovarianceInterface in gpp_covariance.hpp
and comments are copied to the matching method comments of
:mod:`moe.optimal_learning.python.python_version.covariance.SquareExponential`.
The covariance function is guaranteed to be symmetric by definition: ``covariance(x, y) = covariance(y, x)``.
This function is also positive definite by definition.
:param point_one: first input, the point ``x``
:type point_one: array of float64 with shape (dim)
:param point_two: second input, the point ``y``
:type point_two: array of float64 with shape (dim)
:return: value of covariance between the input points
:rtype: float64
"""
pass | [
"def",
"covariance",
"(",
"self",
",",
"point_one",
",",
"point_two",
")",
":",
"pass"
] | https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/interfaces/covariance_interface.py#L74-L92 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | _log10_lb | (c, correction = {
'1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
'6': 23, '7': 16, '8': 10, '9': 5}) | return 100*len(str_c) - correction[str_c[0]] | Compute a lower bound for 100*log10(c) for a positive integer c. | Compute a lower bound for 100*log10(c) for a positive integer c. | [
"Compute",
"a",
"lower",
"bound",
"for",
"100",
"*",
"log10",
"(",
"c",
")",
"for",
"a",
"positive",
"integer",
"c",
"."
] | def _log10_lb(c, correction = {
'1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
'6': 23, '7': 16, '8': 10, '9': 5}):
"""Compute a lower bound for 100*log10(c) for a positive integer c."""
if c <= 0:
raise ValueError("The argument to _log10_lb should be nonnegative.")
str_c = str(c)
return 100*len(str_c) - correction[str_c[0]] | [
"def",
"_log10_lb",
"(",
"c",
",",
"correction",
"=",
"{",
"'1'",
":",
"100",
",",
"'2'",
":",
"70",
",",
"'3'",
":",
"53",
",",
"'4'",
":",
"40",
",",
"'5'",
":",
"31",
",",
"'6'",
":",
"23",
",",
"'7'",
":",
"16",
",",
"'8'",
":",
"10",
",",
"'9'",
":",
"5",
"}",
")",
":",
"if",
"c",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"The argument to _log10_lb should be nonnegative.\"",
")",
"str_c",
"=",
"str",
"(",
"c",
")",
"return",
"100",
"*",
"len",
"(",
"str_c",
")",
"-",
"correction",
"[",
"str_c",
"[",
"0",
"]",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L5824-L5831 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | _ProxyFile.close | (self) | Close the file. | Close the file. | [
"Close",
"the",
"file",
"."
] | def close(self):
"""Close the file."""
if hasattr(self, '_file'):
if hasattr(self._file, 'close'):
self._file.close()
del self._file | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_file'",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_file",
",",
"'close'",
")",
":",
"self",
".",
"_file",
".",
"close",
"(",
")",
"del",
"self",
".",
"_file"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L1905-L1910 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | RobotModel.getTotalInertia | (self) | return _robotsim.RobotModel_getTotalInertia(self) | r"""
Computes the 3x3 total inertia matrix of the robot. | r"""
Computes the 3x3 total inertia matrix of the robot. | [
"r",
"Computes",
"the",
"3x3",
"total",
"inertia",
"matrix",
"of",
"the",
"robot",
"."
] | def getTotalInertia(self) ->None:
r"""
Computes the 3x3 total inertia matrix of the robot.
"""
return _robotsim.RobotModel_getTotalInertia(self) | [
"def",
"getTotalInertia",
"(",
"self",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"RobotModel_getTotalInertia",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L4934-L4939 | |
RobotLocomotion/drake | 0e18a34604c45ed65bc9018a54f7610f91cdad5b | examples/manipulation_station/end_effector_teleop_sliders.py | python | EndEffectorTeleop.SetRPY | (self, rpy) | @param rpy is a RollPitchYaw object | [] | def SetRPY(self, rpy):
"""
@param rpy is a RollPitchYaw object
"""
self.roll.set(rpy.roll_angle())
if not self.planar:
self.pitch.set(rpy.pitch_angle())
self.yaw.set(rpy.yaw_angle()) | [
"def",
"SetRPY",
"(",
"self",
",",
"rpy",
")",
":",
"self",
".",
"roll",
".",
"set",
"(",
"rpy",
".",
"roll_angle",
"(",
")",
")",
"if",
"not",
"self",
".",
"planar",
":",
"self",
".",
"pitch",
".",
"set",
"(",
"rpy",
".",
"pitch_angle",
"(",
")",
")",
"self",
".",
"yaw",
".",
"set",
"(",
"rpy",
".",
"yaw_angle",
"(",
")",
")"
] | https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/examples/manipulation_station/end_effector_teleop_sliders.py#L152-L159 | |||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/webkit.py | python | WebKitNewWindowEvent.SetTargetName | (*args, **kwargs) | return _webkit.WebKitNewWindowEvent_SetTargetName(*args, **kwargs) | SetTargetName(self, String name) | SetTargetName(self, String name) | [
"SetTargetName",
"(",
"self",
"String",
"name",
")"
] | def SetTargetName(*args, **kwargs):
"""SetTargetName(self, String name)"""
return _webkit.WebKitNewWindowEvent_SetTargetName(*args, **kwargs) | [
"def",
"SetTargetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_webkit",
".",
"WebKitNewWindowEvent_SetTargetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/webkit.py#L274-L276 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Node/FS.py | python | File._add_strings_to_dependency_map | (self, dmap) | return dmap | In the case comparing node objects isn't sufficient, we'll add the strings for the nodes to the dependency map
:return: | In the case comparing node objects isn't sufficient, we'll add the strings for the nodes to the dependency map
:return: | [
"In",
"the",
"case",
"comparing",
"node",
"objects",
"isn",
"t",
"sufficient",
"we",
"ll",
"add",
"the",
"strings",
"for",
"the",
"nodes",
"to",
"the",
"dependency",
"map",
":",
"return",
":"
] | def _add_strings_to_dependency_map(self, dmap):
"""
In the case comparing node objects isn't sufficient, we'll add the strings for the nodes to the dependency map
:return:
"""
first_string = str(next(iter(dmap)))
# print("DMAP:%s"%id(dmap))
if first_string not in dmap:
string_dict = {str(child): signature for child, signature in dmap.items()}
dmap.update(string_dict)
return dmap | [
"def",
"_add_strings_to_dependency_map",
"(",
"self",
",",
"dmap",
")",
":",
"first_string",
"=",
"str",
"(",
"next",
"(",
"iter",
"(",
"dmap",
")",
")",
")",
"# print(\"DMAP:%s\"%id(dmap))",
"if",
"first_string",
"not",
"in",
"dmap",
":",
"string_dict",
"=",
"{",
"str",
"(",
"child",
")",
":",
"signature",
"for",
"child",
",",
"signature",
"in",
"dmap",
".",
"items",
"(",
")",
"}",
"dmap",
".",
"update",
"(",
"string_dict",
")",
"return",
"dmap"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L3326-L3338 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/SampleData/SampleData.py | python | SampleDataLogic.registerCustomSampleDataSource | (category='Custom',
sampleName=None, uris=None, fileNames=None, nodeNames=None,
customDownloader=None, thumbnailFileName=None,
loadFileType='VolumeFile', loadFiles=None, loadFileProperties={},
checksums=None) | Adds custom data sets to SampleData.
:param category: Section title of data set in SampleData module GUI.
:param sampleName: Displayed name of data set in SampleData module GUI.
:param thumbnailFileName: Displayed thumbnail of data set in SampleData module GUI,
:param uris: Download URL(s).
:param fileNames: File name(s) that will be loaded.
:param nodeNames: Node name(s) in the scene.
:param customDownloader: Custom function for downloading.
:param loadFileType: file format name(s) ('VolumeFile' by default).
:param loadFiles: Boolean indicating if file(s) should be loaded. By default, the function decides.
:param loadFileProperties: custom properties passed to the IO plugin.
:param checksums: Checksum(s) formatted as ``<algo>:<digest>`` to verify the downloaded file(s). For example, ``SHA256:cc211f0dfd9a05ca3841ce1141b292898b2dd2d3f08286affadf823a7e58df93``. | Adds custom data sets to SampleData.
:param category: Section title of data set in SampleData module GUI.
:param sampleName: Displayed name of data set in SampleData module GUI.
:param thumbnailFileName: Displayed thumbnail of data set in SampleData module GUI,
:param uris: Download URL(s).
:param fileNames: File name(s) that will be loaded.
:param nodeNames: Node name(s) in the scene.
:param customDownloader: Custom function for downloading.
:param loadFileType: file format name(s) ('VolumeFile' by default).
:param loadFiles: Boolean indicating if file(s) should be loaded. By default, the function decides.
:param loadFileProperties: custom properties passed to the IO plugin.
:param checksums: Checksum(s) formatted as ``<algo>:<digest>`` to verify the downloaded file(s). For example, ``SHA256:cc211f0dfd9a05ca3841ce1141b292898b2dd2d3f08286affadf823a7e58df93``. | [
"Adds",
"custom",
"data",
"sets",
"to",
"SampleData",
".",
":",
"param",
"category",
":",
"Section",
"title",
"of",
"data",
"set",
"in",
"SampleData",
"module",
"GUI",
".",
":",
"param",
"sampleName",
":",
"Displayed",
"name",
"of",
"data",
"set",
"in",
"SampleData",
"module",
"GUI",
".",
":",
"param",
"thumbnailFileName",
":",
"Displayed",
"thumbnail",
"of",
"data",
"set",
"in",
"SampleData",
"module",
"GUI",
":",
"param",
"uris",
":",
"Download",
"URL",
"(",
"s",
")",
".",
":",
"param",
"fileNames",
":",
"File",
"name",
"(",
"s",
")",
"that",
"will",
"be",
"loaded",
".",
":",
"param",
"nodeNames",
":",
"Node",
"name",
"(",
"s",
")",
"in",
"the",
"scene",
".",
":",
"param",
"customDownloader",
":",
"Custom",
"function",
"for",
"downloading",
".",
":",
"param",
"loadFileType",
":",
"file",
"format",
"name",
"(",
"s",
")",
"(",
"VolumeFile",
"by",
"default",
")",
".",
":",
"param",
"loadFiles",
":",
"Boolean",
"indicating",
"if",
"file",
"(",
"s",
")",
"should",
"be",
"loaded",
".",
"By",
"default",
"the",
"function",
"decides",
".",
":",
"param",
"loadFileProperties",
":",
"custom",
"properties",
"passed",
"to",
"the",
"IO",
"plugin",
".",
":",
"param",
"checksums",
":",
"Checksum",
"(",
"s",
")",
"formatted",
"as",
"<algo",
">",
":",
"<digest",
">",
"to",
"verify",
"the",
"downloaded",
"file",
"(",
"s",
")",
".",
"For",
"example",
"SHA256",
":",
"cc211f0dfd9a05ca3841ce1141b292898b2dd2d3f08286affadf823a7e58df93",
"."
] | def registerCustomSampleDataSource(category='Custom',
sampleName=None, uris=None, fileNames=None, nodeNames=None,
customDownloader=None, thumbnailFileName=None,
loadFileType='VolumeFile', loadFiles=None, loadFileProperties={},
checksums=None):
"""Adds custom data sets to SampleData.
:param category: Section title of data set in SampleData module GUI.
:param sampleName: Displayed name of data set in SampleData module GUI.
:param thumbnailFileName: Displayed thumbnail of data set in SampleData module GUI,
:param uris: Download URL(s).
:param fileNames: File name(s) that will be loaded.
:param nodeNames: Node name(s) in the scene.
:param customDownloader: Custom function for downloading.
:param loadFileType: file format name(s) ('VolumeFile' by default).
:param loadFiles: Boolean indicating if file(s) should be loaded. By default, the function decides.
:param loadFileProperties: custom properties passed to the IO plugin.
:param checksums: Checksum(s) formatted as ``<algo>:<digest>`` to verify the downloaded file(s). For example, ``SHA256:cc211f0dfd9a05ca3841ce1141b292898b2dd2d3f08286affadf823a7e58df93``.
"""
try:
slicer.modules.sampleDataSources
except AttributeError:
slicer.modules.sampleDataSources = {}
if category not in slicer.modules.sampleDataSources:
slicer.modules.sampleDataSources[category] = []
dataSource = SampleDataSource(
sampleName=sampleName,
uris=uris,
fileNames=fileNames,
nodeNames=nodeNames,
thumbnailFileName=thumbnailFileName,
loadFileType=loadFileType,
loadFiles=loadFiles,
loadFileProperties=loadFileProperties,
checksums=checksums,
customDownloader=customDownloader,
)
if SampleDataLogic.isSampleDataSourceRegistered(category, dataSource):
return
slicer.modules.sampleDataSources[category].append(dataSource) | [
"def",
"registerCustomSampleDataSource",
"(",
"category",
"=",
"'Custom'",
",",
"sampleName",
"=",
"None",
",",
"uris",
"=",
"None",
",",
"fileNames",
"=",
"None",
",",
"nodeNames",
"=",
"None",
",",
"customDownloader",
"=",
"None",
",",
"thumbnailFileName",
"=",
"None",
",",
"loadFileType",
"=",
"'VolumeFile'",
",",
"loadFiles",
"=",
"None",
",",
"loadFileProperties",
"=",
"{",
"}",
",",
"checksums",
"=",
"None",
")",
":",
"try",
":",
"slicer",
".",
"modules",
".",
"sampleDataSources",
"except",
"AttributeError",
":",
"slicer",
".",
"modules",
".",
"sampleDataSources",
"=",
"{",
"}",
"if",
"category",
"not",
"in",
"slicer",
".",
"modules",
".",
"sampleDataSources",
":",
"slicer",
".",
"modules",
".",
"sampleDataSources",
"[",
"category",
"]",
"=",
"[",
"]",
"dataSource",
"=",
"SampleDataSource",
"(",
"sampleName",
"=",
"sampleName",
",",
"uris",
"=",
"uris",
",",
"fileNames",
"=",
"fileNames",
",",
"nodeNames",
"=",
"nodeNames",
",",
"thumbnailFileName",
"=",
"thumbnailFileName",
",",
"loadFileType",
"=",
"loadFileType",
",",
"loadFiles",
"=",
"loadFiles",
",",
"loadFileProperties",
"=",
"loadFileProperties",
",",
"checksums",
"=",
"checksums",
",",
"customDownloader",
"=",
"customDownloader",
",",
")",
"if",
"SampleDataLogic",
".",
"isSampleDataSourceRegistered",
"(",
"category",
",",
"dataSource",
")",
":",
"return",
"slicer",
".",
"modules",
".",
"sampleDataSources",
"[",
"category",
"]",
".",
"append",
"(",
"dataSource",
")"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/SampleData/SampleData.py#L412-L455 | ||
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/autograd.py | python | Asin.forward | (self, x) | return singa.Asin(x) | Args:
x (CTensor): Input tensor
Returns:
CTensor, the output | Args:
x (CTensor): Input tensor
Returns:
CTensor, the output | [
"Args",
":",
"x",
"(",
"CTensor",
")",
":",
"Input",
"tensor",
"Returns",
":",
"CTensor",
"the",
"output"
] | def forward(self, x):
"""
Args:
x (CTensor): Input tensor
Returns:
CTensor, the output
"""
if training:
self.input = x
return singa.Asin(x) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"if",
"training",
":",
"self",
".",
"input",
"=",
"x",
"return",
"singa",
".",
"Asin",
"(",
"x",
")"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L2239-L2248 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py | python | shared_embedding_columns | (sparse_id_columns,
dimension,
combiner="mean",
shared_embedding_name=None,
initializer=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None,
max_norm=None,
trainable=True) | Creates a list of `_EmbeddingColumn` sharing the same embedding.
Args:
sparse_id_columns: An iterable of `_SparseColumn`, such as those created by
`sparse_column_with_*` or crossed_column functions. Note that `combiner`
defined in each sparse_id_column is ignored.
dimension: An integer specifying dimension of the embedding.
combiner: A string specifying how to reduce if there are multiple entries in
a single row. Currently "mean", "sqrtn" and "sum" are supported, with
"mean" the default. "sqrtn" often achieves good accuracy, in particular
with bag-of-words columns. Each of this can be thought as example level
normalizations on the column:
* "sum": do not normalize
* "mean": do l1 normalization
* "sqrtn": do l2 normalization
For more information: `tf.embedding_lookup_sparse`.
shared_embedding_name: (Optional). A string specifying the name of shared
embedding weights. This will be needed if you want to reference the shared
embedding separately from the generated `_EmbeddingColumn`.
initializer: A variable initializer function to be used in embedding
variable initialization. If not specified, defaults to
`tf.compat.v1.truncated_normal_initializer` with mean 0.0 and standard
deviation 1/sqrt(sparse_id_columns[0].length).
ckpt_to_load_from: (Optional). String representing checkpoint name/pattern
to restore the column weights. Required if `tensor_name_in_ckpt` is not
None.
tensor_name_in_ckpt: (Optional). Name of the `Tensor` in the provided
checkpoint from which to restore the column weights. Required if
`ckpt_to_load_from` is not None.
max_norm: (Optional). If not None, embedding values are l2-normalized to the
value of max_norm.
trainable: (Optional). Should the embedding be trainable. Default is True
Returns:
A tuple of `_EmbeddingColumn` with shared embedding space.
Raises:
ValueError: if sparse_id_columns is empty, or its elements are not
compatible with each other.
TypeError: if `sparse_id_columns` is not a sequence or is a string. If at
least one element of `sparse_id_columns` is not a `SparseColumn` or a
`WeightedSparseColumn`. | Creates a list of `_EmbeddingColumn` sharing the same embedding. | [
"Creates",
"a",
"list",
"of",
"_EmbeddingColumn",
"sharing",
"the",
"same",
"embedding",
"."
] | def shared_embedding_columns(sparse_id_columns,
dimension,
combiner="mean",
shared_embedding_name=None,
initializer=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None,
max_norm=None,
trainable=True):
"""Creates a list of `_EmbeddingColumn` sharing the same embedding.
Args:
sparse_id_columns: An iterable of `_SparseColumn`, such as those created by
`sparse_column_with_*` or crossed_column functions. Note that `combiner`
defined in each sparse_id_column is ignored.
dimension: An integer specifying dimension of the embedding.
combiner: A string specifying how to reduce if there are multiple entries in
a single row. Currently "mean", "sqrtn" and "sum" are supported, with
"mean" the default. "sqrtn" often achieves good accuracy, in particular
with bag-of-words columns. Each of this can be thought as example level
normalizations on the column:
* "sum": do not normalize
* "mean": do l1 normalization
* "sqrtn": do l2 normalization
For more information: `tf.embedding_lookup_sparse`.
shared_embedding_name: (Optional). A string specifying the name of shared
embedding weights. This will be needed if you want to reference the shared
embedding separately from the generated `_EmbeddingColumn`.
initializer: A variable initializer function to be used in embedding
variable initialization. If not specified, defaults to
`tf.compat.v1.truncated_normal_initializer` with mean 0.0 and standard
deviation 1/sqrt(sparse_id_columns[0].length).
ckpt_to_load_from: (Optional). String representing checkpoint name/pattern
to restore the column weights. Required if `tensor_name_in_ckpt` is not
None.
tensor_name_in_ckpt: (Optional). Name of the `Tensor` in the provided
checkpoint from which to restore the column weights. Required if
`ckpt_to_load_from` is not None.
max_norm: (Optional). If not None, embedding values are l2-normalized to the
value of max_norm.
trainable: (Optional). Should the embedding be trainable. Default is True
Returns:
A tuple of `_EmbeddingColumn` with shared embedding space.
Raises:
ValueError: if sparse_id_columns is empty, or its elements are not
compatible with each other.
TypeError: if `sparse_id_columns` is not a sequence or is a string. If at
least one element of `sparse_id_columns` is not a `SparseColumn` or a
`WeightedSparseColumn`.
"""
if (not isinstance(sparse_id_columns, collections_abc.Sequence) or
isinstance(sparse_id_columns, six.string_types)):
raise TypeError(
"sparse_id_columns must be a non-string sequence (ex: list or tuple) "
"instead of type {}.".format(type(sparse_id_columns)))
if len(sparse_id_columns) < 1:
raise ValueError("The input sparse_id_columns should have at least one "
"element.")
for sparse_id_column in sparse_id_columns:
if not (isinstance(sparse_id_column, _SparseColumn) or
isinstance(sparse_id_column, _WeightedSparseColumn)):
raise TypeError(
"Elements of sparse_id_columns must be _SparseColumn or "
"_WeightedSparseColumn, but {} is not.".format(sparse_id_column))
if len(sparse_id_columns) == 1:
return [
_EmbeddingColumn(
sparse_id_columns[0],
dimension,
combiner,
initializer,
ckpt_to_load_from,
tensor_name_in_ckpt,
shared_embedding_name,
max_norm=max_norm,
trainable=trainable)
]
else:
# Check compatibility of sparse_id_columns
compatible = True
for column in sparse_id_columns[1:]:
if isinstance(sparse_id_columns[0], _WeightedSparseColumn):
compatible = compatible and sparse_id_columns[0].is_compatible(column)
else:
compatible = compatible and column.is_compatible(sparse_id_columns[0])
if not compatible:
raise ValueError("The input sparse id columns are not compatible.")
# Construct the shared name and size for shared embedding space.
if not shared_embedding_name:
# Sort the columns so that shared_embedding_name will be deterministic
# even if users pass in unsorted columns from a dict or something.
# Since they are different classes, ordering is SparseColumns first,
# then WeightedSparseColumns.
sparse_columns = []
weighted_sparse_columns = []
for column in sparse_id_columns:
if isinstance(column, _SparseColumn):
sparse_columns.append(column)
else:
weighted_sparse_columns.append(column)
sorted_columns = sorted(sparse_columns) + sorted(
weighted_sparse_columns, key=lambda x: x.name)
if len(sorted_columns) <= 3:
shared_embedding_name = "_".join(
[column.name for column in sorted_columns])
else:
shared_embedding_name = "_".join(
[column.name for column in sorted_columns[0:3]])
shared_embedding_name += (
"_plus_{}_others".format(len(sorted_columns) - 3))
shared_embedding_name += "_shared_embedding"
shared_vocab_size = sparse_id_columns[0].length
embedded_columns = []
for column in sparse_id_columns:
embedded_columns.append(
_EmbeddingColumn(
column,
dimension,
combiner,
initializer,
ckpt_to_load_from,
tensor_name_in_ckpt,
shared_embedding_name,
shared_vocab_size,
max_norm=max_norm,
trainable=trainable))
return tuple(embedded_columns) | [
"def",
"shared_embedding_columns",
"(",
"sparse_id_columns",
",",
"dimension",
",",
"combiner",
"=",
"\"mean\"",
",",
"shared_embedding_name",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"ckpt_to_load_from",
"=",
"None",
",",
"tensor_name_in_ckpt",
"=",
"None",
",",
"max_norm",
"=",
"None",
",",
"trainable",
"=",
"True",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"sparse_id_columns",
",",
"collections_abc",
".",
"Sequence",
")",
"or",
"isinstance",
"(",
"sparse_id_columns",
",",
"six",
".",
"string_types",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"sparse_id_columns must be a non-string sequence (ex: list or tuple) \"",
"\"instead of type {}.\"",
".",
"format",
"(",
"type",
"(",
"sparse_id_columns",
")",
")",
")",
"if",
"len",
"(",
"sparse_id_columns",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"The input sparse_id_columns should have at least one \"",
"\"element.\"",
")",
"for",
"sparse_id_column",
"in",
"sparse_id_columns",
":",
"if",
"not",
"(",
"isinstance",
"(",
"sparse_id_column",
",",
"_SparseColumn",
")",
"or",
"isinstance",
"(",
"sparse_id_column",
",",
"_WeightedSparseColumn",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Elements of sparse_id_columns must be _SparseColumn or \"",
"\"_WeightedSparseColumn, but {} is not.\"",
".",
"format",
"(",
"sparse_id_column",
")",
")",
"if",
"len",
"(",
"sparse_id_columns",
")",
"==",
"1",
":",
"return",
"[",
"_EmbeddingColumn",
"(",
"sparse_id_columns",
"[",
"0",
"]",
",",
"dimension",
",",
"combiner",
",",
"initializer",
",",
"ckpt_to_load_from",
",",
"tensor_name_in_ckpt",
",",
"shared_embedding_name",
",",
"max_norm",
"=",
"max_norm",
",",
"trainable",
"=",
"trainable",
")",
"]",
"else",
":",
"# Check compatibility of sparse_id_columns",
"compatible",
"=",
"True",
"for",
"column",
"in",
"sparse_id_columns",
"[",
"1",
":",
"]",
":",
"if",
"isinstance",
"(",
"sparse_id_columns",
"[",
"0",
"]",
",",
"_WeightedSparseColumn",
")",
":",
"compatible",
"=",
"compatible",
"and",
"sparse_id_columns",
"[",
"0",
"]",
".",
"is_compatible",
"(",
"column",
")",
"else",
":",
"compatible",
"=",
"compatible",
"and",
"column",
".",
"is_compatible",
"(",
"sparse_id_columns",
"[",
"0",
"]",
")",
"if",
"not",
"compatible",
":",
"raise",
"ValueError",
"(",
"\"The input sparse id columns are not compatible.\"",
")",
"# Construct the shared name and size for shared embedding space.",
"if",
"not",
"shared_embedding_name",
":",
"# Sort the columns so that shared_embedding_name will be deterministic",
"# even if users pass in unsorted columns from a dict or something.",
"# Since they are different classes, ordering is SparseColumns first,",
"# then WeightedSparseColumns.",
"sparse_columns",
"=",
"[",
"]",
"weighted_sparse_columns",
"=",
"[",
"]",
"for",
"column",
"in",
"sparse_id_columns",
":",
"if",
"isinstance",
"(",
"column",
",",
"_SparseColumn",
")",
":",
"sparse_columns",
".",
"append",
"(",
"column",
")",
"else",
":",
"weighted_sparse_columns",
".",
"append",
"(",
"column",
")",
"sorted_columns",
"=",
"sorted",
"(",
"sparse_columns",
")",
"+",
"sorted",
"(",
"weighted_sparse_columns",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"name",
")",
"if",
"len",
"(",
"sorted_columns",
")",
"<=",
"3",
":",
"shared_embedding_name",
"=",
"\"_\"",
".",
"join",
"(",
"[",
"column",
".",
"name",
"for",
"column",
"in",
"sorted_columns",
"]",
")",
"else",
":",
"shared_embedding_name",
"=",
"\"_\"",
".",
"join",
"(",
"[",
"column",
".",
"name",
"for",
"column",
"in",
"sorted_columns",
"[",
"0",
":",
"3",
"]",
"]",
")",
"shared_embedding_name",
"+=",
"(",
"\"_plus_{}_others\"",
".",
"format",
"(",
"len",
"(",
"sorted_columns",
")",
"-",
"3",
")",
")",
"shared_embedding_name",
"+=",
"\"_shared_embedding\"",
"shared_vocab_size",
"=",
"sparse_id_columns",
"[",
"0",
"]",
".",
"length",
"embedded_columns",
"=",
"[",
"]",
"for",
"column",
"in",
"sparse_id_columns",
":",
"embedded_columns",
".",
"append",
"(",
"_EmbeddingColumn",
"(",
"column",
",",
"dimension",
",",
"combiner",
",",
"initializer",
",",
"ckpt_to_load_from",
",",
"tensor_name_in_ckpt",
",",
"shared_embedding_name",
",",
"shared_vocab_size",
",",
"max_norm",
"=",
"max_norm",
",",
"trainable",
"=",
"trainable",
")",
")",
"return",
"tuple",
"(",
"embedded_columns",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py#L1355-L1485 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/command_interface/ISISCommandInterface.py | python | TransWorkspace | (sample, can=None) | Use a given workpspace that contains pre-calculated transmissions
@param sample the workspace to use for the sample
@param can calculated transmission for the can | Use a given workpspace that contains pre-calculated transmissions | [
"Use",
"a",
"given",
"workpspace",
"that",
"contains",
"pre",
"-",
"calculated",
"transmissions"
] | def TransWorkspace(sample, can=None):
"""
Use a given workpspace that contains pre-calculated transmissions
@param sample the workspace to use for the sample
@param can calculated transmission for the can
"""
_, _ = sample, can # noqa
raise NotImplementedError("The TransWorkspace command is not implemented in SANS v2.") | [
"def",
"TransWorkspace",
"(",
"sample",
",",
"can",
"=",
"None",
")",
":",
"_",
",",
"_",
"=",
"sample",
",",
"can",
"# noqa",
"raise",
"NotImplementedError",
"(",
"\"The TransWorkspace command is not implemented in SANS v2.\"",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/command_interface/ISISCommandInterface.py#L132-L139 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/environment.py | python | Template.debug_info | (self) | return [tuple(imap(int, x.split('='))) for x in
self._debug_info.split('&')] | The debug info mapping. | The debug info mapping. | [
"The",
"debug",
"info",
"mapping",
"."
] | def debug_info(self):
"""The debug info mapping."""
return [tuple(imap(int, x.split('='))) for x in
self._debug_info.split('&')] | [
"def",
"debug_info",
"(",
"self",
")",
":",
"return",
"[",
"tuple",
"(",
"imap",
"(",
"int",
",",
"x",
".",
"split",
"(",
"'='",
")",
")",
")",
"for",
"x",
"in",
"self",
".",
"_debug_info",
".",
"split",
"(",
"'&'",
")",
"]"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/environment.py#L1125-L1128 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Rect2D.GetRight | (*args, **kwargs) | return _core_.Rect2D_GetRight(*args, **kwargs) | GetRight(self) -> Double | GetRight(self) -> Double | [
"GetRight",
"(",
"self",
")",
"-",
">",
"Double"
] | def GetRight(*args, **kwargs):
"""GetRight(self) -> Double"""
return _core_.Rect2D_GetRight(*args, **kwargs) | [
"def",
"GetRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect2D_GetRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1891-L1893 | |
koth/kcws | 88efbd36a7022de4e6e90f5a1fb880cf87cfae9f | third_party/python/cpplint/cpplint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"r",
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style. Also look for
# non-single-argument constructors which are also technically valid, but
# strongly suggest something is wrong.
explicit_constructor_match = Match(
r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*'
r'\(((?:[^()]|\([^()]*\))*)\)'
% re.escape(base_classname),
line)
if explicit_constructor_match:
is_marked_explicit = explicit_constructor_match.group(1)
if not explicit_constructor_match.group(2):
constructor_args = []
else:
constructor_args = explicit_constructor_match.group(2).split(',')
# collapse arguments so that commas in template parameter lists and function
# argument parameter lists don't split arguments in two
i = 0
while i < len(constructor_args):
constructor_arg = constructor_args[i]
while (constructor_arg.count('<') > constructor_arg.count('>') or
constructor_arg.count('(') > constructor_arg.count(')')):
constructor_arg += ',' + constructor_args[i + 1]
del constructor_args[i + 1]
constructor_args[i] = constructor_arg
i += 1
defaulted_args = [arg for arg in constructor_args if '=' in arg]
noarg_constructor = (not constructor_args or # empty arg list
# 'void' arg specifier
(len(constructor_args) == 1 and
constructor_args[0].strip() == 'void'))
onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
not noarg_constructor) or
# all but at most one arg defaulted
(len(constructor_args) >= 1 and
not noarg_constructor and
len(defaulted_args) >= len(constructor_args) - 1))
initializer_list_constructor = bool(
onearg_constructor and
Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
copy_constructor = bool(
onearg_constructor and
Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), constructor_args[0].strip()))
if (not is_marked_explicit and
onearg_constructor and
not initializer_list_constructor and
not copy_constructor):
if defaulted_args:
error(filename, linenum, 'runtime/explicit', 5,
'Constructors callable with one argument '
'should be marked explicit.')
else:
error(filename, linenum, 'runtime/explicit', 5,
'Single-parameter constructors should be marked explicit.')
elif is_marked_explicit and not onearg_constructor:
if noarg_constructor:
error(filename, linenum, 'runtime/explicit', 5,
'Zero-parameter constructors should not be marked explicit.')
else:
error(filename, linenum, 'runtime/explicit', 0,
'Constructors that require multiple arguments '
'should not be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage class (static, extern, typedef, etc) should be first.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Everything else in this function operates on class declarations.",
"# Return early if the top of the nesting stack is not a class, or if",
"# the class head is not completed yet.",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"not",
"classinfo",
"or",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style. Also look for",
"# non-single-argument constructors which are also technically valid, but",
"# strongly suggest something is wrong.",
"explicit_constructor_match",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?(explicit\\s+)?(?:inline\\s+)?%s\\s*'",
"r'\\(((?:[^()]|\\([^()]*\\))*)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"explicit_constructor_match",
":",
"is_marked_explicit",
"=",
"explicit_constructor_match",
".",
"group",
"(",
"1",
")",
"if",
"not",
"explicit_constructor_match",
".",
"group",
"(",
"2",
")",
":",
"constructor_args",
"=",
"[",
"]",
"else",
":",
"constructor_args",
"=",
"explicit_constructor_match",
".",
"group",
"(",
"2",
")",
".",
"split",
"(",
"','",
")",
"# collapse arguments so that commas in template parameter lists and function",
"# argument parameter lists don't split arguments in two",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"constructor_args",
")",
":",
"constructor_arg",
"=",
"constructor_args",
"[",
"i",
"]",
"while",
"(",
"constructor_arg",
".",
"count",
"(",
"'<'",
")",
">",
"constructor_arg",
".",
"count",
"(",
"'>'",
")",
"or",
"constructor_arg",
".",
"count",
"(",
"'('",
")",
">",
"constructor_arg",
".",
"count",
"(",
"')'",
")",
")",
":",
"constructor_arg",
"+=",
"','",
"+",
"constructor_args",
"[",
"i",
"+",
"1",
"]",
"del",
"constructor_args",
"[",
"i",
"+",
"1",
"]",
"constructor_args",
"[",
"i",
"]",
"=",
"constructor_arg",
"i",
"+=",
"1",
"defaulted_args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"constructor_args",
"if",
"'='",
"in",
"arg",
"]",
"noarg_constructor",
"=",
"(",
"not",
"constructor_args",
"or",
"# empty arg list",
"# 'void' arg specifier",
"(",
"len",
"(",
"constructor_args",
")",
"==",
"1",
"and",
"constructor_args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"==",
"'void'",
")",
")",
"onearg_constructor",
"=",
"(",
"(",
"len",
"(",
"constructor_args",
")",
"==",
"1",
"and",
"# exactly one arg",
"not",
"noarg_constructor",
")",
"or",
"# all but at most one arg defaulted",
"(",
"len",
"(",
"constructor_args",
")",
">=",
"1",
"and",
"not",
"noarg_constructor",
"and",
"len",
"(",
"defaulted_args",
")",
">=",
"len",
"(",
"constructor_args",
")",
"-",
"1",
")",
")",
"initializer_list_constructor",
"=",
"bool",
"(",
"onearg_constructor",
"and",
"Search",
"(",
"r'\\bstd\\s*::\\s*initializer_list\\b'",
",",
"constructor_args",
"[",
"0",
"]",
")",
")",
"copy_constructor",
"=",
"bool",
"(",
"onearg_constructor",
"and",
"Match",
"(",
"r'(const\\s+)?%s(\\s*<[^>]*>)?(\\s+const)?\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"constructor_args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
")",
"if",
"(",
"not",
"is_marked_explicit",
"and",
"onearg_constructor",
"and",
"not",
"initializer_list_constructor",
"and",
"not",
"copy_constructor",
")",
":",
"if",
"defaulted_args",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Constructors callable with one argument '",
"'should be marked explicit.'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-parameter constructors should be marked explicit.'",
")",
"elif",
"is_marked_explicit",
"and",
"not",
"onearg_constructor",
":",
"if",
"noarg_constructor",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Zero-parameter constructors should not be marked explicit.'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"0",
",",
"'Constructors that require multiple arguments '",
"'should not be marked explicit.'",
")"
] | https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/python/cpplint/cpplint.py#L2574-L2735 | ||
gitahead/gitahead | 711a9633149ef8f9dd0d2d6becfee4e147b6458c | dep/scintilla/scintilla-3.21.0/scripts/FileGenerator.py | python | UpdateLineInPlistFile | (path, key, value) | Replace a single string value preceded by 'key' in an XML plist file. | Replace a single string value preceded by 'key' in an XML plist file. | [
"Replace",
"a",
"single",
"string",
"value",
"preceded",
"by",
"key",
"in",
"an",
"XML",
"plist",
"file",
"."
] | def UpdateLineInPlistFile(path, key, value):
"""Replace a single string value preceded by 'key' in an XML plist file.
"""
lines = []
keyCurrent = ""
with codecs.open(path, "rb", "utf-8") as f:
for l in f.readlines():
ls = l.strip()
if ls.startswith("<key>"):
keyCurrent = ls.replace("<key>", "").replace("</key>", "")
elif ls.startswith("<string>"):
if keyCurrent == key:
start, tag, rest = l.partition("<string>")
val, etag, end = rest.partition("</string>")
l = start + tag + value + etag + end
lines.append(l)
contents = "".join(lines)
UpdateFile(path, contents) | [
"def",
"UpdateLineInPlistFile",
"(",
"path",
",",
"key",
",",
"value",
")",
":",
"lines",
"=",
"[",
"]",
"keyCurrent",
"=",
"\"\"",
"with",
"codecs",
".",
"open",
"(",
"path",
",",
"\"rb\"",
",",
"\"utf-8\"",
")",
"as",
"f",
":",
"for",
"l",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"ls",
"=",
"l",
".",
"strip",
"(",
")",
"if",
"ls",
".",
"startswith",
"(",
"\"<key>\"",
")",
":",
"keyCurrent",
"=",
"ls",
".",
"replace",
"(",
"\"<key>\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"</key>\"",
",",
"\"\"",
")",
"elif",
"ls",
".",
"startswith",
"(",
"\"<string>\"",
")",
":",
"if",
"keyCurrent",
"==",
"key",
":",
"start",
",",
"tag",
",",
"rest",
"=",
"l",
".",
"partition",
"(",
"\"<string>\"",
")",
"val",
",",
"etag",
",",
"end",
"=",
"rest",
".",
"partition",
"(",
"\"</string>\"",
")",
"l",
"=",
"start",
"+",
"tag",
"+",
"value",
"+",
"etag",
"+",
"end",
"lines",
".",
"append",
"(",
"l",
")",
"contents",
"=",
"\"\"",
".",
"join",
"(",
"lines",
")",
"UpdateFile",
"(",
"path",
",",
"contents",
")"
] | https://github.com/gitahead/gitahead/blob/711a9633149ef8f9dd0d2d6becfee4e147b6458c/dep/scintilla/scintilla-3.21.0/scripts/FileGenerator.py#L140-L157 | ||
daijifeng001/caffe-rfcn | 543f8f6a4b7c88256ea1445ae951a12d1ad9cffd | python/caffe/coord_map.py | python | conv_params | (fn) | return (axis, np.array(params.get('stride', 1), ndmin=1),
(ks - 1) * dilation + 1,
np.array(params.get('pad', 0), ndmin=1)) | Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation.
Implementation detail: Convolution, Deconvolution, and Im2col layers
define these in the convolution_param message, while Pooling has its
own fields in pooling_param. This method deals with these details to
extract canonical parameters. | Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation. | [
"Extract",
"the",
"spatial",
"parameters",
"that",
"determine",
"the",
"coordinate",
"mapping",
":",
"kernel",
"size",
"stride",
"padding",
"and",
"dilation",
"."
] | def conv_params(fn):
"""
Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation.
Implementation detail: Convolution, Deconvolution, and Im2col layers
define these in the convolution_param message, while Pooling has its
own fields in pooling_param. This method deals with these details to
extract canonical parameters.
"""
params = fn.params.get('convolution_param', fn.params)
axis = params.get('axis', 1)
ks = np.array(params['kernel_size'], ndmin=1)
dilation = np.array(params.get('dilation', 1), ndmin=1)
assert len({'pad_h', 'pad_w', 'kernel_h', 'kernel_w', 'stride_h',
'stride_w'} & set(fn.params)) == 0, \
'cropping does not support legacy _h/_w params'
return (axis, np.array(params.get('stride', 1), ndmin=1),
(ks - 1) * dilation + 1,
np.array(params.get('pad', 0), ndmin=1)) | [
"def",
"conv_params",
"(",
"fn",
")",
":",
"params",
"=",
"fn",
".",
"params",
".",
"get",
"(",
"'convolution_param'",
",",
"fn",
".",
"params",
")",
"axis",
"=",
"params",
".",
"get",
"(",
"'axis'",
",",
"1",
")",
"ks",
"=",
"np",
".",
"array",
"(",
"params",
"[",
"'kernel_size'",
"]",
",",
"ndmin",
"=",
"1",
")",
"dilation",
"=",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'dilation'",
",",
"1",
")",
",",
"ndmin",
"=",
"1",
")",
"assert",
"len",
"(",
"{",
"'pad_h'",
",",
"'pad_w'",
",",
"'kernel_h'",
",",
"'kernel_w'",
",",
"'stride_h'",
",",
"'stride_w'",
"}",
"&",
"set",
"(",
"fn",
".",
"params",
")",
")",
"==",
"0",
",",
"'cropping does not support legacy _h/_w params'",
"return",
"(",
"axis",
",",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'stride'",
",",
"1",
")",
",",
"ndmin",
"=",
"1",
")",
",",
"(",
"ks",
"-",
"1",
")",
"*",
"dilation",
"+",
"1",
",",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'pad'",
",",
"0",
")",
",",
"ndmin",
"=",
"1",
")",
")"
] | https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/python/caffe/coord_map.py#L18-L37 | |
potassco/clingo | e0c91d8f95cc28de1c480a871f9c97c30de83d40 | examples/clingo/dl/app.py | python | DLPropagator.init | (self, init: PropagateInit) | Initialize the propagator extracting difference constraints from the
theory data. | Initialize the propagator extracting difference constraints from the
theory data. | [
"Initialize",
"the",
"propagator",
"extracting",
"difference",
"constraints",
"from",
"the",
"theory",
"data",
"."
] | def init(self, init: PropagateInit):
'''
Initialize the propagator extracting difference constraints from the
theory data.
'''
for atom in init.theory_atoms:
term = atom.term
if term.name == "diff" and len(term.arguments) == 1:
assert atom.guard is not None
u = _evaluate(atom.elements[0].terms[0].arguments[0])
v = _evaluate(atom.elements[0].terms[0].arguments[1])
w = _evaluate(atom.guard[1]).number
lit = init.solver_literal(atom.literal)
self._add_edge(init, lit, u, v, w)
if term.arguments[0].name == "body":
self._add_edge(init, -lit, v, u, -w - 1) | [
"def",
"init",
"(",
"self",
",",
"init",
":",
"PropagateInit",
")",
":",
"for",
"atom",
"in",
"init",
".",
"theory_atoms",
":",
"term",
"=",
"atom",
".",
"term",
"if",
"term",
".",
"name",
"==",
"\"diff\"",
"and",
"len",
"(",
"term",
".",
"arguments",
")",
"==",
"1",
":",
"assert",
"atom",
".",
"guard",
"is",
"not",
"None",
"u",
"=",
"_evaluate",
"(",
"atom",
".",
"elements",
"[",
"0",
"]",
".",
"terms",
"[",
"0",
"]",
".",
"arguments",
"[",
"0",
"]",
")",
"v",
"=",
"_evaluate",
"(",
"atom",
".",
"elements",
"[",
"0",
"]",
".",
"terms",
"[",
"0",
"]",
".",
"arguments",
"[",
"1",
"]",
")",
"w",
"=",
"_evaluate",
"(",
"atom",
".",
"guard",
"[",
"1",
"]",
")",
".",
"number",
"lit",
"=",
"init",
".",
"solver_literal",
"(",
"atom",
".",
"literal",
")",
"self",
".",
"_add_edge",
"(",
"init",
",",
"lit",
",",
"u",
",",
"v",
",",
"w",
")",
"if",
"term",
".",
"arguments",
"[",
"0",
"]",
".",
"name",
"==",
"\"body\"",
":",
"self",
".",
"_add_edge",
"(",
"init",
",",
"-",
"lit",
",",
"v",
",",
"u",
",",
"-",
"w",
"-",
"1",
")"
] | https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/examples/clingo/dl/app.py#L277-L292 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py | python | extract_dask_data | (data) | Extract data from dask.Series or dask.DataFrame for predictors. | Extract data from dask.Series or dask.DataFrame for predictors. | [
"Extract",
"data",
"from",
"dask",
".",
"Series",
"or",
"dask",
".",
"DataFrame",
"for",
"predictors",
"."
] | def extract_dask_data(data):
"""Extract data from dask.Series or dask.DataFrame for predictors."""
if isinstance(data, allowed_classes):
return _construct_dask_df_with_divisions(data)
else:
return data | [
"def",
"extract_dask_data",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"allowed_classes",
")",
":",
"return",
"_construct_dask_df_with_divisions",
"(",
"data",
")",
"else",
":",
"return",
"data"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py#L63-L68 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/fx/passes/graph_manipulation.py | python | serialize_module | (fx_module: GraphModule, weights: Dict, name_prefix="") | return serialized_dict | Recursively Serializes a graph module (fx_module) to a dictionary which is later exported to JSON.
It also adds all weights the provided weights dictionary by qualified_name.
Dictionary Schema:
MODULE
{
modules: {module_name: MODULE],
nodes: [NODE],
weights {qualified_name: WEIGHT},
}
NODE
{
shape: [],
stride: [],
dtype: dtype,
is_quantized: bool,
target: target,
op_code: op_code,
name: name,
args: [],
kwargs: {}
}
WEIGHT
{
dtype: dtype,
is_quantized: bool,
shape: [],
QUANTIZATION,
}
QUANTIZATION
{
qscheme: qscheme,
q_scale: float,
q_zero_point: float,
q_per_channel_scales, [],
q_per_channel_zero_points: [],
q_per_channel_axis, int
} | Recursively Serializes a graph module (fx_module) to a dictionary which is later exported to JSON.
It also adds all weights the provided weights dictionary by qualified_name.
Dictionary Schema:
MODULE
{
modules: {module_name: MODULE],
nodes: [NODE],
weights {qualified_name: WEIGHT},
}
NODE
{
shape: [],
stride: [],
dtype: dtype,
is_quantized: bool,
target: target,
op_code: op_code,
name: name,
args: [],
kwargs: {}
}
WEIGHT
{
dtype: dtype,
is_quantized: bool,
shape: [],
QUANTIZATION,
}
QUANTIZATION
{
qscheme: qscheme,
q_scale: float,
q_zero_point: float,
q_per_channel_scales, [],
q_per_channel_zero_points: [],
q_per_channel_axis, int
} | [
"Recursively",
"Serializes",
"a",
"graph",
"module",
"(",
"fx_module",
")",
"to",
"a",
"dictionary",
"which",
"is",
"later",
"exported",
"to",
"JSON",
".",
"It",
"also",
"adds",
"all",
"weights",
"the",
"provided",
"weights",
"dictionary",
"by",
"qualified_name",
".",
"Dictionary",
"Schema",
":",
"MODULE",
"{",
"modules",
":",
"{",
"module_name",
":",
"MODULE",
"]",
"nodes",
":",
"[",
"NODE",
"]",
"weights",
"{",
"qualified_name",
":",
"WEIGHT",
"}",
"}",
"NODE",
"{",
"shape",
":",
"[]",
"stride",
":",
"[]",
"dtype",
":",
"dtype",
"is_quantized",
":",
"bool",
"target",
":",
"target",
"op_code",
":",
"op_code",
"name",
":",
"name",
"args",
":",
"[]",
"kwargs",
":",
"{}",
"}",
"WEIGHT",
"{",
"dtype",
":",
"dtype",
"is_quantized",
":",
"bool",
"shape",
":",
"[]",
"QUANTIZATION",
"}",
"QUANTIZATION",
"{",
"qscheme",
":",
"qscheme",
"q_scale",
":",
"float",
"q_zero_point",
":",
"float",
"q_per_channel_scales",
"[]",
"q_per_channel_zero_points",
":",
"[]",
"q_per_channel_axis",
"int",
"}"
] | def serialize_module(fx_module: GraphModule, weights: Dict, name_prefix="") -> Dict:
"""Recursively Serializes a graph module (fx_module) to a dictionary which is later exported to JSON.
It also adds all weights the provided weights dictionary by qualified_name.
Dictionary Schema:
MODULE
{
modules: {module_name: MODULE],
nodes: [NODE],
weights {qualified_name: WEIGHT},
}
NODE
{
shape: [],
stride: [],
dtype: dtype,
is_quantized: bool,
target: target,
op_code: op_code,
name: name,
args: [],
kwargs: {}
}
WEIGHT
{
dtype: dtype,
is_quantized: bool,
shape: [],
QUANTIZATION,
}
QUANTIZATION
{
qscheme: qscheme,
q_scale: float,
q_zero_point: float,
q_per_channel_scales, [],
q_per_channel_zero_points: [],
q_per_channel_axis, int
}
"""
serialized_dict: Dict[str, Any] = {}
serialized_dict["modules"] = {}
serialized_dict["weights"] = {}
serialized_dict["nodes"] = []
submodules = dict(fx_module.named_modules())
prefix = f"{name_prefix}." if name_prefix else ""
def add_weight_tensors(named_tensors):
for name, p in named_tensors:
if name.startswith("parent.") or not isinstance(p, torch.Tensor):
continue
weight_dict = serialize_weight(p, weights, prefix + name)
serialized_dict["weights"].update(weight_dict)
weights[prefix + name] = p
add_weight_tensors(fx_module.named_parameters())
add_weight_tensors(fx_module.named_buffers())
def get_node_info(node):
tensor_meta = get_tensor_meta(node)
node_rep = {
"shape": serialize_shape(tensor_meta.shape),
"dtype": str(tensor_meta.dtype),
"requires_grad": str(tensor_meta.requires_grad),
"stride": serialize_stride(tensor_meta.stride),
"is_quantized": tensor_meta.is_quantized,
}
if tensor_meta.is_quantized:
node_rep["qscheme"] = str(tensor_meta.qparams["qscheme"])
if tensor_meta.qparams["qscheme"] in {
torch.per_tensor_affine,
torch.per_tensor_symmetric,
}:
node_rep["q_scale"] = tensor_meta.qparams["scale"]
node_rep["q_zero_point"] = tensor_meta.qparams["zero_point"]
# Add all extra lowering_info that was provided in node.meta.
lowering_info = node.meta.get("lowering_info")
if lowering_info is not None:
overlapping_keys = node_rep.keys() & lowering_info.keys()
assert (
len(overlapping_keys) == 0
), f"Overlap found between lowering_info and node_rep: {overlapping_keys}"
node_rep.update(lowering_info)
return node_rep
# Note: lift_lowering_attrs_to_nodes is only used to support leaf modules
# that cannot currently be symbolically traced into, e.g. batch norm.
lift_lowering_attrs_to_nodes(fx_module)
for node in fx_module.graph.nodes:
node_rep: Dict[str, Any] = {}
# Get shape/type info, currently not needed for call_module node
# whose target is a GraphModule and output node.
if (
not (
node.op == "call_module"
and isinstance(submodules[node.target], GraphModule)
)
and node.op != "output"
):
node_rep.update(get_node_info(node))
# Recurse down into any submodules we are calling.
if node.op == "call_module":
if isinstance(submodules[node.target], GraphModule):
serialized_module = serialize_module(
getattr(fx_module, node.target), weights, node.target
)
serialized_dict["modules"][node.target] = serialized_module
else:
node_rep["parameters"] = serialize_leaf_module(
node,
serialized_dict["weights"],
weights,
prefix + node.target,
)
if node.op == "call_function":
node_rep["target"] = _get_qualified_name(node.target)
else:
node_rep["target"] = str(node.target)
# Make sure we capture all constants.
if node.op == "get_attr":
# If we are targeting a parent constant we update the target.
if node.target.startswith("parent."):
stripped_name = node.target[len("parent.") :]
node.name = stripped_name
node_rep["target"] = stripped_name
weight = serialize_weight(
weights[stripped_name], weights, node.target[len("parent.") :]
)
# For quantized embedding tables we need to update the shape/type,
# so we check if the users of this get_attr is a quantized EB and this is the weight for the EB.
user_targets = {
_get_qualified_name(n.target)
.replace("torch.fx.experimental.fx_acc.", "")
.replace("glow.fb.fx.", ""): n
for n in node.users.keys()
}
if (
"acc_ops.embedding_bag_byte_rowwise_offsets" in user_targets
and str(
user_targets[
"acc_ops.embedding_bag_byte_rowwise_offsets"
].kwargs["weight"]
)
== stripped_name
):
weight[stripped_name]["dtype"] = "acc.uint8fused"
# Same as above, but for the 4 bit version.
if (
"acc_ops.embedding_bag_4bit_rowwise_offsets" in user_targets
and str(
user_targets[
"acc_ops.embedding_bag_4bit_rowwise_offsets"
].kwargs["weight"]
)
== stripped_name
):
weight[stripped_name]["dtype"] = "acc.uint4fused"
serialized_dict["weights"].update(weight)
else:
# Find the actual target parameter/buffer from the fx_module.
submod_path, _, target_name = node.target.rpartition(".")
submod: Optional[torch.nn.Module] = (
fx_module.get_submodule(submod_path) if submod_path else fx_module
)
assert submod is not None, f"submod {submod_path} not found"
target = getattr(submod, target_name, None)
assert target is not None, f"{target_name} not an attr of {submod_path}"
qualname = prefix + node.target
# Check that the target is a tensor, and that we haven't added it already from a leaf module.
if isinstance(target, torch.Tensor) and qualname not in weights:
weight = serialize_weight(target, weights, qualname)
serialized_dict["weights"].update(weight)
weights[qualname] = target
node_rep["op_code"] = node.op
node_rep["name"] = node.name
def get_user_info(user_node: Argument) -> Any:
return {"is_node": True, "name": str(user_node)}
def get_arg_info(arg: Argument) -> Any:
if isinstance(arg, torch.fx.Node):
return {"is_node": True, "name": str(arg)}
elif isinstance(arg, (torch.dtype, torch.memory_format, torch.qscheme)):
return str(arg)
else:
return arg
def get_output_arg_info(arg: Node) -> Dict[str, Any]:
node_rep: Dict[str, Any] = get_arg_info(arg)
node_rep.update(get_node_info(arg))
return node_rep
if node.op == "output":
node_rep["args"] = map_arg(
node.args,
get_output_arg_info,
)
# If there're multiple outputs then node_rep["args"][0] will be a tuple.
# In this case we want to unpack the tuple.
if isinstance(node_rep["args"][0], tuple):
node_rep["args"] = node_rep["args"][0]
else:
node_rep["args"] = map_aggregate(node.args, get_arg_info)
node_rep["kwargs"] = map_aggregate(node.kwargs, get_arg_info)
node_rep["users"] = map_aggregate(list(node.users.keys()), get_user_info)
serialized_dict["nodes"] += [node_rep]
return serialized_dict | [
"def",
"serialize_module",
"(",
"fx_module",
":",
"GraphModule",
",",
"weights",
":",
"Dict",
",",
"name_prefix",
"=",
"\"\"",
")",
"->",
"Dict",
":",
"serialized_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"serialized_dict",
"[",
"\"modules\"",
"]",
"=",
"{",
"}",
"serialized_dict",
"[",
"\"weights\"",
"]",
"=",
"{",
"}",
"serialized_dict",
"[",
"\"nodes\"",
"]",
"=",
"[",
"]",
"submodules",
"=",
"dict",
"(",
"fx_module",
".",
"named_modules",
"(",
")",
")",
"prefix",
"=",
"f\"{name_prefix}.\"",
"if",
"name_prefix",
"else",
"\"\"",
"def",
"add_weight_tensors",
"(",
"named_tensors",
")",
":",
"for",
"name",
",",
"p",
"in",
"named_tensors",
":",
"if",
"name",
".",
"startswith",
"(",
"\"parent.\"",
")",
"or",
"not",
"isinstance",
"(",
"p",
",",
"torch",
".",
"Tensor",
")",
":",
"continue",
"weight_dict",
"=",
"serialize_weight",
"(",
"p",
",",
"weights",
",",
"prefix",
"+",
"name",
")",
"serialized_dict",
"[",
"\"weights\"",
"]",
".",
"update",
"(",
"weight_dict",
")",
"weights",
"[",
"prefix",
"+",
"name",
"]",
"=",
"p",
"add_weight_tensors",
"(",
"fx_module",
".",
"named_parameters",
"(",
")",
")",
"add_weight_tensors",
"(",
"fx_module",
".",
"named_buffers",
"(",
")",
")",
"def",
"get_node_info",
"(",
"node",
")",
":",
"tensor_meta",
"=",
"get_tensor_meta",
"(",
"node",
")",
"node_rep",
"=",
"{",
"\"shape\"",
":",
"serialize_shape",
"(",
"tensor_meta",
".",
"shape",
")",
",",
"\"dtype\"",
":",
"str",
"(",
"tensor_meta",
".",
"dtype",
")",
",",
"\"requires_grad\"",
":",
"str",
"(",
"tensor_meta",
".",
"requires_grad",
")",
",",
"\"stride\"",
":",
"serialize_stride",
"(",
"tensor_meta",
".",
"stride",
")",
",",
"\"is_quantized\"",
":",
"tensor_meta",
".",
"is_quantized",
",",
"}",
"if",
"tensor_meta",
".",
"is_quantized",
":",
"node_rep",
"[",
"\"qscheme\"",
"]",
"=",
"str",
"(",
"tensor_meta",
".",
"qparams",
"[",
"\"qscheme\"",
"]",
")",
"if",
"tensor_meta",
".",
"qparams",
"[",
"\"qscheme\"",
"]",
"in",
"{",
"torch",
".",
"per_tensor_affine",
",",
"torch",
".",
"per_tensor_symmetric",
",",
"}",
":",
"node_rep",
"[",
"\"q_scale\"",
"]",
"=",
"tensor_meta",
".",
"qparams",
"[",
"\"scale\"",
"]",
"node_rep",
"[",
"\"q_zero_point\"",
"]",
"=",
"tensor_meta",
".",
"qparams",
"[",
"\"zero_point\"",
"]",
"# Add all extra lowering_info that was provided in node.meta.",
"lowering_info",
"=",
"node",
".",
"meta",
".",
"get",
"(",
"\"lowering_info\"",
")",
"if",
"lowering_info",
"is",
"not",
"None",
":",
"overlapping_keys",
"=",
"node_rep",
".",
"keys",
"(",
")",
"&",
"lowering_info",
".",
"keys",
"(",
")",
"assert",
"(",
"len",
"(",
"overlapping_keys",
")",
"==",
"0",
")",
",",
"f\"Overlap found between lowering_info and node_rep: {overlapping_keys}\"",
"node_rep",
".",
"update",
"(",
"lowering_info",
")",
"return",
"node_rep",
"# Note: lift_lowering_attrs_to_nodes is only used to support leaf modules",
"# that cannot currently be symbolically traced into, e.g. batch norm.",
"lift_lowering_attrs_to_nodes",
"(",
"fx_module",
")",
"for",
"node",
"in",
"fx_module",
".",
"graph",
".",
"nodes",
":",
"node_rep",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"# Get shape/type info, currently not needed for call_module node",
"# whose target is a GraphModule and output node.",
"if",
"(",
"not",
"(",
"node",
".",
"op",
"==",
"\"call_module\"",
"and",
"isinstance",
"(",
"submodules",
"[",
"node",
".",
"target",
"]",
",",
"GraphModule",
")",
")",
"and",
"node",
".",
"op",
"!=",
"\"output\"",
")",
":",
"node_rep",
".",
"update",
"(",
"get_node_info",
"(",
"node",
")",
")",
"# Recurse down into any submodules we are calling.",
"if",
"node",
".",
"op",
"==",
"\"call_module\"",
":",
"if",
"isinstance",
"(",
"submodules",
"[",
"node",
".",
"target",
"]",
",",
"GraphModule",
")",
":",
"serialized_module",
"=",
"serialize_module",
"(",
"getattr",
"(",
"fx_module",
",",
"node",
".",
"target",
")",
",",
"weights",
",",
"node",
".",
"target",
")",
"serialized_dict",
"[",
"\"modules\"",
"]",
"[",
"node",
".",
"target",
"]",
"=",
"serialized_module",
"else",
":",
"node_rep",
"[",
"\"parameters\"",
"]",
"=",
"serialize_leaf_module",
"(",
"node",
",",
"serialized_dict",
"[",
"\"weights\"",
"]",
",",
"weights",
",",
"prefix",
"+",
"node",
".",
"target",
",",
")",
"if",
"node",
".",
"op",
"==",
"\"call_function\"",
":",
"node_rep",
"[",
"\"target\"",
"]",
"=",
"_get_qualified_name",
"(",
"node",
".",
"target",
")",
"else",
":",
"node_rep",
"[",
"\"target\"",
"]",
"=",
"str",
"(",
"node",
".",
"target",
")",
"# Make sure we capture all constants.",
"if",
"node",
".",
"op",
"==",
"\"get_attr\"",
":",
"# If we are targeting a parent constant we update the target.",
"if",
"node",
".",
"target",
".",
"startswith",
"(",
"\"parent.\"",
")",
":",
"stripped_name",
"=",
"node",
".",
"target",
"[",
"len",
"(",
"\"parent.\"",
")",
":",
"]",
"node",
".",
"name",
"=",
"stripped_name",
"node_rep",
"[",
"\"target\"",
"]",
"=",
"stripped_name",
"weight",
"=",
"serialize_weight",
"(",
"weights",
"[",
"stripped_name",
"]",
",",
"weights",
",",
"node",
".",
"target",
"[",
"len",
"(",
"\"parent.\"",
")",
":",
"]",
")",
"# For quantized embedding tables we need to update the shape/type,",
"# so we check if the users of this get_attr is a quantized EB and this is the weight for the EB.",
"user_targets",
"=",
"{",
"_get_qualified_name",
"(",
"n",
".",
"target",
")",
".",
"replace",
"(",
"\"torch.fx.experimental.fx_acc.\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"glow.fb.fx.\"",
",",
"\"\"",
")",
":",
"n",
"for",
"n",
"in",
"node",
".",
"users",
".",
"keys",
"(",
")",
"}",
"if",
"(",
"\"acc_ops.embedding_bag_byte_rowwise_offsets\"",
"in",
"user_targets",
"and",
"str",
"(",
"user_targets",
"[",
"\"acc_ops.embedding_bag_byte_rowwise_offsets\"",
"]",
".",
"kwargs",
"[",
"\"weight\"",
"]",
")",
"==",
"stripped_name",
")",
":",
"weight",
"[",
"stripped_name",
"]",
"[",
"\"dtype\"",
"]",
"=",
"\"acc.uint8fused\"",
"# Same as above, but for the 4 bit version.",
"if",
"(",
"\"acc_ops.embedding_bag_4bit_rowwise_offsets\"",
"in",
"user_targets",
"and",
"str",
"(",
"user_targets",
"[",
"\"acc_ops.embedding_bag_4bit_rowwise_offsets\"",
"]",
".",
"kwargs",
"[",
"\"weight\"",
"]",
")",
"==",
"stripped_name",
")",
":",
"weight",
"[",
"stripped_name",
"]",
"[",
"\"dtype\"",
"]",
"=",
"\"acc.uint4fused\"",
"serialized_dict",
"[",
"\"weights\"",
"]",
".",
"update",
"(",
"weight",
")",
"else",
":",
"# Find the actual target parameter/buffer from the fx_module.",
"submod_path",
",",
"_",
",",
"target_name",
"=",
"node",
".",
"target",
".",
"rpartition",
"(",
"\".\"",
")",
"submod",
":",
"Optional",
"[",
"torch",
".",
"nn",
".",
"Module",
"]",
"=",
"(",
"fx_module",
".",
"get_submodule",
"(",
"submod_path",
")",
"if",
"submod_path",
"else",
"fx_module",
")",
"assert",
"submod",
"is",
"not",
"None",
",",
"f\"submod {submod_path} not found\"",
"target",
"=",
"getattr",
"(",
"submod",
",",
"target_name",
",",
"None",
")",
"assert",
"target",
"is",
"not",
"None",
",",
"f\"{target_name} not an attr of {submod_path}\"",
"qualname",
"=",
"prefix",
"+",
"node",
".",
"target",
"# Check that the target is a tensor, and that we haven't added it already from a leaf module.",
"if",
"isinstance",
"(",
"target",
",",
"torch",
".",
"Tensor",
")",
"and",
"qualname",
"not",
"in",
"weights",
":",
"weight",
"=",
"serialize_weight",
"(",
"target",
",",
"weights",
",",
"qualname",
")",
"serialized_dict",
"[",
"\"weights\"",
"]",
".",
"update",
"(",
"weight",
")",
"weights",
"[",
"qualname",
"]",
"=",
"target",
"node_rep",
"[",
"\"op_code\"",
"]",
"=",
"node",
".",
"op",
"node_rep",
"[",
"\"name\"",
"]",
"=",
"node",
".",
"name",
"def",
"get_user_info",
"(",
"user_node",
":",
"Argument",
")",
"->",
"Any",
":",
"return",
"{",
"\"is_node\"",
":",
"True",
",",
"\"name\"",
":",
"str",
"(",
"user_node",
")",
"}",
"def",
"get_arg_info",
"(",
"arg",
":",
"Argument",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"arg",
",",
"torch",
".",
"fx",
".",
"Node",
")",
":",
"return",
"{",
"\"is_node\"",
":",
"True",
",",
"\"name\"",
":",
"str",
"(",
"arg",
")",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"(",
"torch",
".",
"dtype",
",",
"torch",
".",
"memory_format",
",",
"torch",
".",
"qscheme",
")",
")",
":",
"return",
"str",
"(",
"arg",
")",
"else",
":",
"return",
"arg",
"def",
"get_output_arg_info",
"(",
"arg",
":",
"Node",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"node_rep",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"get_arg_info",
"(",
"arg",
")",
"node_rep",
".",
"update",
"(",
"get_node_info",
"(",
"arg",
")",
")",
"return",
"node_rep",
"if",
"node",
".",
"op",
"==",
"\"output\"",
":",
"node_rep",
"[",
"\"args\"",
"]",
"=",
"map_arg",
"(",
"node",
".",
"args",
",",
"get_output_arg_info",
",",
")",
"# If there're multiple outputs then node_rep[\"args\"][0] will be a tuple.",
"# In this case we want to unpack the tuple.",
"if",
"isinstance",
"(",
"node_rep",
"[",
"\"args\"",
"]",
"[",
"0",
"]",
",",
"tuple",
")",
":",
"node_rep",
"[",
"\"args\"",
"]",
"=",
"node_rep",
"[",
"\"args\"",
"]",
"[",
"0",
"]",
"else",
":",
"node_rep",
"[",
"\"args\"",
"]",
"=",
"map_aggregate",
"(",
"node",
".",
"args",
",",
"get_arg_info",
")",
"node_rep",
"[",
"\"kwargs\"",
"]",
"=",
"map_aggregate",
"(",
"node",
".",
"kwargs",
",",
"get_arg_info",
")",
"node_rep",
"[",
"\"users\"",
"]",
"=",
"map_aggregate",
"(",
"list",
"(",
"node",
".",
"users",
".",
"keys",
"(",
")",
")",
",",
"get_user_info",
")",
"serialized_dict",
"[",
"\"nodes\"",
"]",
"+=",
"[",
"node_rep",
"]",
"return",
"serialized_dict"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/passes/graph_manipulation.py#L248-L465 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Sizer.GetItemCount | (*args, **kwargs) | return _core_.Sizer_GetItemCount(*args, **kwargs) | GetItemCount(self) -> size_t | GetItemCount(self) -> size_t | [
"GetItemCount",
"(",
"self",
")",
"-",
">",
"size_t"
] | def GetItemCount(*args, **kwargs):
"""GetItemCount(self) -> size_t"""
return _core_.Sizer_GetItemCount(*args, **kwargs) | [
"def",
"GetItemCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Sizer_GetItemCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L14756-L14758 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py | python | RawTurtle.setundobuffer | (self, size) | Set or disable undobuffer.
Argument:
size -- an integer or None
If size is an integer an empty undobuffer of given size is installed.
Size gives the maximum number of turtle-actions that can be undone
by the undo() function.
If size is None, no undobuffer is present.
Example (for a Turtle instance named turtle):
>>> turtle.setundobuffer(42) | Set or disable undobuffer. | [
"Set",
"or",
"disable",
"undobuffer",
"."
] | def setundobuffer(self, size):
"""Set or disable undobuffer.
Argument:
size -- an integer or None
If size is an integer an empty undobuffer of given size is installed.
Size gives the maximum number of turtle-actions that can be undone
by the undo() function.
If size is None, no undobuffer is present.
Example (for a Turtle instance named turtle):
>>> turtle.setundobuffer(42)
"""
if size is None:
self.undobuffer = None
else:
self.undobuffer = Tbuffer(size) | [
"def",
"setundobuffer",
"(",
"self",
",",
"size",
")",
":",
"if",
"size",
"is",
"None",
":",
"self",
".",
"undobuffer",
"=",
"None",
"else",
":",
"self",
".",
"undobuffer",
"=",
"Tbuffer",
"(",
"size",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L2488-L2505 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/internetcontent/nv_python_libs/hulu/hulu_api.py | python | Videos.searchTitle | (self, title, pagenumber, pagelen) | return [itemDict, morePages] | Key word video search of the Hulu web site
return an array of matching item elements
return | Key word video search of the Hulu web site
return an array of matching item elements
return | [
"Key",
"word",
"video",
"search",
"of",
"the",
"Hulu",
"web",
"site",
"return",
"an",
"array",
"of",
"matching",
"item",
"elements",
"return"
] | def searchTitle(self, title, pagenumber, pagelen):
'''Key word video search of the Hulu web site
return an array of matching item elements
return
'''
# Save the origninal URL
orgUrl = self.hulu_config.find('searchURLS').xpath(".//href")[0].text
url = self.hulu_config.find('searchURLS').xpath(".//href")[0].text.replace('PAGENUM', str(pagenumber)).replace('SEARCHTERM', urllib.parse.quote_plus(title.encode("utf-8")))
if self.config['debug_enabled']:
print(url)
print()
self.hulu_config.find('searchURLS').xpath(".//href")[0].text = url
# Perform a search
try:
resultTree = self.common.getUrlData(self.hulu_config.find('searchURLS'))
except Exception as errormsg:
# Restore the origninal URL
self.hulu_config.find('searchURLS').xpath(".//href")[0].text = orgUrl
raise HuluUrlDownloadError(self.error_messages['HuluUrlDownloadError'] % (errormsg))
# Restore the origninal URL
self.hulu_config.find('searchURLS').xpath(".//href")[0].text = orgUrl
if resultTree is None:
raise HuluVideoNotFound("No Hulu Video matches found for search value (%s)" % title)
searchResults = resultTree.xpath('//result//a[@href!="#"]')
if not len(searchResults):
raise HuluVideoNotFound("No Hulu Video matches found for search value (%s)" % title)
if self.config['debug_enabled']:
print("resultTree: count(%s)" % len(searchResults))
print()
# Hulu search results do not have a pubDate so use the current data time
# e.g. "Sun, 06 Jan 2008 21:44:36 GMT"
pubDate = datetime.datetime.now().strftime(self.common.pubDateFormat)
# Translate the search results into MNV RSS item format
titleFilter = etree.XPath(".//img")
thumbnailFilter = etree.XPath(".//img")
itemLink = etree.XPath('.//media:content', namespaces=self.common.namespaces)
itemThumbnail = etree.XPath('.//media:thumbnail', namespaces=self.common.namespaces)
itemDict = {}
for result in searchResults:
tmpLink = result.attrib['href']
if not tmpLink: # Make sure that this result actually has a video
continue
huluItem = etree.XML(self.common.mnvItem)
# Extract and massage data
link = self.common.ampReplace(tmpLink)
tmpTitleText = titleFilter(result)[0].attrib['alt'].strip()
tmpList = tmpTitleText.split(':')
title = self.common.massageText(tmpList[0].strip())
if len(tmpList) > 1:
description = self.common.massageText(tmpList[1].strip())
else:
description = ''
# Insert data into a new item element
huluItem.find('title').text = title
huluItem.find('author').text = 'Hulu'
huluItem.find('pubDate').text = pubDate
huluItem.find('description').text = description
huluItem.find('link').text = link
itemThumbnail(huluItem)[0].attrib['url'] = self.common.ampReplace(thumbnailFilter(result)[0].attrib['src'])
itemLink(huluItem)[0].attrib['url'] = link
etree.SubElement(huluItem, "{http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format}country").text = 'us'
s_e = self.getSeasonEpisode(title, description, itemThumbnail(huluItem)[0].attrib['url'])
if s_e[0]:
etree.SubElement(huluItem, "{http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format}season").text = s_e[0]
if s_e[1]:
etree.SubElement(huluItem, "{http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format}episode").text = s_e[1]
if not title and s_e[2]:
huluItem.find('title').text = s_e[2]
itemDict[link] = huluItem
if not len(list(itemDict.keys())):
raise HuluVideoNotFound("No Hulu Video matches found for search value (%s)" % title)
# Set the number of search results returned
self.channel['channel_numresults'] = len(itemDict)
# Check if there are any more pages
lastPage = resultTree.xpath('//result//a[@alt="Go to the last page"]')
morePages = False
if len(lastPage):
try:
if pagenumber < lastPage[0].text:
morePages = True
except:
pass
return [itemDict, morePages] | [
"def",
"searchTitle",
"(",
"self",
",",
"title",
",",
"pagenumber",
",",
"pagelen",
")",
":",
"# Save the origninal URL",
"orgUrl",
"=",
"self",
".",
"hulu_config",
".",
"find",
"(",
"'searchURLS'",
")",
".",
"xpath",
"(",
"\".//href\"",
")",
"[",
"0",
"]",
".",
"text",
"url",
"=",
"self",
".",
"hulu_config",
".",
"find",
"(",
"'searchURLS'",
")",
".",
"xpath",
"(",
"\".//href\"",
")",
"[",
"0",
"]",
".",
"text",
".",
"replace",
"(",
"'PAGENUM'",
",",
"str",
"(",
"pagenumber",
")",
")",
".",
"replace",
"(",
"'SEARCHTERM'",
",",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"title",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
")",
"if",
"self",
".",
"config",
"[",
"'debug_enabled'",
"]",
":",
"print",
"(",
"url",
")",
"print",
"(",
")",
"self",
".",
"hulu_config",
".",
"find",
"(",
"'searchURLS'",
")",
".",
"xpath",
"(",
"\".//href\"",
")",
"[",
"0",
"]",
".",
"text",
"=",
"url",
"# Perform a search",
"try",
":",
"resultTree",
"=",
"self",
".",
"common",
".",
"getUrlData",
"(",
"self",
".",
"hulu_config",
".",
"find",
"(",
"'searchURLS'",
")",
")",
"except",
"Exception",
"as",
"errormsg",
":",
"# Restore the origninal URL",
"self",
".",
"hulu_config",
".",
"find",
"(",
"'searchURLS'",
")",
".",
"xpath",
"(",
"\".//href\"",
")",
"[",
"0",
"]",
".",
"text",
"=",
"orgUrl",
"raise",
"HuluUrlDownloadError",
"(",
"self",
".",
"error_messages",
"[",
"'HuluUrlDownloadError'",
"]",
"%",
"(",
"errormsg",
")",
")",
"# Restore the origninal URL",
"self",
".",
"hulu_config",
".",
"find",
"(",
"'searchURLS'",
")",
".",
"xpath",
"(",
"\".//href\"",
")",
"[",
"0",
"]",
".",
"text",
"=",
"orgUrl",
"if",
"resultTree",
"is",
"None",
":",
"raise",
"HuluVideoNotFound",
"(",
"\"No Hulu Video matches found for search value (%s)\"",
"%",
"title",
")",
"searchResults",
"=",
"resultTree",
".",
"xpath",
"(",
"'//result//a[@href!=\"#\"]'",
")",
"if",
"not",
"len",
"(",
"searchResults",
")",
":",
"raise",
"HuluVideoNotFound",
"(",
"\"No Hulu Video matches found for search value (%s)\"",
"%",
"title",
")",
"if",
"self",
".",
"config",
"[",
"'debug_enabled'",
"]",
":",
"print",
"(",
"\"resultTree: count(%s)\"",
"%",
"len",
"(",
"searchResults",
")",
")",
"print",
"(",
")",
"# Hulu search results do not have a pubDate so use the current data time",
"# e.g. \"Sun, 06 Jan 2008 21:44:36 GMT\"",
"pubDate",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"self",
".",
"common",
".",
"pubDateFormat",
")",
"# Translate the search results into MNV RSS item format",
"titleFilter",
"=",
"etree",
".",
"XPath",
"(",
"\".//img\"",
")",
"thumbnailFilter",
"=",
"etree",
".",
"XPath",
"(",
"\".//img\"",
")",
"itemLink",
"=",
"etree",
".",
"XPath",
"(",
"'.//media:content'",
",",
"namespaces",
"=",
"self",
".",
"common",
".",
"namespaces",
")",
"itemThumbnail",
"=",
"etree",
".",
"XPath",
"(",
"'.//media:thumbnail'",
",",
"namespaces",
"=",
"self",
".",
"common",
".",
"namespaces",
")",
"itemDict",
"=",
"{",
"}",
"for",
"result",
"in",
"searchResults",
":",
"tmpLink",
"=",
"result",
".",
"attrib",
"[",
"'href'",
"]",
"if",
"not",
"tmpLink",
":",
"# Make sure that this result actually has a video",
"continue",
"huluItem",
"=",
"etree",
".",
"XML",
"(",
"self",
".",
"common",
".",
"mnvItem",
")",
"# Extract and massage data",
"link",
"=",
"self",
".",
"common",
".",
"ampReplace",
"(",
"tmpLink",
")",
"tmpTitleText",
"=",
"titleFilter",
"(",
"result",
")",
"[",
"0",
"]",
".",
"attrib",
"[",
"'alt'",
"]",
".",
"strip",
"(",
")",
"tmpList",
"=",
"tmpTitleText",
".",
"split",
"(",
"':'",
")",
"title",
"=",
"self",
".",
"common",
".",
"massageText",
"(",
"tmpList",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
"if",
"len",
"(",
"tmpList",
")",
">",
"1",
":",
"description",
"=",
"self",
".",
"common",
".",
"massageText",
"(",
"tmpList",
"[",
"1",
"]",
".",
"strip",
"(",
")",
")",
"else",
":",
"description",
"=",
"''",
"# Insert data into a new item element",
"huluItem",
".",
"find",
"(",
"'title'",
")",
".",
"text",
"=",
"title",
"huluItem",
".",
"find",
"(",
"'author'",
")",
".",
"text",
"=",
"'Hulu'",
"huluItem",
".",
"find",
"(",
"'pubDate'",
")",
".",
"text",
"=",
"pubDate",
"huluItem",
".",
"find",
"(",
"'description'",
")",
".",
"text",
"=",
"description",
"huluItem",
".",
"find",
"(",
"'link'",
")",
".",
"text",
"=",
"link",
"itemThumbnail",
"(",
"huluItem",
")",
"[",
"0",
"]",
".",
"attrib",
"[",
"'url'",
"]",
"=",
"self",
".",
"common",
".",
"ampReplace",
"(",
"thumbnailFilter",
"(",
"result",
")",
"[",
"0",
"]",
".",
"attrib",
"[",
"'src'",
"]",
")",
"itemLink",
"(",
"huluItem",
")",
"[",
"0",
"]",
".",
"attrib",
"[",
"'url'",
"]",
"=",
"link",
"etree",
".",
"SubElement",
"(",
"huluItem",
",",
"\"{http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format}country\"",
")",
".",
"text",
"=",
"'us'",
"s_e",
"=",
"self",
".",
"getSeasonEpisode",
"(",
"title",
",",
"description",
",",
"itemThumbnail",
"(",
"huluItem",
")",
"[",
"0",
"]",
".",
"attrib",
"[",
"'url'",
"]",
")",
"if",
"s_e",
"[",
"0",
"]",
":",
"etree",
".",
"SubElement",
"(",
"huluItem",
",",
"\"{http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format}season\"",
")",
".",
"text",
"=",
"s_e",
"[",
"0",
"]",
"if",
"s_e",
"[",
"1",
"]",
":",
"etree",
".",
"SubElement",
"(",
"huluItem",
",",
"\"{http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format}episode\"",
")",
".",
"text",
"=",
"s_e",
"[",
"1",
"]",
"if",
"not",
"title",
"and",
"s_e",
"[",
"2",
"]",
":",
"huluItem",
".",
"find",
"(",
"'title'",
")",
".",
"text",
"=",
"s_e",
"[",
"2",
"]",
"itemDict",
"[",
"link",
"]",
"=",
"huluItem",
"if",
"not",
"len",
"(",
"list",
"(",
"itemDict",
".",
"keys",
"(",
")",
")",
")",
":",
"raise",
"HuluVideoNotFound",
"(",
"\"No Hulu Video matches found for search value (%s)\"",
"%",
"title",
")",
"# Set the number of search results returned",
"self",
".",
"channel",
"[",
"'channel_numresults'",
"]",
"=",
"len",
"(",
"itemDict",
")",
"# Check if there are any more pages",
"lastPage",
"=",
"resultTree",
".",
"xpath",
"(",
"'//result//a[@alt=\"Go to the last page\"]'",
")",
"morePages",
"=",
"False",
"if",
"len",
"(",
"lastPage",
")",
":",
"try",
":",
"if",
"pagenumber",
"<",
"lastPage",
"[",
"0",
"]",
".",
"text",
":",
"morePages",
"=",
"True",
"except",
":",
"pass",
"return",
"[",
"itemDict",
",",
"morePages",
"]"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/hulu/hulu_api.py#L271-L368 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/format/policy_templates/writers/doc_writer.py | python | DocWriter._AddDictionaryExampleAndroidLinux | (self, parent, policy) | Adds an example value for Android/Linux of a 'dict' policy to a DOM node.
Args:
parent: The DOM node for which the example will be added.
policy: A policy of type 'dict', for which the Android/Linux example value
is generated. | Adds an example value for Android/Linux of a 'dict' policy to a DOM node. | [
"Adds",
"an",
"example",
"value",
"for",
"Android",
"/",
"Linux",
"of",
"a",
"dict",
"policy",
"to",
"a",
"DOM",
"node",
"."
] | def _AddDictionaryExampleAndroidLinux(self, parent, policy):
'''Adds an example value for Android/Linux of a 'dict' policy to a DOM node.
Args:
parent: The DOM node for which the example will be added.
policy: A policy of type 'dict', for which the Android/Linux example value
is generated.
'''
self.AddElement(parent, 'dt', {}, 'Android/Linux:')
element = self._AddStyledElement(parent, 'dd', ['.monospace'])
example = json.dumps(policy['example_value'])
self.AddText(element, '%s: %s' % (policy['name'], example)) | [
"def",
"_AddDictionaryExampleAndroidLinux",
"(",
"self",
",",
"parent",
",",
"policy",
")",
":",
"self",
".",
"AddElement",
"(",
"parent",
",",
"'dt'",
",",
"{",
"}",
",",
"'Android/Linux:'",
")",
"element",
"=",
"self",
".",
"_AddStyledElement",
"(",
"parent",
",",
"'dd'",
",",
"[",
"'.monospace'",
"]",
")",
"example",
"=",
"json",
".",
"dumps",
"(",
"policy",
"[",
"'example_value'",
"]",
")",
"self",
".",
"AddText",
"(",
"element",
",",
"'%s: %s'",
"%",
"(",
"policy",
"[",
"'name'",
"]",
",",
"example",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/policy_templates/writers/doc_writer.py#L317-L328 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py | python | SuperplotPresenter.on_workspace_renamed | (self, old_name, new_name) | Triggered when the model reports a workspace renaming.
Args:
old_name (str): old name of the workspace
new_name (str): new name of the workspace | Triggered when the model reports a workspace renaming. | [
"Triggered",
"when",
"the",
"model",
"reports",
"a",
"workspace",
"renaming",
"."
] | def on_workspace_renamed(self, old_name, new_name):
"""
Triggered when the model reports a workspace renaming.
Args:
old_name (str): old name of the workspace
new_name (str): new name of the workspace
"""
selection = self._view.get_selection()
if old_name in selection:
selection[new_name] = selection[old_name]
del selection[old_name]
self._update_list()
self._view.set_selection(selection)
self._update_plot() | [
"def",
"on_workspace_renamed",
"(",
"self",
",",
"old_name",
",",
"new_name",
")",
":",
"selection",
"=",
"self",
".",
"_view",
".",
"get_selection",
"(",
")",
"if",
"old_name",
"in",
"selection",
":",
"selection",
"[",
"new_name",
"]",
"=",
"selection",
"[",
"old_name",
"]",
"del",
"selection",
"[",
"old_name",
"]",
"self",
".",
"_update_list",
"(",
")",
"self",
".",
"_view",
".",
"set_selection",
"(",
"selection",
")",
"self",
".",
"_update_plot",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py#L584-L598 | ||
ros-planning/moveit2 | dd240ef6fd8b9932a7a53964140f2952786187a9 | moveit_commander/src/moveit_commander/move_group.py | python | MoveGroupCommander.set_workspace | (self, ws) | Set the workspace for the robot as either [], [minX, minY, maxX, maxY] or [minX, minY, minZ, maxX, maxY, maxZ] | Set the workspace for the robot as either [], [minX, minY, maxX, maxY] or [minX, minY, minZ, maxX, maxY, maxZ] | [
"Set",
"the",
"workspace",
"for",
"the",
"robot",
"as",
"either",
"[]",
"[",
"minX",
"minY",
"maxX",
"maxY",
"]",
"or",
"[",
"minX",
"minY",
"minZ",
"maxX",
"maxY",
"maxZ",
"]"
] | def set_workspace(self, ws):
""" Set the workspace for the robot as either [], [minX, minY, maxX, maxY] or [minX, minY, minZ, maxX, maxY, maxZ] """
if len(ws) == 0:
self._g.set_workspace(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
else:
if len(ws) == 4:
self._g.set_workspace(ws[0], ws[1], 0.0, ws[2], ws[3], 0.0)
else:
if len(ws) == 6:
self._g.set_workspace(ws[0], ws[1], ws[2], ws[3], ws[4], ws[5])
else:
raise MoveItCommanderException(
"Expected 0, 4 or 6 values in list specifying workspace"
) | [
"def",
"set_workspace",
"(",
"self",
",",
"ws",
")",
":",
"if",
"len",
"(",
"ws",
")",
"==",
"0",
":",
"self",
".",
"_g",
".",
"set_workspace",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
")",
"else",
":",
"if",
"len",
"(",
"ws",
")",
"==",
"4",
":",
"self",
".",
"_g",
".",
"set_workspace",
"(",
"ws",
"[",
"0",
"]",
",",
"ws",
"[",
"1",
"]",
",",
"0.0",
",",
"ws",
"[",
"2",
"]",
",",
"ws",
"[",
"3",
"]",
",",
"0.0",
")",
"else",
":",
"if",
"len",
"(",
"ws",
")",
"==",
"6",
":",
"self",
".",
"_g",
".",
"set_workspace",
"(",
"ws",
"[",
"0",
"]",
",",
"ws",
"[",
"1",
"]",
",",
"ws",
"[",
"2",
"]",
",",
"ws",
"[",
"3",
"]",
",",
"ws",
"[",
"4",
"]",
",",
"ws",
"[",
"5",
"]",
")",
"else",
":",
"raise",
"MoveItCommanderException",
"(",
"\"Expected 0, 4 or 6 values in list specifying workspace\"",
")"
] | https://github.com/ros-planning/moveit2/blob/dd240ef6fd8b9932a7a53964140f2952786187a9/moveit_commander/src/moveit_commander/move_group.py#L556-L569 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/ParseTreeTransforms.py | python | AnalyseDeclarationsTransform._handle_fused_def_decorators | (self, old_decorators, env, node) | return node | Create function calls to the decorators and reassignments to
the function. | Create function calls to the decorators and reassignments to
the function. | [
"Create",
"function",
"calls",
"to",
"the",
"decorators",
"and",
"reassignments",
"to",
"the",
"function",
"."
] | def _handle_fused_def_decorators(self, old_decorators, env, node):
"""
Create function calls to the decorators and reassignments to
the function.
"""
# Delete staticmethod and classmethod decorators, this is
# handled directly by the fused function object.
decorators = []
for decorator in old_decorators:
func = decorator.decorator
if (not func.is_name or
func.name not in ('staticmethod', 'classmethod') or
env.lookup_here(func.name)):
# not a static or classmethod
decorators.append(decorator)
if decorators:
transform = DecoratorTransform(self.context)
def_node = node.node
_, reassignments = transform.chain_decorators(
def_node, decorators, def_node.name)
reassignments.analyse_declarations(env)
node = [node, reassignments]
return node | [
"def",
"_handle_fused_def_decorators",
"(",
"self",
",",
"old_decorators",
",",
"env",
",",
"node",
")",
":",
"# Delete staticmethod and classmethod decorators, this is",
"# handled directly by the fused function object.",
"decorators",
"=",
"[",
"]",
"for",
"decorator",
"in",
"old_decorators",
":",
"func",
"=",
"decorator",
".",
"decorator",
"if",
"(",
"not",
"func",
".",
"is_name",
"or",
"func",
".",
"name",
"not",
"in",
"(",
"'staticmethod'",
",",
"'classmethod'",
")",
"or",
"env",
".",
"lookup_here",
"(",
"func",
".",
"name",
")",
")",
":",
"# not a static or classmethod",
"decorators",
".",
"append",
"(",
"decorator",
")",
"if",
"decorators",
":",
"transform",
"=",
"DecoratorTransform",
"(",
"self",
".",
"context",
")",
"def_node",
"=",
"node",
".",
"node",
"_",
",",
"reassignments",
"=",
"transform",
".",
"chain_decorators",
"(",
"def_node",
",",
"decorators",
",",
"def_node",
".",
"name",
")",
"reassignments",
".",
"analyse_declarations",
"(",
"env",
")",
"node",
"=",
"[",
"node",
",",
"reassignments",
"]",
"return",
"node"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/ParseTreeTransforms.py#L1772-L1796 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Wm.wm_minsize | (self, width=None, height=None) | return self._getints(self.tk.call(
'wm', 'minsize', self._w, width, height)) | Set min WIDTH and HEIGHT for this widget. If the window is gridded
the values are given in grid units. Return the current values if None
is given. | Set min WIDTH and HEIGHT for this widget. If the window is gridded
the values are given in grid units. Return the current values if None
is given. | [
"Set",
"min",
"WIDTH",
"and",
"HEIGHT",
"for",
"this",
"widget",
".",
"If",
"the",
"window",
"is",
"gridded",
"the",
"values",
"are",
"given",
"in",
"grid",
"units",
".",
"Return",
"the",
"current",
"values",
"if",
"None",
"is",
"given",
"."
] | def wm_minsize(self, width=None, height=None):
"""Set min WIDTH and HEIGHT for this widget. If the window is gridded
the values are given in grid units. Return the current values if None
is given."""
return self._getints(self.tk.call(
'wm', 'minsize', self._w, width, height)) | [
"def",
"wm_minsize",
"(",
"self",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'wm'",
",",
"'minsize'",
",",
"self",
".",
"_w",
",",
"width",
",",
"height",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1658-L1663 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiPaneInfo.dock_direction_set | (self, value) | Setter for the `dock_direction`.
:param integer `value`: the docking direction. This can be one of the following bits:
============================ ======= =============================================
Dock Flag Value Description
============================ ======= =============================================
``AUI_DOCK_NONE`` 0 No docking direction.
``AUI_DOCK_TOP`` 1 Top docking direction.
``AUI_DOCK_RIGHT`` 2 Right docking direction.
``AUI_DOCK_BOTTOM`` 3 Bottom docking direction.
``AUI_DOCK_LEFT`` 4 Left docking direction.
``AUI_DOCK_CENTER`` 5 Center docking direction.
``AUI_DOCK_CENTRE`` 5 Centre docking direction.
``AUI_DOCK_NOTEBOOK_PAGE`` 6 Automatic AuiNotebooks docking style.
============================ ======= ============================================= | Setter for the `dock_direction`. | [
"Setter",
"for",
"the",
"dock_direction",
"."
] | def dock_direction_set(self, value):
"""
Setter for the `dock_direction`.
:param integer `value`: the docking direction. This can be one of the following bits:
============================ ======= =============================================
Dock Flag Value Description
============================ ======= =============================================
``AUI_DOCK_NONE`` 0 No docking direction.
``AUI_DOCK_TOP`` 1 Top docking direction.
``AUI_DOCK_RIGHT`` 2 Right docking direction.
``AUI_DOCK_BOTTOM`` 3 Bottom docking direction.
``AUI_DOCK_LEFT`` 4 Left docking direction.
``AUI_DOCK_CENTER`` 5 Center docking direction.
``AUI_DOCK_CENTRE`` 5 Centre docking direction.
``AUI_DOCK_NOTEBOOK_PAGE`` 6 Automatic AuiNotebooks docking style.
============================ ======= =============================================
"""
self._dock_direction = value | [
"def",
"dock_direction_set",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_dock_direction",
"=",
"value"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L568-L589 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/PyShell.py | python | ModifiedInterpreter.open_remote_stack_viewer | (self) | return | Initiate the remote stack viewer from a separate thread.
This method is called from the subprocess, and by returning from this
method we allow the subprocess to unblock. After a bit the shell
requests the subprocess to open the remote stack viewer which returns a
static object looking at the last exception. It is queried through
the RPC mechanism. | Initiate the remote stack viewer from a separate thread. | [
"Initiate",
"the",
"remote",
"stack",
"viewer",
"from",
"a",
"separate",
"thread",
"."
] | def open_remote_stack_viewer(self):
"""Initiate the remote stack viewer from a separate thread.
This method is called from the subprocess, and by returning from this
method we allow the subprocess to unblock. After a bit the shell
requests the subprocess to open the remote stack viewer which returns a
static object looking at the last exception. It is queried through
the RPC mechanism.
"""
self.tkconsole.text.after(300, self.remote_stack_viewer)
return | [
"def",
"open_remote_stack_viewer",
"(",
"self",
")",
":",
"self",
".",
"tkconsole",
".",
"text",
".",
"after",
"(",
"300",
",",
"self",
".",
"remote_stack_viewer",
")",
"return"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/PyShell.py#L583-L594 | |
bristolcrypto/SPDZ-2 | 721abfae849625a02ea49aabc534f9cf41ca643f | Compiler/oram.py | python | TreeORAM.batch_init | (self, values) | Batch initalization. Obliviously shuffles and adds N entries to
random leaf buckets. | Batch initalization. Obliviously shuffles and adds N entries to
random leaf buckets. | [
"Batch",
"initalization",
".",
"Obliviously",
"shuffles",
"and",
"adds",
"N",
"entries",
"to",
"random",
"leaf",
"buckets",
"."
] | def batch_init(self, values):
""" Batch initalization. Obliviously shuffles and adds N entries to
random leaf buckets. """
m = len(values)
assert((m & (m-1)) == 0)
if m != self.size:
raise CompilerError('Batch initialization must have N values.')
if self.value_type != sint:
raise CompilerError('Batch initialization only possible with sint.')
depth = log2(m)
leaves = [0] * m
entries = [0] * m
indexed_values = [0] * m
# assign indices 0, ..., m-1
for i,value in enumerate(values):
index = MemValue(self.value_type.hard_conv(i))
new_value = [MemValue(self.value_type.hard_conv(v)) \
for v in (value if isinstance(value, (tuple, list)) \
else (value,))]
indexed_values[i] = [index] + new_value
# assign leaves
for i,index_value in enumerate(indexed_values):
leaves[i] = random_block(self.D, self.value_type)
index = index_value[0]
value = [leaves[i]] + index_value[1:]
entries[i] = Entry(index, value, \
self.value_type.hard_conv(False), value_type=self.value_type)
# save unsorted leaves for position map
unsorted_leaves = [MemValue(self.value_type(leaf)) for leaf in leaves]
permutation.sort(leaves, comp=permutation.normal_comparator)
bucket_sz = 0
# B[i] = (pos, leaf, "last in bucket" flag) for i-th entry
B = [[0]*3 for i in range(m)]
B[0] = [0, leaves[0], 0]
B[-1] = [None, None, sint(1)]
s = 0
for i in range(1, m):
eq = leaves[i].equal(leaves[i-1])
s = (s + eq) * eq
B[i][0] = s
B[i][1] = leaves[i]
B[i-1][2] = 1 - eq
#pos[i] = [s, leaves[i]]
#last_in_bucket[i-1] = 1 - eq
# shuffle
permutation.shuffle(B, value_type=sint)
#cint(0).print_reg('shuf')
sz = MemValue(0) #cint(0)
nleaves = 2**self.D
empty_positions = Array(nleaves, self.value_type)
empty_leaves = Array(nleaves, self.value_type)
for i in range(m):
if_then(reveal(B[i][2]))
#if B[i][2] == 1:
#cint(i).print_reg('last')
if isinstance(sz, int):
szval = sz
else:
szval = sz.read()
#szval.print_reg('sz')
empty_positions[szval] = B[i][0] #pos[i][0]
#empty_positions[szval].reveal().print_reg('ps0')
empty_leaves[szval] = B[i][1] #pos[i][1]
sz += 1
end_if()
pos_bits = []
for i in range(nleaves):
leaf = empty_leaves[i]
# split into 2 if bucket size can't fit into one field elem
if self.bucket_size + Program.prog.security > 128:
parity = (empty_positions[i]+1) % 2
half = (empty_positions[i]+1 - parity) / 2
half_max = self.bucket_size / 2
bits = floatingpoint.B2U(half, half_max, Program.prog.security)[0]
bits2 = floatingpoint.B2U(half+parity, half_max, Program.prog.security)[0]
# (doesn't work)
#bits2 = [0] * half_max
## second half with parity bit
#for j in range(half_max-1, 0, -1):
# bits2[j] = bits[j] + (bits[j-1] - bits[j]) * parity
#bits2[0] = (1 - bits[0]) * parity
bucket_bits = [b for sl in zip(bits2,bits) for b in sl]
else:
bucket_bits = floatingpoint.B2U(empty_positions[i]+1, self.bucket_size, Program.prog.security)[0]
pos_bits += [[b, leaf] for b in bucket_bits]
# sort to get empty positions first
permutation.sort(pos_bits, comp=permutation.bitwise_list_comparator)
# now assign positions to empty entries
empty_entries = [0] * (self.bucket_size*2**self.D - m)
for i in range(self.bucket_size*2**self.D - m):
vtype, vlength = self.internal_value_type()
leaf = vtype(pos_bits[i][1])
# set leaf in empty entry for assigning after shuffle
value = tuple([leaf] + [vtype(0) for j in range(vlength)])
entry = Entry(vtype(0), value, vtype.hard_conv(True), vtype)
empty_entries[i] = entry
# now shuffle, reveal positions and place entries
entries = entries + empty_entries
while len(entries) & (len(entries)-1) != 0:
entries.append(None)
permutation.shuffle(entries, value_type=sint)
entries = [entry for entry in entries if entry is not None]
clear_leaves = [MemValue(entry.x[0].reveal()) for entry in entries]
Program.prog.curr_tape.start_new_basicblock()
bucket_sizes = Array(2**self.D, regint)
for i in range(2**self.D):
bucket_sizes[i] = 0
k = 0
for entry,leaf in zip(entries, clear_leaves):
leaf = leaf.read()
k += 1
# for some reason leaf_buckets is in bit-reversed order
bits = bit_decompose(leaf, self.D)
rev_leaf = sum(b*2**i for i,b in enumerate(bits[::-1]))
bucket = RefBucket(rev_leaf + (1 << self.D), self)
# hack: 1*entry ensures MemValues are converted to sints
bucket.bucket.ram[bucket_sizes[leaf]] = 1*entry
bucket_sizes[leaf] += 1
self.index.batch_init([leaf.read() for leaf in unsorted_leaves]) | [
"def",
"batch_init",
"(",
"self",
",",
"values",
")",
":",
"m",
"=",
"len",
"(",
"values",
")",
"assert",
"(",
"(",
"m",
"&",
"(",
"m",
"-",
"1",
")",
")",
"==",
"0",
")",
"if",
"m",
"!=",
"self",
".",
"size",
":",
"raise",
"CompilerError",
"(",
"'Batch initialization must have N values.'",
")",
"if",
"self",
".",
"value_type",
"!=",
"sint",
":",
"raise",
"CompilerError",
"(",
"'Batch initialization only possible with sint.'",
")",
"depth",
"=",
"log2",
"(",
"m",
")",
"leaves",
"=",
"[",
"0",
"]",
"*",
"m",
"entries",
"=",
"[",
"0",
"]",
"*",
"m",
"indexed_values",
"=",
"[",
"0",
"]",
"*",
"m",
"# assign indices 0, ..., m-1",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"values",
")",
":",
"index",
"=",
"MemValue",
"(",
"self",
".",
"value_type",
".",
"hard_conv",
"(",
"i",
")",
")",
"new_value",
"=",
"[",
"MemValue",
"(",
"self",
".",
"value_type",
".",
"hard_conv",
"(",
"v",
")",
")",
"for",
"v",
"in",
"(",
"value",
"if",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
"else",
"(",
"value",
",",
")",
")",
"]",
"indexed_values",
"[",
"i",
"]",
"=",
"[",
"index",
"]",
"+",
"new_value",
"# assign leaves",
"for",
"i",
",",
"index_value",
"in",
"enumerate",
"(",
"indexed_values",
")",
":",
"leaves",
"[",
"i",
"]",
"=",
"random_block",
"(",
"self",
".",
"D",
",",
"self",
".",
"value_type",
")",
"index",
"=",
"index_value",
"[",
"0",
"]",
"value",
"=",
"[",
"leaves",
"[",
"i",
"]",
"]",
"+",
"index_value",
"[",
"1",
":",
"]",
"entries",
"[",
"i",
"]",
"=",
"Entry",
"(",
"index",
",",
"value",
",",
"self",
".",
"value_type",
".",
"hard_conv",
"(",
"False",
")",
",",
"value_type",
"=",
"self",
".",
"value_type",
")",
"# save unsorted leaves for position map",
"unsorted_leaves",
"=",
"[",
"MemValue",
"(",
"self",
".",
"value_type",
"(",
"leaf",
")",
")",
"for",
"leaf",
"in",
"leaves",
"]",
"permutation",
".",
"sort",
"(",
"leaves",
",",
"comp",
"=",
"permutation",
".",
"normal_comparator",
")",
"bucket_sz",
"=",
"0",
"# B[i] = (pos, leaf, \"last in bucket\" flag) for i-th entry",
"B",
"=",
"[",
"[",
"0",
"]",
"*",
"3",
"for",
"i",
"in",
"range",
"(",
"m",
")",
"]",
"B",
"[",
"0",
"]",
"=",
"[",
"0",
",",
"leaves",
"[",
"0",
"]",
",",
"0",
"]",
"B",
"[",
"-",
"1",
"]",
"=",
"[",
"None",
",",
"None",
",",
"sint",
"(",
"1",
")",
"]",
"s",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"m",
")",
":",
"eq",
"=",
"leaves",
"[",
"i",
"]",
".",
"equal",
"(",
"leaves",
"[",
"i",
"-",
"1",
"]",
")",
"s",
"=",
"(",
"s",
"+",
"eq",
")",
"*",
"eq",
"B",
"[",
"i",
"]",
"[",
"0",
"]",
"=",
"s",
"B",
"[",
"i",
"]",
"[",
"1",
"]",
"=",
"leaves",
"[",
"i",
"]",
"B",
"[",
"i",
"-",
"1",
"]",
"[",
"2",
"]",
"=",
"1",
"-",
"eq",
"#pos[i] = [s, leaves[i]]",
"#last_in_bucket[i-1] = 1 - eq",
"# shuffle",
"permutation",
".",
"shuffle",
"(",
"B",
",",
"value_type",
"=",
"sint",
")",
"#cint(0).print_reg('shuf')",
"sz",
"=",
"MemValue",
"(",
"0",
")",
"#cint(0)",
"nleaves",
"=",
"2",
"**",
"self",
".",
"D",
"empty_positions",
"=",
"Array",
"(",
"nleaves",
",",
"self",
".",
"value_type",
")",
"empty_leaves",
"=",
"Array",
"(",
"nleaves",
",",
"self",
".",
"value_type",
")",
"for",
"i",
"in",
"range",
"(",
"m",
")",
":",
"if_then",
"(",
"reveal",
"(",
"B",
"[",
"i",
"]",
"[",
"2",
"]",
")",
")",
"#if B[i][2] == 1:",
"#cint(i).print_reg('last')",
"if",
"isinstance",
"(",
"sz",
",",
"int",
")",
":",
"szval",
"=",
"sz",
"else",
":",
"szval",
"=",
"sz",
".",
"read",
"(",
")",
"#szval.print_reg('sz')",
"empty_positions",
"[",
"szval",
"]",
"=",
"B",
"[",
"i",
"]",
"[",
"0",
"]",
"#pos[i][0]",
"#empty_positions[szval].reveal().print_reg('ps0')",
"empty_leaves",
"[",
"szval",
"]",
"=",
"B",
"[",
"i",
"]",
"[",
"1",
"]",
"#pos[i][1]",
"sz",
"+=",
"1",
"end_if",
"(",
")",
"pos_bits",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"nleaves",
")",
":",
"leaf",
"=",
"empty_leaves",
"[",
"i",
"]",
"# split into 2 if bucket size can't fit into one field elem",
"if",
"self",
".",
"bucket_size",
"+",
"Program",
".",
"prog",
".",
"security",
">",
"128",
":",
"parity",
"=",
"(",
"empty_positions",
"[",
"i",
"]",
"+",
"1",
")",
"%",
"2",
"half",
"=",
"(",
"empty_positions",
"[",
"i",
"]",
"+",
"1",
"-",
"parity",
")",
"/",
"2",
"half_max",
"=",
"self",
".",
"bucket_size",
"/",
"2",
"bits",
"=",
"floatingpoint",
".",
"B2U",
"(",
"half",
",",
"half_max",
",",
"Program",
".",
"prog",
".",
"security",
")",
"[",
"0",
"]",
"bits2",
"=",
"floatingpoint",
".",
"B2U",
"(",
"half",
"+",
"parity",
",",
"half_max",
",",
"Program",
".",
"prog",
".",
"security",
")",
"[",
"0",
"]",
"# (doesn't work)",
"#bits2 = [0] * half_max",
"## second half with parity bit ",
"#for j in range(half_max-1, 0, -1):",
"# bits2[j] = bits[j] + (bits[j-1] - bits[j]) * parity",
"#bits2[0] = (1 - bits[0]) * parity",
"bucket_bits",
"=",
"[",
"b",
"for",
"sl",
"in",
"zip",
"(",
"bits2",
",",
"bits",
")",
"for",
"b",
"in",
"sl",
"]",
"else",
":",
"bucket_bits",
"=",
"floatingpoint",
".",
"B2U",
"(",
"empty_positions",
"[",
"i",
"]",
"+",
"1",
",",
"self",
".",
"bucket_size",
",",
"Program",
".",
"prog",
".",
"security",
")",
"[",
"0",
"]",
"pos_bits",
"+=",
"[",
"[",
"b",
",",
"leaf",
"]",
"for",
"b",
"in",
"bucket_bits",
"]",
"# sort to get empty positions first",
"permutation",
".",
"sort",
"(",
"pos_bits",
",",
"comp",
"=",
"permutation",
".",
"bitwise_list_comparator",
")",
"# now assign positions to empty entries",
"empty_entries",
"=",
"[",
"0",
"]",
"*",
"(",
"self",
".",
"bucket_size",
"*",
"2",
"**",
"self",
".",
"D",
"-",
"m",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"bucket_size",
"*",
"2",
"**",
"self",
".",
"D",
"-",
"m",
")",
":",
"vtype",
",",
"vlength",
"=",
"self",
".",
"internal_value_type",
"(",
")",
"leaf",
"=",
"vtype",
"(",
"pos_bits",
"[",
"i",
"]",
"[",
"1",
"]",
")",
"# set leaf in empty entry for assigning after shuffle",
"value",
"=",
"tuple",
"(",
"[",
"leaf",
"]",
"+",
"[",
"vtype",
"(",
"0",
")",
"for",
"j",
"in",
"range",
"(",
"vlength",
")",
"]",
")",
"entry",
"=",
"Entry",
"(",
"vtype",
"(",
"0",
")",
",",
"value",
",",
"vtype",
".",
"hard_conv",
"(",
"True",
")",
",",
"vtype",
")",
"empty_entries",
"[",
"i",
"]",
"=",
"entry",
"# now shuffle, reveal positions and place entries",
"entries",
"=",
"entries",
"+",
"empty_entries",
"while",
"len",
"(",
"entries",
")",
"&",
"(",
"len",
"(",
"entries",
")",
"-",
"1",
")",
"!=",
"0",
":",
"entries",
".",
"append",
"(",
"None",
")",
"permutation",
".",
"shuffle",
"(",
"entries",
",",
"value_type",
"=",
"sint",
")",
"entries",
"=",
"[",
"entry",
"for",
"entry",
"in",
"entries",
"if",
"entry",
"is",
"not",
"None",
"]",
"clear_leaves",
"=",
"[",
"MemValue",
"(",
"entry",
".",
"x",
"[",
"0",
"]",
".",
"reveal",
"(",
")",
")",
"for",
"entry",
"in",
"entries",
"]",
"Program",
".",
"prog",
".",
"curr_tape",
".",
"start_new_basicblock",
"(",
")",
"bucket_sizes",
"=",
"Array",
"(",
"2",
"**",
"self",
".",
"D",
",",
"regint",
")",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"self",
".",
"D",
")",
":",
"bucket_sizes",
"[",
"i",
"]",
"=",
"0",
"k",
"=",
"0",
"for",
"entry",
",",
"leaf",
"in",
"zip",
"(",
"entries",
",",
"clear_leaves",
")",
":",
"leaf",
"=",
"leaf",
".",
"read",
"(",
")",
"k",
"+=",
"1",
"# for some reason leaf_buckets is in bit-reversed order",
"bits",
"=",
"bit_decompose",
"(",
"leaf",
",",
"self",
".",
"D",
")",
"rev_leaf",
"=",
"sum",
"(",
"b",
"*",
"2",
"**",
"i",
"for",
"i",
",",
"b",
"in",
"enumerate",
"(",
"bits",
"[",
":",
":",
"-",
"1",
"]",
")",
")",
"bucket",
"=",
"RefBucket",
"(",
"rev_leaf",
"+",
"(",
"1",
"<<",
"self",
".",
"D",
")",
",",
"self",
")",
"# hack: 1*entry ensures MemValues are converted to sints",
"bucket",
".",
"bucket",
".",
"ram",
"[",
"bucket_sizes",
"[",
"leaf",
"]",
"]",
"=",
"1",
"*",
"entry",
"bucket_sizes",
"[",
"leaf",
"]",
"+=",
"1",
"self",
".",
"index",
".",
"batch_init",
"(",
"[",
"leaf",
".",
"read",
"(",
")",
"for",
"leaf",
"in",
"unsorted_leaves",
"]",
")"
] | https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/oram.py#L1145-L1285 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | NativeFontInfo.GetFamily | (*args, **kwargs) | return _gdi_.NativeFontInfo_GetFamily(*args, **kwargs) | GetFamily(self) -> int | GetFamily(self) -> int | [
"GetFamily",
"(",
"self",
")",
"-",
">",
"int"
] | def GetFamily(*args, **kwargs):
"""GetFamily(self) -> int"""
return _gdi_.NativeFontInfo_GetFamily(*args, **kwargs) | [
"def",
"GetFamily",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"NativeFontInfo_GetFamily",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1901-L1903 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/Resources/Python/Override/Lib/multiprocessing/__init__.py | python | RawArray | (typecode_or_type, size_or_initializer) | return RawArray(typecode_or_type, size_or_initializer) | Returns a shared array | Returns a shared array | [
"Returns",
"a",
"shared",
"array"
] | def RawArray(typecode_or_type, size_or_initializer):
'''
Returns a shared array
'''
from multiprocessing.sharedctypes import RawArray
return RawArray(typecode_or_type, size_or_initializer) | [
"def",
"RawArray",
"(",
"typecode_or_type",
",",
"size_or_initializer",
")",
":",
"from",
"multiprocessing",
".",
"sharedctypes",
"import",
"RawArray",
"return",
"RawArray",
"(",
"typecode_or_type",
",",
"size_or_initializer",
")"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/Resources/Python/Override/Lib/multiprocessing/__init__.py#L241-L246 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiPaneInfo.SafeSet | (*args, **kwargs) | return _aui.AuiPaneInfo_SafeSet(*args, **kwargs) | SafeSet(self, AuiPaneInfo source) | SafeSet(self, AuiPaneInfo source) | [
"SafeSet",
"(",
"self",
"AuiPaneInfo",
"source",
")"
] | def SafeSet(*args, **kwargs):
"""SafeSet(self, AuiPaneInfo source)"""
return _aui.AuiPaneInfo_SafeSet(*args, **kwargs) | [
"def",
"SafeSet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_SafeSet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L233-L235 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/procrouting/findif_response_utils/db_helper.py | python | stat | (db) | Checks displacement sub_directories for the status of each
displacement computation
db: (database) the database storing information for this distributed
property calculation
Returns: nothing
Throws: nothing | Checks displacement sub_directories for the status of each
displacement computation | [
"Checks",
"displacement",
"sub_directories",
"for",
"the",
"status",
"of",
"each",
"displacement",
"computation"
] | def stat(db):
"""
Checks displacement sub_directories for the status of each
displacement computation
db: (database) the database storing information for this distributed
property calculation
Returns: nothing
Throws: nothing
"""
n_finished = 0
for job, status in db['job_status'].items():
if status == 'finished':
n_finished += 1
elif status in ('not_started', 'running'):
try:
with open("{}/output.dat".format(job)) as outfile:
outfile.seek(-150, 2)
for line in outfile:
if 'Psi4 exiting successfully' in line:
db['job_status'][job] = 'finished'
n_finished += 1
break
else:
db['job_status'][job] = 'running'
except:
pass
# check all jobs done?
if n_finished == len(db['job_status'].keys()):
db['jobs_complete'] = True | [
"def",
"stat",
"(",
"db",
")",
":",
"n_finished",
"=",
"0",
"for",
"job",
",",
"status",
"in",
"db",
"[",
"'job_status'",
"]",
".",
"items",
"(",
")",
":",
"if",
"status",
"==",
"'finished'",
":",
"n_finished",
"+=",
"1",
"elif",
"status",
"in",
"(",
"'not_started'",
",",
"'running'",
")",
":",
"try",
":",
"with",
"open",
"(",
"\"{}/output.dat\"",
".",
"format",
"(",
"job",
")",
")",
"as",
"outfile",
":",
"outfile",
".",
"seek",
"(",
"-",
"150",
",",
"2",
")",
"for",
"line",
"in",
"outfile",
":",
"if",
"'Psi4 exiting successfully'",
"in",
"line",
":",
"db",
"[",
"'job_status'",
"]",
"[",
"job",
"]",
"=",
"'finished'",
"n_finished",
"+=",
"1",
"break",
"else",
":",
"db",
"[",
"'job_status'",
"]",
"[",
"job",
"]",
"=",
"'running'",
"except",
":",
"pass",
"# check all jobs done?",
"if",
"n_finished",
"==",
"len",
"(",
"db",
"[",
"'job_status'",
"]",
".",
"keys",
"(",
")",
")",
":",
"db",
"[",
"'jobs_complete'",
"]",
"=",
"True"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/findif_response_utils/db_helper.py#L147-L177 | ||
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | python/dolfinx/io.py | python | ufl_mesh_from_gmsh | (gmsh_cell: int, gdim: int) | return ufl.Mesh(ufl.VectorElement(scalar_element)) | Create a UFL mesh from a Gmsh cell identifier and the geometric dimension.
See: # http://gmsh.info//doc/texinfo/gmsh.html#MSH-file-format | Create a UFL mesh from a Gmsh cell identifier and the geometric dimension.
See: # http://gmsh.info//doc/texinfo/gmsh.html#MSH-file-format | [
"Create",
"a",
"UFL",
"mesh",
"from",
"a",
"Gmsh",
"cell",
"identifier",
"and",
"the",
"geometric",
"dimension",
".",
"See",
":",
"#",
"http",
":",
"//",
"gmsh",
".",
"info",
"//",
"doc",
"/",
"texinfo",
"/",
"gmsh",
".",
"html#MSH",
"-",
"file",
"-",
"format"
] | def ufl_mesh_from_gmsh(gmsh_cell: int, gdim: int) -> ufl.Mesh:
"""Create a UFL mesh from a Gmsh cell identifier and the geometric dimension.
See: # http://gmsh.info//doc/texinfo/gmsh.html#MSH-file-format
"""
shape, degree = _gmsh_to_cells[gmsh_cell]
cell = ufl.Cell(shape, geometric_dimension=gdim)
scalar_element = ufl.FiniteElement("Lagrange", cell, degree, variant="equispaced")
return ufl.Mesh(ufl.VectorElement(scalar_element)) | [
"def",
"ufl_mesh_from_gmsh",
"(",
"gmsh_cell",
":",
"int",
",",
"gdim",
":",
"int",
")",
"->",
"ufl",
".",
"Mesh",
":",
"shape",
",",
"degree",
"=",
"_gmsh_to_cells",
"[",
"gmsh_cell",
"]",
"cell",
"=",
"ufl",
".",
"Cell",
"(",
"shape",
",",
"geometric_dimension",
"=",
"gdim",
")",
"scalar_element",
"=",
"ufl",
".",
"FiniteElement",
"(",
"\"Lagrange\"",
",",
"cell",
",",
"degree",
",",
"variant",
"=",
"\"equispaced\"",
")",
"return",
"ufl",
".",
"Mesh",
"(",
"ufl",
".",
"VectorElement",
"(",
"scalar_element",
")",
")"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/io.py#L165-L173 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/uuid.py | python | _random_getnode | () | return random.getrandbits(48) | (1 << 40) | Get a random node ID. | Get a random node ID. | [
"Get",
"a",
"random",
"node",
"ID",
"."
] | def _random_getnode():
"""Get a random node ID."""
# RFC 4122, $4.1.6 says "For systems with no IEEE address, a randomly or
# pseudo-randomly generated value may be used; see Section 4.5. The
# multicast bit must be set in such addresses, in order that they will
# never conflict with addresses obtained from network cards."
#
# The "multicast bit" of a MAC address is defined to be "the least
# significant bit of the first octet". This works out to be the 41st bit
# counting from 1 being the least significant bit, or 1<<40.
#
# See https://en.wikipedia.org/wiki/MAC_address#Unicast_vs._multicast
import random
return random.getrandbits(48) | (1 << 40) | [
"def",
"_random_getnode",
"(",
")",
":",
"# RFC 4122, $4.1.6 says \"For systems with no IEEE address, a randomly or",
"# pseudo-randomly generated value may be used; see Section 4.5. The",
"# multicast bit must be set in such addresses, in order that they will",
"# never conflict with addresses obtained from network cards.\"",
"#",
"# The \"multicast bit\" of a MAC address is defined to be \"the least",
"# significant bit of the first octet\". This works out to be the 41st bit",
"# counting from 1 being the least significant bit, or 1<<40.",
"#",
"# See https://en.wikipedia.org/wiki/MAC_address#Unicast_vs._multicast",
"import",
"random",
"return",
"random",
".",
"getrandbits",
"(",
"48",
")",
"|",
"(",
"1",
"<<",
"40",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/uuid.py#L662-L675 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/customtreectrl.py | python | CustomTreeCtrl.GetBorderPen | (self) | return self._borderPen | Returns the pen used to draw the selected item border.
:return: An instance of :class:`Pen`.
:note: The border pen is not used if the Windows Vista selection style is applied. | Returns the pen used to draw the selected item border. | [
"Returns",
"the",
"pen",
"used",
"to",
"draw",
"the",
"selected",
"item",
"border",
"."
] | def GetBorderPen(self):
"""
Returns the pen used to draw the selected item border.
:return: An instance of :class:`Pen`.
:note: The border pen is not used if the Windows Vista selection style is applied.
"""
return self._borderPen | [
"def",
"GetBorderPen",
"(",
"self",
")",
":",
"return",
"self",
".",
"_borderPen"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L4161-L4170 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/numpy_ops/np_utils.py | python | finfo | (dtype) | return np.finfo(_to_numpy_type(dtype)) | Note that currently it just forwards to the numpy namesake, while
tensorflow and numpy dtypes may have different properties. | Note that currently it just forwards to the numpy namesake, while
tensorflow and numpy dtypes may have different properties. | [
"Note",
"that",
"currently",
"it",
"just",
"forwards",
"to",
"the",
"numpy",
"namesake",
"while",
"tensorflow",
"and",
"numpy",
"dtypes",
"may",
"have",
"different",
"properties",
"."
] | def finfo(dtype):
"""Note that currently it just forwards to the numpy namesake, while
tensorflow and numpy dtypes may have different properties."""
return np.finfo(_to_numpy_type(dtype)) | [
"def",
"finfo",
"(",
"dtype",
")",
":",
"return",
"np",
".",
"finfo",
"(",
"_to_numpy_type",
"(",
"dtype",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/numpy_ops/np_utils.py#L475-L478 | |
doxygen/doxygen | c5d4b67565a5fadea5d84d28cfe86db605b4593f | examples/docstring.py | python | func | () | Documentation for a function.
More details. | Documentation for a function. | [
"Documentation",
"for",
"a",
"function",
"."
] | def func():
"""Documentation for a function.
More details.
"""
pass | [
"def",
"func",
"(",
")",
":",
"pass"
] | https://github.com/doxygen/doxygen/blob/c5d4b67565a5fadea5d84d28cfe86db605b4593f/examples/docstring.py#L7-L12 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/re.py | python | subn | (pattern, repl, string, count=0) | return _compile(pattern, 0).subn(repl, string, count) | Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the match object and must
return a replacement string to be used. | Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the match object and must
return a replacement string to be used. | [
"Return",
"a",
"2",
"-",
"tuple",
"containing",
"(",
"new_string",
"number",
")",
".",
"new_string",
"is",
"the",
"string",
"obtained",
"by",
"replacing",
"the",
"leftmost",
"non",
"-",
"overlapping",
"occurrences",
"of",
"the",
"pattern",
"in",
"the",
"source",
"string",
"by",
"the",
"replacement",
"repl",
".",
"number",
"is",
"the",
"number",
"of",
"substitutions",
"that",
"were",
"made",
".",
"repl",
"can",
"be",
"either",
"a",
"string",
"or",
"a",
"callable",
";",
"if",
"a",
"string",
"backslash",
"escapes",
"in",
"it",
"are",
"processed",
".",
"If",
"it",
"is",
"a",
"callable",
"it",
"s",
"passed",
"the",
"match",
"object",
"and",
"must",
"return",
"a",
"replacement",
"string",
"to",
"be",
"used",
"."
] | def subn(pattern, repl, string, count=0):
"""Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the match object and must
return a replacement string to be used."""
return _compile(pattern, 0).subn(repl, string, count) | [
"def",
"subn",
"(",
"pattern",
",",
"repl",
",",
"string",
",",
"count",
"=",
"0",
")",
":",
"return",
"_compile",
"(",
"pattern",
",",
"0",
")",
".",
"subn",
"(",
"repl",
",",
"string",
",",
"count",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/re.py#L153-L162 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/configobj/configobj.py | python | Section.merge | (self, indict) | A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... [section1]
... option1 = False
... # end of file'''.splitlines()
>>> c1 = ConfigObj(b)
>>> c2 = ConfigObj(a)
>>> c2.merge(c1)
>>> c2
ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}) | A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... [section1]
... option1 = False
... # end of file'''.splitlines()
>>> c1 = ConfigObj(b)
>>> c2 = ConfigObj(a)
>>> c2.merge(c1)
>>> c2
ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}) | [
"A",
"recursive",
"update",
"-",
"useful",
"for",
"merging",
"config",
"files",
".",
">>>",
"a",
"=",
"[",
"section1",
"]",
"...",
"option1",
"=",
"True",
"...",
"[[",
"subsection",
"]]",
"...",
"more_options",
"=",
"False",
"...",
"#",
"end",
"of",
"file",
".",
"splitlines",
"()",
">>>",
"b",
"=",
"#",
"File",
"is",
"user",
".",
"ini",
"...",
"[",
"section1",
"]",
"...",
"option1",
"=",
"False",
"...",
"#",
"end",
"of",
"file",
".",
"splitlines",
"()",
">>>",
"c1",
"=",
"ConfigObj",
"(",
"b",
")",
">>>",
"c2",
"=",
"ConfigObj",
"(",
"a",
")",
">>>",
"c2",
".",
"merge",
"(",
"c1",
")",
">>>",
"c2",
"ConfigObj",
"(",
"{",
"section1",
":",
"{",
"option1",
":",
"False",
"subsection",
":",
"{",
"more_options",
":",
"False",
"}}}",
")"
] | def merge(self, indict):
"""
A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... [section1]
... option1 = False
... # end of file'''.splitlines()
>>> c1 = ConfigObj(b)
>>> c2 = ConfigObj(a)
>>> c2.merge(c1)
>>> c2
ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}})
"""
for key, val in indict.items():
if (key in self and isinstance(self[key], dict) and
isinstance(val, dict)):
self[key].merge(val)
else:
self[key] = val | [
"def",
"merge",
"(",
"self",
",",
"indict",
")",
":",
"for",
"key",
",",
"val",
"in",
"indict",
".",
"items",
"(",
")",
":",
"if",
"(",
"key",
"in",
"self",
"and",
"isinstance",
"(",
"self",
"[",
"key",
"]",
",",
"dict",
")",
"and",
"isinstance",
"(",
"val",
",",
"dict",
")",
")",
":",
"self",
"[",
"key",
"]",
".",
"merge",
"(",
"val",
")",
"else",
":",
"self",
"[",
"key",
"]",
"=",
"val"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/configobj/configobj.py#L798-L822 | ||
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | BindHandler.WriteGLES2Implementation | (self, func, f) | Writes the GLES2 Implemention. | Writes the GLES2 Implemention. | [
"Writes",
"the",
"GLES2",
"Implemention",
"."
] | def WriteGLES2Implementation(self, func, f):
"""Writes the GLES2 Implemention."""
impl_func = func.GetInfo('impl_func', True)
if func.can_auto_generate and impl_func:
f.write("%s GLES2Implementation::%s(%s) {\n" %
(func.return_type, func.original_name,
func.MakeTypedOriginalArgString("")))
f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
func.WriteDestinationInitalizationValidation(f)
self.WriteClientGLCallLog(func, f)
for arg in func.GetOriginalArgs():
arg.WriteClientSideValidationCode(f, func)
code = """ if (Is%(type)sReservedId(%(id)s)) {
SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
return;
}
%(name)sHelper(%(arg_string)s);
CheckGLError();
}
"""
name_arg = func.GetResourceIdArg()
f.write(code % {
'name': func.name,
'arg_string': func.MakeOriginalArgString(""),
'id': name_arg.name,
'type': name_arg.resource_type,
'lc_type': name_arg.resource_type.lower(),
}) | [
"def",
"WriteGLES2Implementation",
"(",
"self",
",",
"func",
",",
"f",
")",
":",
"impl_func",
"=",
"func",
".",
"GetInfo",
"(",
"'impl_func'",
",",
"True",
")",
"if",
"func",
".",
"can_auto_generate",
"and",
"impl_func",
":",
"f",
".",
"write",
"(",
"\"%s GLES2Implementation::%s(%s) {\\n\"",
"%",
"(",
"func",
".",
"return_type",
",",
"func",
".",
"original_name",
",",
"func",
".",
"MakeTypedOriginalArgString",
"(",
"\"\"",
")",
")",
")",
"f",
".",
"write",
"(",
"\" GPU_CLIENT_SINGLE_THREAD_CHECK();\\n\"",
")",
"func",
".",
"WriteDestinationInitalizationValidation",
"(",
"f",
")",
"self",
".",
"WriteClientGLCallLog",
"(",
"func",
",",
"f",
")",
"for",
"arg",
"in",
"func",
".",
"GetOriginalArgs",
"(",
")",
":",
"arg",
".",
"WriteClientSideValidationCode",
"(",
"f",
",",
"func",
")",
"code",
"=",
"\"\"\" if (Is%(type)sReservedId(%(id)s)) {\n SetGLError(GL_INVALID_OPERATION, \"%(name)s\\\", \\\"%(id)s reserved id\");\n return;\n }\n %(name)sHelper(%(arg_string)s);\n CheckGLError();\n}\n\n\"\"\"",
"name_arg",
"=",
"func",
".",
"GetResourceIdArg",
"(",
")",
"f",
".",
"write",
"(",
"code",
"%",
"{",
"'name'",
":",
"func",
".",
"name",
",",
"'arg_string'",
":",
"func",
".",
"MakeOriginalArgString",
"(",
"\"\"",
")",
",",
"'id'",
":",
"name_arg",
".",
"name",
",",
"'type'",
":",
"name_arg",
".",
"resource_type",
",",
"'lc_type'",
":",
"name_arg",
".",
"resource_type",
".",
"lower",
"(",
")",
",",
"}",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L5897-L5927 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/preprocessing/image.py | python | random_shift | (x,
wrg,
hrg,
row_axis=1,
col_axis=2,
channel_axis=0,
fill_mode='nearest',
cval=0.) | return x | Performs a random spatial shift of a Numpy image tensor.
Arguments:
x: Input tensor. Must be 3D.
wrg: Width shift range, as a float fraction of the width.
hrg: Height shift range, as a float fraction of the height.
row_axis: Index of axis for rows in the input tensor.
col_axis: Index of axis for columns in the input tensor.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
Returns:
Shifted Numpy image tensor. | Performs a random spatial shift of a Numpy image tensor. | [
"Performs",
"a",
"random",
"spatial",
"shift",
"of",
"a",
"Numpy",
"image",
"tensor",
"."
] | def random_shift(x,
wrg,
hrg,
row_axis=1,
col_axis=2,
channel_axis=0,
fill_mode='nearest',
cval=0.):
"""Performs a random spatial shift of a Numpy image tensor.
Arguments:
x: Input tensor. Must be 3D.
wrg: Width shift range, as a float fraction of the width.
hrg: Height shift range, as a float fraction of the height.
row_axis: Index of axis for rows in the input tensor.
col_axis: Index of axis for columns in the input tensor.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
Returns:
Shifted Numpy image tensor.
"""
h, w = x.shape[row_axis], x.shape[col_axis]
tx = np.random.uniform(-hrg, hrg) * h
ty = np.random.uniform(-wrg, wrg) * w
translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)
return x | [
"def",
"random_shift",
"(",
"x",
",",
"wrg",
",",
"hrg",
",",
"row_axis",
"=",
"1",
",",
"col_axis",
"=",
"2",
",",
"channel_axis",
"=",
"0",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
")",
":",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"row_axis",
"]",
",",
"x",
".",
"shape",
"[",
"col_axis",
"]",
"tx",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"hrg",
",",
"hrg",
")",
"*",
"h",
"ty",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"wrg",
",",
"wrg",
")",
"*",
"w",
"translation_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"tx",
"]",
",",
"[",
"0",
",",
"1",
",",
"ty",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"transform_matrix",
"=",
"translation_matrix",
"# no need to do offset",
"x",
"=",
"apply_transform",
"(",
"x",
",",
"transform_matrix",
",",
"channel_axis",
",",
"fill_mode",
",",
"cval",
")",
"return",
"x"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/preprocessing/image.py#L85-L118 | |
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/input.py | python | QualifyDependencies | (targets) | Make dependency links fully-qualified relative to the current directory.
|targets| is a dict mapping fully-qualified target names to their target
dicts. For each target in this dict, keys known to contain dependency
links are examined, and any dependencies referenced will be rewritten
so that they are fully-qualified and relative to the current directory.
All rewritten dependencies are suitable for use as keys to |targets| or a
similar dict. | Make dependency links fully-qualified relative to the current directory. | [
"Make",
"dependency",
"links",
"fully",
"-",
"qualified",
"relative",
"to",
"the",
"current",
"directory",
"."
] | def QualifyDependencies(targets):
"""Make dependency links fully-qualified relative to the current directory.
|targets| is a dict mapping fully-qualified target names to their target
dicts. For each target in this dict, keys known to contain dependency
links are examined, and any dependencies referenced will be rewritten
so that they are fully-qualified and relative to the current directory.
All rewritten dependencies are suitable for use as keys to |targets| or a
similar dict.
"""
for target, target_dict in targets.iteritems():
target_build_file = gyp.common.BuildFile(target)
toolset = target_dict['toolset']
for dependency_key in dependency_sections:
dependencies = target_dict.get(dependency_key, [])
for index in xrange(0, len(dependencies)):
dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget(
target_build_file, dependencies[index], toolset)
global multiple_toolsets
if not multiple_toolsets:
# Ignore toolset specification in the dependency if it is specified.
dep_toolset = toolset
dependency = gyp.common.QualifiedTarget(dep_file,
dep_target,
dep_toolset)
dependencies[index] = dependency
# Make sure anything appearing in a list other than "dependencies" also
# appears in the "dependencies" list.
if dependency_key != 'dependencies' and \
dependency not in target_dict['dependencies']:
raise KeyError, 'Found ' + dependency + ' in ' + dependency_key + \
' of ' + target + ', but not in dependencies' | [
"def",
"QualifyDependencies",
"(",
"targets",
")",
":",
"for",
"target",
",",
"target_dict",
"in",
"targets",
".",
"iteritems",
"(",
")",
":",
"target_build_file",
"=",
"gyp",
".",
"common",
".",
"BuildFile",
"(",
"target",
")",
"toolset",
"=",
"target_dict",
"[",
"'toolset'",
"]",
"for",
"dependency_key",
"in",
"dependency_sections",
":",
"dependencies",
"=",
"target_dict",
".",
"get",
"(",
"dependency_key",
",",
"[",
"]",
")",
"for",
"index",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"dependencies",
")",
")",
":",
"dep_file",
",",
"dep_target",
",",
"dep_toolset",
"=",
"gyp",
".",
"common",
".",
"ResolveTarget",
"(",
"target_build_file",
",",
"dependencies",
"[",
"index",
"]",
",",
"toolset",
")",
"global",
"multiple_toolsets",
"if",
"not",
"multiple_toolsets",
":",
"# Ignore toolset specification in the dependency if it is specified.",
"dep_toolset",
"=",
"toolset",
"dependency",
"=",
"gyp",
".",
"common",
".",
"QualifiedTarget",
"(",
"dep_file",
",",
"dep_target",
",",
"dep_toolset",
")",
"dependencies",
"[",
"index",
"]",
"=",
"dependency",
"# Make sure anything appearing in a list other than \"dependencies\" also",
"# appears in the \"dependencies\" list.",
"if",
"dependency_key",
"!=",
"'dependencies'",
"and",
"dependency",
"not",
"in",
"target_dict",
"[",
"'dependencies'",
"]",
":",
"raise",
"KeyError",
",",
"'Found '",
"+",
"dependency",
"+",
"' in '",
"+",
"dependency_key",
"+",
"' of '",
"+",
"target",
"+",
"', but not in dependencies'"
] | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/input.py#L1034-L1067 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/stats.py | python | trimboth | (a, proportiontocut, axis=0) | return atmp[sl] | Slices off a proportion of items from both ends of an array.
Slices off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). The trimmed values are the lowest and
highest ones.
Slices off less if proportion results in a non-integer slice index (i.e.,
conservatively slices off`proportiontocut`).
Parameters
----------
a : array_like
Data to trim.
proportiontocut : float
Proportion (in range 0-1) of total data set to trim of each end.
axis : int or None, optional
Axis along which to trim data. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
out : ndarray
Trimmed version of array `a`. The order of the trimmed content
is undefined.
See Also
--------
trim_mean
Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,) | Slices off a proportion of items from both ends of an array. | [
"Slices",
"off",
"a",
"proportion",
"of",
"items",
"from",
"both",
"ends",
"of",
"an",
"array",
"."
] | def trimboth(a, proportiontocut, axis=0):
"""
Slices off a proportion of items from both ends of an array.
Slices off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). The trimmed values are the lowest and
highest ones.
Slices off less if proportion results in a non-integer slice index (i.e.,
conservatively slices off`proportiontocut`).
Parameters
----------
a : array_like
Data to trim.
proportiontocut : float
Proportion (in range 0-1) of total data set to trim of each end.
axis : int or None, optional
Axis along which to trim data. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
out : ndarray
Trimmed version of array `a`. The order of the trimmed content
is undefined.
See Also
--------
trim_mean
Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,)
"""
a = np.asarray(a)
if a.size == 0:
return a
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
lowercut = int(proportiontocut * nobs)
uppercut = nobs - lowercut
if (lowercut >= uppercut):
raise ValueError("Proportion too big.")
# np.partition is preferred but it only exist in numpy 1.8.0 and higher,
# in those cases we use np.sort
try:
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
except AttributeError:
atmp = np.sort(a, axis)
sl = [slice(None)] * atmp.ndim
sl[axis] = slice(lowercut, uppercut)
return atmp[sl] | [
"def",
"trimboth",
"(",
"a",
",",
"proportiontocut",
",",
"axis",
"=",
"0",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"if",
"a",
".",
"size",
"==",
"0",
":",
"return",
"a",
"if",
"axis",
"is",
"None",
":",
"a",
"=",
"a",
".",
"ravel",
"(",
")",
"axis",
"=",
"0",
"nobs",
"=",
"a",
".",
"shape",
"[",
"axis",
"]",
"lowercut",
"=",
"int",
"(",
"proportiontocut",
"*",
"nobs",
")",
"uppercut",
"=",
"nobs",
"-",
"lowercut",
"if",
"(",
"lowercut",
">=",
"uppercut",
")",
":",
"raise",
"ValueError",
"(",
"\"Proportion too big.\"",
")",
"# np.partition is preferred but it only exist in numpy 1.8.0 and higher,",
"# in those cases we use np.sort",
"try",
":",
"atmp",
"=",
"np",
".",
"partition",
"(",
"a",
",",
"(",
"lowercut",
",",
"uppercut",
"-",
"1",
")",
",",
"axis",
")",
"except",
"AttributeError",
":",
"atmp",
"=",
"np",
".",
"sort",
"(",
"a",
",",
"axis",
")",
"sl",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"atmp",
".",
"ndim",
"sl",
"[",
"axis",
"]",
"=",
"slice",
"(",
"lowercut",
",",
"uppercut",
")",
"return",
"atmp",
"[",
"sl",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L2678-L2742 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/fastboot_utils.py | python | FastbootUtils.WaitForFastbootMode | (self, timeout=None, retries=None) | Wait for device to boot into fastboot mode.
This waits for the device serial to show up in fastboot devices output. | Wait for device to boot into fastboot mode. | [
"Wait",
"for",
"device",
"to",
"boot",
"into",
"fastboot",
"mode",
"."
] | def WaitForFastbootMode(self, timeout=None, retries=None):
"""Wait for device to boot into fastboot mode.
This waits for the device serial to show up in fastboot devices output.
"""
def fastboot_mode():
return self._serial in self.fastboot.Devices()
timeout_retry.WaitFor(fastboot_mode, wait_period=self._FASTBOOT_WAIT_TIME) | [
"def",
"WaitForFastbootMode",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"retries",
"=",
"None",
")",
":",
"def",
"fastboot_mode",
"(",
")",
":",
"return",
"self",
".",
"_serial",
"in",
"self",
".",
"fastboot",
".",
"Devices",
"(",
")",
"timeout_retry",
".",
"WaitFor",
"(",
"fastboot_mode",
",",
"wait_period",
"=",
"self",
".",
"_FASTBOOT_WAIT_TIME",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/fastboot_utils.py#L103-L111 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.AdjustLibraries | (self, libraries, config_name=None) | return libraries | Transforms entries like 'Cocoa.framework' in libraries into entries like
'-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. | Transforms entries like 'Cocoa.framework' in libraries into entries like
'-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. | [
"Transforms",
"entries",
"like",
"Cocoa",
".",
"framework",
"in",
"libraries",
"into",
"entries",
"like",
"-",
"framework",
"Cocoa",
"libcrypto",
".",
"dylib",
"into",
"-",
"lcrypto",
"etc",
"."
] | def AdjustLibraries(self, libraries, config_name=None):
"""Transforms entries like 'Cocoa.framework' in libraries into entries like
'-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc.
"""
libraries = [self._AdjustLibrary(library, config_name)
for library in libraries]
return libraries | [
"def",
"AdjustLibraries",
"(",
"self",
",",
"libraries",
",",
"config_name",
"=",
"None",
")",
":",
"libraries",
"=",
"[",
"self",
".",
"_AdjustLibrary",
"(",
"library",
",",
"config_name",
")",
"for",
"library",
"in",
"libraries",
"]",
"return",
"libraries"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcode_emulation.py#L1182-L1188 | |
OAID/Tengine | 66b2c22ad129d25e2fc6de3b22a608bb54dd90db | pytengine/tengine/graph.py | python | Graph.setlayout | (self, type) | return _LIB.set_graph_layout(ctypes.c_void_p(self.graph), type) | set the layer type of the graph
:param type: <layout_type> like: tg.TENGINE_LAYOUT_NCHW, tg.TENGINE_LAYOUT_NHWC
:return: 0: success, -1: fail | set the layer type of the graph
:param type: <layout_type> like: tg.TENGINE_LAYOUT_NCHW, tg.TENGINE_LAYOUT_NHWC
:return: 0: success, -1: fail | [
"set",
"the",
"layer",
"type",
"of",
"the",
"graph",
":",
"param",
"type",
":",
"<layout_type",
">",
"like",
":",
"tg",
".",
"TENGINE_LAYOUT_NCHW",
"tg",
".",
"TENGINE_LAYOUT_NHWC",
":",
"return",
":",
"0",
":",
"success",
"-",
"1",
":",
"fail"
] | def setlayout(self, type):
"""
set the layer type of the graph
:param type: <layout_type> like: tg.TENGINE_LAYOUT_NCHW, tg.TENGINE_LAYOUT_NHWC
:return: 0: success, -1: fail
"""
return _LIB.set_graph_layout(ctypes.c_void_p(self.graph), type) | [
"def",
"setlayout",
"(",
"self",
",",
"type",
")",
":",
"return",
"_LIB",
".",
"set_graph_layout",
"(",
"ctypes",
".",
"c_void_p",
"(",
"self",
".",
"graph",
")",
",",
"type",
")"
] | https://github.com/OAID/Tengine/blob/66b2c22ad129d25e2fc6de3b22a608bb54dd90db/pytengine/tengine/graph.py#L107-L113 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | TopLevelWindow.GetIcon | (*args, **kwargs) | return _windows_.TopLevelWindow_GetIcon(*args, **kwargs) | GetIcon(self) -> Icon | GetIcon(self) -> Icon | [
"GetIcon",
"(",
"self",
")",
"-",
">",
"Icon"
] | def GetIcon(*args, **kwargs):
"""GetIcon(self) -> Icon"""
return _windows_.TopLevelWindow_GetIcon(*args, **kwargs) | [
"def",
"GetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TopLevelWindow_GetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L429-L431 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | _IsLoopConstantEnter | (op) | return is_enter and op.get_attr("is_constant") | Return true iff op is a loop invariant. | Return true iff op is a loop invariant. | [
"Return",
"true",
"iff",
"op",
"is",
"a",
"loop",
"invariant",
"."
] | def _IsLoopConstantEnter(op):
"""Return true iff op is a loop invariant."""
is_enter = (op.type == "Enter" or op.type == "RefEnter")
return is_enter and op.get_attr("is_constant") | [
"def",
"_IsLoopConstantEnter",
"(",
"op",
")",
":",
"is_enter",
"=",
"(",
"op",
".",
"type",
"==",
"\"Enter\"",
"or",
"op",
".",
"type",
"==",
"\"RefEnter\"",
")",
"return",
"is_enter",
"and",
"op",
".",
"get_attr",
"(",
"\"is_constant\"",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L416-L419 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathUtils.py | python | depth_params.start_depth | (self) | return self.__start_depth | Start Depth is the top of the model. | Start Depth is the top of the model. | [
"Start",
"Depth",
"is",
"the",
"top",
"of",
"the",
"model",
"."
] | def start_depth(self):
"""
Start Depth is the top of the model.
"""
return self.__start_depth | [
"def",
"start_depth",
"(",
"self",
")",
":",
"return",
"self",
".",
"__start_depth"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathUtils.py#L642-L646 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/plots/mantidaxes.py | python | MantidAxes.imshow | (self, *args, **kwargs) | return self._plot_2d_func('imshow', *args, **kwargs) | If the **mantid** projection is chosen, it can be
used the same as :py:meth:`matplotlib.axes.Axes.imshow` for arrays,
or it can be used to plot :class:`mantid.api.MatrixWorkspace`
or :class:`mantid.api.IMDHistoWorkspace`. You can have something like::
import matplotlib.pyplot as plt
from mantid import plots
...
fig, ax = plt.subplots(subplot_kw={'projection':'mantid'})
ax.imshow(workspace) #for workspaces
ax.imshow(C) #for arrays
fig.show()
For keywords related to workspaces, see :func:`plotfunctions.imshow` | If the **mantid** projection is chosen, it can be
used the same as :py:meth:`matplotlib.axes.Axes.imshow` for arrays,
or it can be used to plot :class:`mantid.api.MatrixWorkspace`
or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: | [
"If",
"the",
"**",
"mantid",
"**",
"projection",
"is",
"chosen",
"it",
"can",
"be",
"used",
"the",
"same",
"as",
":",
"py",
":",
"meth",
":",
"matplotlib",
".",
"axes",
".",
"Axes",
".",
"imshow",
"for",
"arrays",
"or",
"it",
"can",
"be",
"used",
"to",
"plot",
":",
"class",
":",
"mantid",
".",
"api",
".",
"MatrixWorkspace",
"or",
":",
"class",
":",
"mantid",
".",
"api",
".",
"IMDHistoWorkspace",
".",
"You",
"can",
"have",
"something",
"like",
"::"
] | def imshow(self, *args, **kwargs):
"""
If the **mantid** projection is chosen, it can be
used the same as :py:meth:`matplotlib.axes.Axes.imshow` for arrays,
or it can be used to plot :class:`mantid.api.MatrixWorkspace`
or :class:`mantid.api.IMDHistoWorkspace`. You can have something like::
import matplotlib.pyplot as plt
from mantid import plots
...
fig, ax = plt.subplots(subplot_kw={'projection':'mantid'})
ax.imshow(workspace) #for workspaces
ax.imshow(C) #for arrays
fig.show()
For keywords related to workspaces, see :func:`plotfunctions.imshow`
"""
return self._plot_2d_func('imshow', *args, **kwargs) | [
"def",
"imshow",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_plot_2d_func",
"(",
"'imshow'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/plots/mantidaxes.py#L878-L897 | |
google/ml-metadata | b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d | ml_metadata/metadata_store/types.py | python | Execution.save_input | (self, store: metadata_store.MetadataStore) | Saves input_struct to store.
Saves the structure of the input, as well as the individual artifacts
if they have not already been saved.
It is intended for orchestration users.
This should never be called more than once, or it will fail.
Args:
store: the database the data goes to.
Raises:
ValueError: if execution has not been saved, or inputs for this execution
already exist. | Saves input_struct to store. | [
"Saves",
"input_struct",
"to",
"store",
"."
] | def save_input(self, store: metadata_store.MetadataStore):
"""Saves input_struct to store.
Saves the structure of the input, as well as the individual artifacts
if they have not already been saved.
It is intended for orchestration users.
This should never be called more than once, or it will fail.
Args:
store: the database the data goes to.
Raises:
ValueError: if execution has not been saved, or inputs for this execution
already exist.
"""
if not self.has_id():
raise ValueError("Must save_execution before save_input")
if self._input_exists(store):
raise ValueError("Input already saved")
_save_artifact_structs_as_events(
store, [(self.execution.id, metadata_store_pb2.Event.DECLARED_INPUT,
self.input_struct)]) | [
"def",
"save_input",
"(",
"self",
",",
"store",
":",
"metadata_store",
".",
"MetadataStore",
")",
":",
"if",
"not",
"self",
".",
"has_id",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Must save_execution before save_input\"",
")",
"if",
"self",
".",
"_input_exists",
"(",
"store",
")",
":",
"raise",
"ValueError",
"(",
"\"Input already saved\"",
")",
"_save_artifact_structs_as_events",
"(",
"store",
",",
"[",
"(",
"self",
".",
"execution",
".",
"id",
",",
"metadata_store_pb2",
".",
"Event",
".",
"DECLARED_INPUT",
",",
"self",
".",
"input_struct",
")",
"]",
")"
] | https://github.com/google/ml-metadata/blob/b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d/ml_metadata/metadata_store/types.py#L1214-L1235 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/mutex.py | python | mutex.lock | (self, function, argument) | Lock a mutex, call the function with supplied argument
when it is acquired. If the mutex is already locked, place
function and argument in the queue. | Lock a mutex, call the function with supplied argument
when it is acquired. If the mutex is already locked, place
function and argument in the queue. | [
"Lock",
"a",
"mutex",
"call",
"the",
"function",
"with",
"supplied",
"argument",
"when",
"it",
"is",
"acquired",
".",
"If",
"the",
"mutex",
"is",
"already",
"locked",
"place",
"function",
"and",
"argument",
"in",
"the",
"queue",
"."
] | def lock(self, function, argument):
"""Lock a mutex, call the function with supplied argument
when it is acquired. If the mutex is already locked, place
function and argument in the queue."""
if self.testandset():
function(argument)
else:
self.queue.append((function, argument)) | [
"def",
"lock",
"(",
"self",
",",
"function",
",",
"argument",
")",
":",
"if",
"self",
".",
"testandset",
"(",
")",
":",
"function",
"(",
"argument",
")",
"else",
":",
"self",
".",
"queue",
".",
"append",
"(",
"(",
"function",
",",
"argument",
")",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mutex.py#L39-L46 | ||
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.AdjustIncludeDirs | (self, include_dirs, config) | return [self.ConvertVSMacros(p, config=config) for p in includes] | Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar. | Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar. | [
"Updates",
"include_dirs",
"to",
"expand",
"VS",
"specific",
"paths",
"and",
"adds",
"the",
"system",
"include",
"dirs",
"used",
"for",
"platform",
"SDK",
"and",
"similar",
"."
] | def AdjustIncludeDirs(self, include_dirs, config):
"""Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar."""
config = self._RealConfig(config)
includes = include_dirs + self.msvs_system_include_dirs[config]
includes.extend(self._Setting(
('VCCLCompilerTool', 'AdditionalIncludeDirectories'), config, default=[]))
return [self.ConvertVSMacros(p, config=config) for p in includes] | [
"def",
"AdjustIncludeDirs",
"(",
"self",
",",
"include_dirs",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_RealConfig",
"(",
"config",
")",
"includes",
"=",
"include_dirs",
"+",
"self",
".",
"msvs_system_include_dirs",
"[",
"config",
"]",
"includes",
".",
"extend",
"(",
"self",
".",
"_Setting",
"(",
"(",
"'VCCLCompilerTool'",
",",
"'AdditionalIncludeDirectories'",
")",
",",
"config",
",",
"default",
"=",
"[",
"]",
")",
")",
"return",
"[",
"self",
".",
"ConvertVSMacros",
"(",
"p",
",",
"config",
"=",
"config",
")",
"for",
"p",
"in",
"includes",
"]"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/msvs_emulation.py#L245-L252 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/utils/hybrid_parallel_inference.py | python | HybridParallelInferenceHelper._get_while_block | (self) | return None, None | Get the while sub-block. | Get the while sub-block. | [
"Get",
"the",
"while",
"sub",
"-",
"block",
"."
] | def _get_while_block(self):
"""
Get the while sub-block.
"""
main_block = self._main_program.global_block()
num_while = 0
sub_block_id = None
for op in main_block.ops:
assert num_while < 2, "More than one while op found."
if op.type == 'while':
sub_block_id = op.attr('sub_block').id
num_while += 1
if sub_block_id: return op, self._main_program.block(sub_block_id)
return None, None | [
"def",
"_get_while_block",
"(",
"self",
")",
":",
"main_block",
"=",
"self",
".",
"_main_program",
".",
"global_block",
"(",
")",
"num_while",
"=",
"0",
"sub_block_id",
"=",
"None",
"for",
"op",
"in",
"main_block",
".",
"ops",
":",
"assert",
"num_while",
"<",
"2",
",",
"\"More than one while op found.\"",
"if",
"op",
".",
"type",
"==",
"'while'",
":",
"sub_block_id",
"=",
"op",
".",
"attr",
"(",
"'sub_block'",
")",
".",
"id",
"num_while",
"+=",
"1",
"if",
"sub_block_id",
":",
"return",
"op",
",",
"self",
".",
"_main_program",
".",
"block",
"(",
"sub_block_id",
")",
"return",
"None",
",",
"None"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/utils/hybrid_parallel_inference.py#L700-L713 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py | python | chararray.__rmul__ | (self, i) | return asarray(multiply(self, i)) | Return (self * i), that is string multiple concatenation,
element-wise.
See also
--------
multiply | Return (self * i), that is string multiple concatenation,
element-wise. | [
"Return",
"(",
"self",
"*",
"i",
")",
"that",
"is",
"string",
"multiple",
"concatenation",
"element",
"-",
"wise",
"."
] | def __rmul__(self, i):
"""
Return (self * i), that is string multiple concatenation,
element-wise.
See also
--------
multiply
"""
return asarray(multiply(self, i)) | [
"def",
"__rmul__",
"(",
"self",
",",
"i",
")",
":",
"return",
"asarray",
"(",
"multiply",
"(",
"self",
",",
"i",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py#L1958-L1967 | |
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | Cursor.is_static_method | (self) | return conf.lib.clang_CXXMethod_isStatic(self) | Returns True if the cursor refers to a C++ member function or member
function template that is declared 'static'. | Returns True if the cursor refers to a C++ member function or member
function template that is declared 'static'. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"member",
"function",
"or",
"member",
"function",
"template",
"that",
"is",
"declared",
"static",
"."
] | def is_static_method(self):
"""Returns True if the cursor refers to a C++ member function or member
function template that is declared 'static'.
"""
return conf.lib.clang_CXXMethod_isStatic(self) | [
"def",
"is_static_method",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXMethod_isStatic",
"(",
"self",
")"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1070-L1074 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | AlphaPixelData_Accessor.Offset | (*args, **kwargs) | return _gdi_.AlphaPixelData_Accessor_Offset(*args, **kwargs) | Offset(self, AlphaPixelData data, int x, int y) | Offset(self, AlphaPixelData data, int x, int y) | [
"Offset",
"(",
"self",
"AlphaPixelData",
"data",
"int",
"x",
"int",
"y",
")"
] | def Offset(*args, **kwargs):
"""Offset(self, AlphaPixelData data, int x, int y)"""
return _gdi_.AlphaPixelData_Accessor_Offset(*args, **kwargs) | [
"def",
"Offset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"AlphaPixelData_Accessor_Offset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L1217-L1219 | |
cztomczak/cefpython | 5679f28cec18a57a56e298da2927aac8d8f83ad6 | tools/automate.py | python | fix_cef_include_files | () | Fixes to CEF include header files for eg. VS2008 on Windows. | Fixes to CEF include header files for eg. VS2008 on Windows. | [
"Fixes",
"to",
"CEF",
"include",
"header",
"files",
"for",
"eg",
".",
"VS2008",
"on",
"Windows",
"."
] | def fix_cef_include_files():
"""Fixes to CEF include header files for eg. VS2008 on Windows."""
# TODO: This was fixed in upstream CEF, remove this code during
# next CEF update on Windows.
if platform.system() == "Windows" and get_msvs_for_python() == "2008":
print("[automate.py] Fixing CEF include/ files")
# cef_types_wrappers.h
cef_types_wrappers = os.path.join(Options.cef_binary, "include",
"internal", "cef_types_wrappers.h")
with open(cef_types_wrappers, "rb") as fp:
contents = fp.read().decode("utf-8")
# error C2059: syntax error : '{'
contents = contents.replace("s->range = {0, 0};",
"s->range.from = 0; s->range.to = 0;")
with open(cef_types_wrappers, "wb") as fp:
fp.write(contents.encode("utf-8")) | [
"def",
"fix_cef_include_files",
"(",
")",
":",
"# TODO: This was fixed in upstream CEF, remove this code during",
"# next CEF update on Windows.",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Windows\"",
"and",
"get_msvs_for_python",
"(",
")",
"==",
"\"2008\"",
":",
"print",
"(",
"\"[automate.py] Fixing CEF include/ files\"",
")",
"# cef_types_wrappers.h",
"cef_types_wrappers",
"=",
"os",
".",
"path",
".",
"join",
"(",
"Options",
".",
"cef_binary",
",",
"\"include\"",
",",
"\"internal\"",
",",
"\"cef_types_wrappers.h\"",
")",
"with",
"open",
"(",
"cef_types_wrappers",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"contents",
"=",
"fp",
".",
"read",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"# error C2059: syntax error : '{'",
"contents",
"=",
"contents",
".",
"replace",
"(",
"\"s->range = {0, 0};\"",
",",
"\"s->range.from = 0; s->range.to = 0;\"",
")",
"with",
"open",
"(",
"cef_types_wrappers",
",",
"\"wb\"",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"contents",
".",
"encode",
"(",
"\"utf-8\"",
")",
")"
] | https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/automate.py#L704-L719 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py | python | StoppedCommandPane.get_selected_line | (self) | return None | Subclasses implement this to control where the cursor (and selected highlight)
is placed. | Subclasses implement this to control where the cursor (and selected highlight)
is placed. | [
"Subclasses",
"implement",
"this",
"to",
"control",
"where",
"the",
"cursor",
"(",
"and",
"selected",
"highlight",
")",
"is",
"placed",
"."
] | def get_selected_line(self):
""" Subclasses implement this to control where the cursor (and selected highlight)
is placed.
"""
return None | [
"def",
"get_selected_line",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L598-L602 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/validators.py | python | check_usps_dataset | (method) | return new_method | A wrapper that wraps a parameter checker around the original Dataset(USPSDataset). | A wrapper that wraps a parameter checker around the original Dataset(USPSDataset). | [
"A",
"wrapper",
"that",
"wraps",
"a",
"parameter",
"checker",
"around",
"the",
"original",
"Dataset",
"(",
"USPSDataset",
")",
"."
] | def check_usps_dataset(method):
"""A wrapper that wraps a parameter checker around the original Dataset(USPSDataset)."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id']
dataset_dir = param_dict.get('dataset_dir')
check_dir(dataset_dir)
usage = param_dict.get('usage')
if usage is not None:
check_valid_str(usage, ["train", "test", "all"], "usage")
validate_dataset_param_value(nreq_param_int, param_dict, int)
check_sampler_shuffle_shard_options(param_dict)
cache = param_dict.get('cache')
check_cache_option(cache)
return method(self, *args, **kwargs)
return new_method | [
"def",
"check_usps_dataset",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"new_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"param_dict",
"=",
"parse_user_args",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"nreq_param_int",
"=",
"[",
"'num_samples'",
",",
"'num_parallel_workers'",
",",
"'num_shards'",
",",
"'shard_id'",
"]",
"dataset_dir",
"=",
"param_dict",
".",
"get",
"(",
"'dataset_dir'",
")",
"check_dir",
"(",
"dataset_dir",
")",
"usage",
"=",
"param_dict",
".",
"get",
"(",
"'usage'",
")",
"if",
"usage",
"is",
"not",
"None",
":",
"check_valid_str",
"(",
"usage",
",",
"[",
"\"train\"",
",",
"\"test\"",
",",
"\"all\"",
"]",
",",
"\"usage\"",
")",
"validate_dataset_param_value",
"(",
"nreq_param_int",
",",
"param_dict",
",",
"int",
")",
"check_sampler_shuffle_shard_options",
"(",
"param_dict",
")",
"cache",
"=",
"param_dict",
".",
"get",
"(",
"'cache'",
")",
"check_cache_option",
"(",
"cache",
")",
"return",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_method"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L465-L489 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/rmic.py | python | generate | (env) | Add Builders and construction variables for rmic to an Environment. | Add Builders and construction variables for rmic to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"rmic",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for rmic to an Environment."""
env['BUILDERS']['RMIC'] = RMICBuilder
env['RMIC'] = 'rmic'
env['RMICFLAGS'] = SCons.Util.CLVar('')
env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}'
env['JAVACLASSSUFFIX'] = '.class' | [
"def",
"generate",
"(",
"env",
")",
":",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'RMIC'",
"]",
"=",
"RMICBuilder",
"env",
"[",
"'RMIC'",
"]",
"=",
"'rmic'",
"env",
"[",
"'RMICFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
"env",
"[",
"'RMICCOM'",
"]",
"=",
"'$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}'",
"env",
"[",
"'JAVACLASSSUFFIX'",
"]",
"=",
"'.class'"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/rmic.py#L104-L111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.