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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_utils.py | python | dbg | (*exprs) | Print expressions evaluated in the caller's frame. | Print expressions evaluated in the caller's frame. | [
"Print",
"expressions",
"evaluated",
"in",
"the",
"caller",
"s",
"frame",
"."
] | def dbg(*exprs):
"""Print expressions evaluated in the caller's frame."""
assert enable_debug,"must use debug=true to enable debug output"
import inspect
frame = inspect.currentframe()
try:
locs = frame.f_back.f_locals
globs = frame.f_back.f_globals
for e in exprs:
print "{}:{}".format(e,eval(e,globs,locs))
finally:
del frame | [
"def",
"dbg",
"(",
"*",
"exprs",
")",
":",
"assert",
"enable_debug",
",",
"\"must use debug=true to enable debug output\"",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"try",
":",
"locs",
"=",
"frame",
".",
"f_back",
".",
"f_lo... | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_utils.py#L686-L697 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | third-party/benchmark/tools/strip_asm.py | python | process_asm | (asm) | return new_contents | Strip the ASM of unwanted directives and lines | Strip the ASM of unwanted directives and lines | [
"Strip",
"the",
"ASM",
"of",
"unwanted",
"directives",
"and",
"lines"
] | def process_asm(asm):
"""
Strip the ASM of unwanted directives and lines
"""
new_contents = ''
asm = transform_labels(asm)
# TODO: Add more things we want to remove
discard_regexes = [
re.compile("\s+\..*$"), # directive
re.compile("\s*#(NO_APP|APP)$"), #inline ASM
re.compile("\s*#.*$"), # comment line
re.compile("\s*\.globa?l\s*([.a-zA-Z_][a-zA-Z0-9$_.]*)"), #global directive
re.compile("\s*\.(string|asciz|ascii|[1248]?byte|short|word|long|quad|value|zero)"),
]
keep_regexes = [
]
fn_label_def = re.compile("^[a-zA-Z_][a-zA-Z0-9_.]*:")
for l in asm.splitlines():
# Remove Mach-O attribute
l = l.replace('@GOTPCREL', '')
add_line = True
for reg in discard_regexes:
if reg.match(l) is not None:
add_line = False
break
for reg in keep_regexes:
if reg.match(l) is not None:
add_line = True
break
if add_line:
if fn_label_def.match(l) and len(new_contents) != 0:
new_contents += '\n'
l = process_identifiers(l)
new_contents += l
new_contents += '\n'
return new_contents | [
"def",
"process_asm",
"(",
"asm",
")",
":",
"new_contents",
"=",
"''",
"asm",
"=",
"transform_labels",
"(",
"asm",
")",
"# TODO: Add more things we want to remove",
"discard_regexes",
"=",
"[",
"re",
".",
"compile",
"(",
"\"\\s+\\..*$\"",
")",
",",
"# directive",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/third-party/benchmark/tools/strip_asm.py#L84-L121 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftfunctions/svg.py | python | get_line_style | (line_style, scale) | return "none" | Return a linestyle scaled by a factor. | Return a linestyle scaled by a factor. | [
"Return",
"a",
"linestyle",
"scaled",
"by",
"a",
"factor",
"."
] | def get_line_style(line_style, scale):
"""Return a linestyle scaled by a factor."""
style = None
if line_style == "Dashed":
style = param.GetString("svgDashedLine", "0.09,0.05")
elif line_style == "Dashdot":
style = param.GetString("svgDashdotLine", "0.09,0.05,0.02,0.05")
elif line_style == "Dotted":
style = param.GetString("svgDottedLine", "0.02,0.02")
elif line_style:
if "," in line_style:
style = line_style
if style:
style = style.split(",")
try:
# scale dashes
style = ",".join([str(float(d)/scale) for d in style])
# print("lstyle ", style)
except Exception:
# TODO: trap only specific exception; what is the problem?
# Bad string specification?
return "none"
else:
return style
return "none" | [
"def",
"get_line_style",
"(",
"line_style",
",",
"scale",
")",
":",
"style",
"=",
"None",
"if",
"line_style",
"==",
"\"Dashed\"",
":",
"style",
"=",
"param",
".",
"GetString",
"(",
"\"svgDashedLine\"",
",",
"\"0.09,0.05\"",
")",
"elif",
"line_style",
"==",
"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftfunctions/svg.py#L58-L85 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py | python | Style.theme_names | (self) | return self.tk.call(self._name, "theme", "names") | Returns a list of all known themes. | Returns a list of all known themes. | [
"Returns",
"a",
"list",
"of",
"all",
"known",
"themes",
"."
] | def theme_names(self):
"""Returns a list of all known themes."""
return self.tk.call(self._name, "theme", "names") | [
"def",
"theme_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_name",
",",
"\"theme\"",
",",
"\"names\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L508-L510 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/third_party/jinja2/parser.py | python | Parser.parse_for | (self) | return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno) | Parse a for loop. | Parse a for loop. | [
"Parse",
"a",
"for",
"loop",
"."
] | def parse_for(self):
"""Parse a for loop."""
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
test = self.parse_expression()
recursive = self.stream.skip_if('name:recursive')
body = self.parse_statements(('name:endfor', 'name:else'))
if next(self.stream).value == 'endfor':
else_ = []
else:
else_ = self.parse_statements(('name:endfor',), drop_needle=True)
return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno) | [
"def",
"parse_for",
"(",
"self",
")",
":",
"lineno",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name:for'",
")",
".",
"lineno",
"target",
"=",
"self",
".",
"parse_assign_target",
"(",
"extra_end_rules",
"=",
"(",
"'name:in'",
",",
")",
")",
"self"... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/parser.py#L178-L195 | |
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | alarm-clock/python/iot_alarm_clock/hardware/dfrobot.py | python | DfrobotBoard.start_buzzer | (self) | Start the hardware buzzer. | Start the hardware buzzer. | [
"Start",
"the",
"hardware",
"buzzer",
"."
] | def start_buzzer(self):
"""
Start the hardware buzzer.
"""
self.buzzer.write(1) | [
"def",
"start_buzzer",
"(",
"self",
")",
":",
"self",
".",
"buzzer",
".",
"write",
"(",
"1",
")"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/alarm-clock/python/iot_alarm_clock/hardware/dfrobot.py#L96-L102 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Window.SetVirtualSizeWH | (*args, **kwargs) | return _core_.Window_SetVirtualSizeWH(*args, **kwargs) | SetVirtualSizeWH(self, int w, int h)
Set the the virtual size of a window in pixels. For most windows this
is just the client area of the window, but for some like scrolled
windows it is more or less independent of the screen window size. | SetVirtualSizeWH(self, int w, int h) | [
"SetVirtualSizeWH",
"(",
"self",
"int",
"w",
"int",
"h",
")"
] | def SetVirtualSizeWH(*args, **kwargs):
"""
SetVirtualSizeWH(self, int w, int h)
Set the the virtual size of a window in pixels. For most windows this
is just the client area of the window, but for some like scrolled
windows it is more or less independent of the screen window size.
"""
return _core_.Window_SetVirtualSizeWH(*args, **kwargs) | [
"def",
"SetVirtualSizeWH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetVirtualSizeWH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L9814-L9822 | |
davidstutz/mesh-voxelization | 81a237c3b345062e364b180a8a4fc7ac98e107a4 | examples/occ_to_off.py | python | Mesh.__init__ | (self, vertices = [[]], faces = [[]], colors = [[]]) | Construct a mesh from vertices and faces.
:param vertices: list of vertices, or numpy array
:type vertices: [[float]] or numpy.ndarray
:param faces: list of faces or numpy array, i.e. the indices of the corresponding vertices per triangular face
:type faces: [[int]] or numpy.ndarray
:param colors: list of colors corresponding to faces, or numpy array
:type colors: [[int]] or numpy.ndarray | Construct a mesh from vertices and faces. | [
"Construct",
"a",
"mesh",
"from",
"vertices",
"and",
"faces",
"."
] | def __init__(self, vertices = [[]], faces = [[]], colors = [[]]):
"""
Construct a mesh from vertices and faces.
:param vertices: list of vertices, or numpy array
:type vertices: [[float]] or numpy.ndarray
:param faces: list of faces or numpy array, i.e. the indices of the corresponding vertices per triangular face
:type faces: [[int]] or numpy.ndarray
:param colors: list of colors corresponding to faces, or numpy array
:type colors: [[int]] or numpy.ndarray
"""
self.vertices = np.array(vertices, dtype = float)
""" (numpy.ndarray) Vertices. """
self.faces = np.array(faces, dtype = int)
""" (numpy.ndarray) Faces. """
self.colors = np.array(colors, dtype = int)
""" (numpy.ndarray) Colors. """
assert self.vertices.shape[1] == 3
assert self.faces.shape[1] == 3 | [
"def",
"__init__",
"(",
"self",
",",
"vertices",
"=",
"[",
"[",
"]",
"]",
",",
"faces",
"=",
"[",
"[",
"]",
"]",
",",
"colors",
"=",
"[",
"[",
"]",
"]",
")",
":",
"self",
".",
"vertices",
"=",
"np",
".",
"array",
"(",
"vertices",
",",
"dtype"... | https://github.com/davidstutz/mesh-voxelization/blob/81a237c3b345062e364b180a8a4fc7ac98e107a4/examples/occ_to_off.py#L95-L117 | ||
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py | python | _AddDescriptors | (message_descriptor, dictionary) | Sets up a new protocol message class dictionary.
Args:
message_descriptor: A Descriptor instance describing this message type.
dictionary: Class dictionary to which we'll add a '__slots__' entry. | Sets up a new protocol message class dictionary. | [
"Sets",
"up",
"a",
"new",
"protocol",
"message",
"class",
"dictionary",
"."
] | def _AddDescriptors(message_descriptor, dictionary):
"""Sets up a new protocol message class dictionary.
Args:
message_descriptor: A Descriptor instance describing this message type.
dictionary: Class dictionary to which we'll add a '__slots__' entry.
"""
dictionary['__descriptors'] = {}
for field in message_descriptor.fields:
dictionary['__descriptors'][field.name] = GetFieldDescriptor(
field.full_name)
dictionary['__slots__'] = list(dictionary['__descriptors'].iterkeys()) + [
'_cmsg', '_owner', '_composite_fields', 'Extensions', '_HACK_REFCOUNTS'] | [
"def",
"_AddDescriptors",
"(",
"message_descriptor",
",",
"dictionary",
")",
":",
"dictionary",
"[",
"'__descriptors'",
"]",
"=",
"{",
"}",
"for",
"field",
"in",
"message_descriptor",
".",
"fields",
":",
"dictionary",
"[",
"'__descriptors'",
"]",
"[",
"field",
... | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py#L391-L404 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/stubout.py | python | StubOutForTesting.Set | (self, parent, child_name, new_child) | Replace child_name's old definition with new_child, in the context
of the given parent. The parent could be a module when the child is a
function at module scope. Or the parent could be a class when a class'
method is being replaced. The named child is set to new_child, while
the prior definition is saved away for later, when UnsetAll() is called.
This method supports the case where child_name is a staticmethod or a
classmethod of parent. | Replace child_name's old definition with new_child, in the context
of the given parent. The parent could be a module when the child is a
function at module scope. Or the parent could be a class when a class'
method is being replaced. The named child is set to new_child, while
the prior definition is saved away for later, when UnsetAll() is called. | [
"Replace",
"child_name",
"s",
"old",
"definition",
"with",
"new_child",
"in",
"the",
"context",
"of",
"the",
"given",
"parent",
".",
"The",
"parent",
"could",
"be",
"a",
"module",
"when",
"the",
"child",
"is",
"a",
"function",
"at",
"module",
"scope",
".",... | def Set(self, parent, child_name, new_child):
"""Replace child_name's old definition with new_child, in the context
of the given parent. The parent could be a module when the child is a
function at module scope. Or the parent could be a class when a class'
method is being replaced. The named child is set to new_child, while
the prior definition is saved away for later, when UnsetAll() is called.
This method supports the case where child_name is a staticmethod or a
classmethod of parent.
"""
old_child = getattr(parent, child_name)
old_attribute = parent.__dict__.get(child_name)
if old_attribute is not None and isinstance(old_attribute, staticmethod):
old_child = staticmethod(old_child)
self.cache.append((parent, old_child, child_name))
setattr(parent, child_name, new_child) | [
"def",
"Set",
"(",
"self",
",",
"parent",
",",
"child_name",
",",
"new_child",
")",
":",
"old_child",
"=",
"getattr",
"(",
"parent",
",",
"child_name",
")",
"old_attribute",
"=",
"parent",
".",
"__dict__",
".",
"get",
"(",
"child_name",
")",
"if",
"old_a... | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/stubout.py#L109-L126 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/google/protobuf/internal/encoder.py | python | _SignedVarintEncoder | () | return EncodeSignedVarint | Return an encoder for a basic signed varint value (does not include
tag). | Return an encoder for a basic signed varint value (does not include
tag). | [
"Return",
"an",
"encoder",
"for",
"a",
"basic",
"signed",
"varint",
"value",
"(",
"does",
"not",
"include",
"tag",
")",
"."
] | def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value (does not include
tag)."""
def EncodeSignedVarint(write, value):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
write(six.int2byte(0x80|bits))
bits = value & 0x7f
value >>= 7
return write(six.int2byte(bits))
return EncodeSignedVarint | [
"def",
"_SignedVarintEncoder",
"(",
")",
":",
"def",
"EncodeSignedVarint",
"(",
"write",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"value",
"+=",
"(",
"1",
"<<",
"64",
")",
"bits",
"=",
"value",
"&",
"0x7f",
"value",
">>=",
"7",
"while",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/encoder.py#L384-L399 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/applications/vgg19.py | python | VGG19 | (include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000) | return model | Instantiates the VGG19 architecture.
Optionally loads weights pre-trained
on ImageNet. Note that when using TensorFlow,
for best performance you should set
`image_data_format="channels_last"` in your Keras config
at ~/.keras/keras.json.
The model and the weights are compatible with both
TensorFlow and Theano. The data format
convention used by the model is the one
specified in your Keras config file.
Arguments:
include_top: whether to include the 3 fully-connected
layers at the top of the network.
weights: one of `None` (random initialization)
or "imagenet" (pre-training on ImageNet).
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `channels_last` data format)
or `(3, 224, 224)` (with `channels_first` data format).
It should have exactly 3 input channels,
and width and height should be no smaller than 48.
E.g. `(200, 200, 3)` would be one valid value.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional layer.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
Returns:
A Keras model instance.
Raises:
ValueError: in case of invalid argument for `weights`,
or invalid input shape. | Instantiates the VGG19 architecture. | [
"Instantiates",
"the",
"VGG19",
"architecture",
"."
] | def VGG19(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000):
"""Instantiates the VGG19 architecture.
Optionally loads weights pre-trained
on ImageNet. Note that when using TensorFlow,
for best performance you should set
`image_data_format="channels_last"` in your Keras config
at ~/.keras/keras.json.
The model and the weights are compatible with both
TensorFlow and Theano. The data format
convention used by the model is the one
specified in your Keras config file.
Arguments:
include_top: whether to include the 3 fully-connected
layers at the top of the network.
weights: one of `None` (random initialization)
or "imagenet" (pre-training on ImageNet).
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `channels_last` data format)
or `(3, 224, 224)` (with `channels_first` data format).
It should have exactly 3 input channels,
and width and height should be no smaller than 48.
E.g. `(200, 200, 3)` would be one valid value.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional layer.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
Returns:
A Keras model instance.
Raises:
ValueError: in case of invalid argument for `weights`,
or invalid input shape.
"""
if weights not in {'imagenet', None}:
raise ValueError('The `weights` argument should be either '
'`None` (random initialization) or `imagenet` '
'(pre-training on ImageNet).')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as imagenet with `include_top`'
' as true, `classes` should be 1000')
# Determine proper input shape
input_shape = _obtain_input_shape(
input_shape,
default_size=224,
min_size=48,
data_format=K.image_data_format(),
require_flatten=include_top,
weights=weights)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
img_input = Input(tensor=input_tensor, shape=input_shape)
# Block 1
x = Conv2D(
64, (3, 3), activation='relu', padding='same',
name='block1_conv1')(img_input)
x = Conv2D(
64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
# Block 2
x = Conv2D(
128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
x = Conv2D(
128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
# Block 3
x = Conv2D(
256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
x = Conv2D(
256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
x = Conv2D(
256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
x = Conv2D(
256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
# Block 4
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
# Block 5
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
x = Conv2D(
512, (3, 3), activation='relu', padding='same', name='block5_conv4')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
if include_top:
# Classification block
x = Flatten(name='flatten')(x)
x = Dense(4096, activation='relu', name='fc1')(x)
x = Dense(4096, activation='relu', name='fc2')(x)
x = Dense(classes, activation='softmax', name='predictions')(x)
else:
if pooling == 'avg':
x = GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = GlobalMaxPooling2D()(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
model = Model(inputs, x, name='vgg19')
# load weights
if weights == 'imagenet':
if include_top:
weights_path = get_file(
'vgg19_weights_tf_dim_ordering_tf_kernels.h5',
WEIGHTS_PATH,
cache_subdir='models')
else:
weights_path = get_file(
'vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5',
WEIGHTS_PATH_NO_TOP,
cache_subdir='models')
model.load_weights(weights_path)
if K.backend() == 'theano':
layer_utils.convert_all_kernels_in_model(model)
if K.image_data_format() == 'channels_first':
if include_top:
maxpool = model.get_layer(name='block5_pool')
shape = maxpool.output_shape[1:]
dense = model.get_layer(name='fc1')
layer_utils.convert_dense_weights_data_format(dense, shape,
'channels_first')
return model | [
"def",
"VGG19",
"(",
"include_top",
"=",
"True",
",",
"weights",
"=",
"'imagenet'",
",",
"input_tensor",
"=",
"None",
",",
"input_shape",
"=",
"None",
",",
"pooling",
"=",
"None",
",",
"classes",
"=",
"1000",
")",
":",
"if",
"weights",
"not",
"in",
"{"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/applications/vgg19.py#L49-L218 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/setup.py | python | run | (config=('package.cfg',), ext=None, script_args=None, manifest_only=0) | return _core.setup(**kwargs) | Main runner | Main runner | [
"Main",
"runner"
] | def run(config=('package.cfg',), ext=None, script_args=None, manifest_only=0):
""" Main runner """
if ext is None:
ext = []
cfg = _util.SafeConfigParser()
cfg.read(config)
pkg = dict(cfg.items('package'))
python_min = pkg.get('python.min') or None
python_max = pkg.get('python.max') or None
check_python_version('python', python_min, python_max)
pypy_min = pkg.get('pypy.min') or None
pypy_max = pkg.get('pypy.max') or None
check_python_version('pypy', pypy_min, pypy_max)
jython_min = pkg.get('jython.min') or None
jython_max = pkg.get('jython.max') or None
check_python_version('jython', jython_min, jython_max)
manifest = dict(cfg.items('manifest'))
try:
docs = dict(cfg.items('docs'))
except _config_parser.NoSectionError:
docs = {}
summary, description = find_description(docs)
scripts = manifest.get('scripts', '').strip() or None
if scripts:
scripts = scripts.split()
modules = manifest.get('modules', '').strip() or None
if modules:
modules = modules.split()
keywords = docs.get('meta.keywords', '').strip() or None
if keywords:
keywords = keywords.split()
revision = pkg.get('version.revision', '').strip()
if revision:
revision = "-r%s" % (revision,)
kwargs = {
'name': pkg['name'],
'version': "%s%s" % (
pkg['version.number'],
["", "-dev%s" % (revision,)][_util.humanbool(
'version.dev', pkg.get('version.dev', 'false')
)],
),
'provides': find_provides(docs),
'description': summary,
'long_description': description,
'classifiers': find_classifiers(docs),
'keywords': keywords,
'author': pkg['author.name'],
'author_email': pkg['author.email'],
'maintainer': pkg.get('maintainer.name'),
'maintainer_email': pkg.get('maintainer.email'),
'url': pkg.get('url.homepage'),
'download_url': pkg.get('url.download'),
'license': find_license(docs),
'package_dir': {'': manifest.get('packages.lib', '.')},
'packages': find_packages(manifest),
'py_modules': modules,
'ext_modules': ext,
'scripts': scripts,
'script_args': script_args,
'data_files': find_data(pkg['name'], docs),
'cmdclass': {
'build' : _commands.Build,
'build_ext' : _commands.BuildExt,
'install' : _commands.Install,
'install_data': _commands.InstallData,
'install_lib' : _commands.InstallLib,
}
}
for key in ('provides',):
if key not in _core.setup_keywords:
del kwargs[key]
if manifest_only:
return make_manifest(manifest, config, docs, kwargs)
# monkey-patch crappy manifest writer away.
from distutils.command import sdist
sdist.sdist.get_file_list = sdist.sdist.read_manifest
return _core.setup(**kwargs) | [
"def",
"run",
"(",
"config",
"=",
"(",
"'package.cfg'",
",",
")",
",",
"ext",
"=",
"None",
",",
"script_args",
"=",
"None",
",",
"manifest_only",
"=",
"0",
")",
":",
"if",
"ext",
"is",
"None",
":",
"ext",
"=",
"[",
"]",
"cfg",
"=",
"_util",
".",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/setup.py#L335-L419 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/archive_util.py | python | unpack_archive | (filename, extract_dir, progress_filter=default_filter,
drivers=None) | Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
`progress_filter` is a function taking two arguments: a source path
internal to the archive ('/'-separated), and a filesystem path where it
will be extracted. The callback must return the desired extract path
(which may be the same as the one passed in), or else ``None`` to skip
that file or directory. The callback can thus be used to report on the
progress of the extraction, as well as to filter the items extracted or
alter their extraction paths.
`drivers`, if supplied, must be a non-empty sequence of functions with the
same signature as this function (minus the `drivers` argument), that raise
``UnrecognizedFormat`` if they do not support extracting the designated
archive type. The `drivers` are tried in sequence until one is found that
does not raise an error, or until all are exhausted (in which case
``UnrecognizedFormat`` is raised). If you do not supply a sequence of
drivers, the module's ``extraction_drivers`` constant will be used, which
means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
order. | Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` | [
"Unpack",
"filename",
"to",
"extract_dir",
"or",
"raise",
"UnrecognizedFormat"
] | def unpack_archive(filename, extract_dir, progress_filter=default_filter,
drivers=None):
"""Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
`progress_filter` is a function taking two arguments: a source path
internal to the archive ('/'-separated), and a filesystem path where it
will be extracted. The callback must return the desired extract path
(which may be the same as the one passed in), or else ``None`` to skip
that file or directory. The callback can thus be used to report on the
progress of the extraction, as well as to filter the items extracted or
alter their extraction paths.
`drivers`, if supplied, must be a non-empty sequence of functions with the
same signature as this function (minus the `drivers` argument), that raise
``UnrecognizedFormat`` if they do not support extracting the designated
archive type. The `drivers` are tried in sequence until one is found that
does not raise an error, or until all are exhausted (in which case
``UnrecognizedFormat`` is raised). If you do not supply a sequence of
drivers, the module's ``extraction_drivers`` constant will be used, which
means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
order.
"""
for driver in drivers or extraction_drivers:
try:
driver(filename, extract_dir, progress_filter)
except UnrecognizedFormat:
continue
else:
return
else:
raise UnrecognizedFormat(
"Not a recognized archive type: %s" % filename
) | [
"def",
"unpack_archive",
"(",
"filename",
",",
"extract_dir",
",",
"progress_filter",
"=",
"default_filter",
",",
"drivers",
"=",
"None",
")",
":",
"for",
"driver",
"in",
"drivers",
"or",
"extraction_drivers",
":",
"try",
":",
"driver",
"(",
"filename",
",",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/archive_util.py#L28-L60 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | _ExtractImportantEnvironment | (output_of_set) | return env | Extracts environment variables required for the toolchain to run from
a textual dump output by the cmd.exe 'set' command. | Extracts environment variables required for the toolchain to run from
a textual dump output by the cmd.exe 'set' command. | [
"Extracts",
"environment",
"variables",
"required",
"for",
"the",
"toolchain",
"to",
"run",
"from",
"a",
"textual",
"dump",
"output",
"by",
"the",
"cmd",
".",
"exe",
"set",
"command",
"."
] | def _ExtractImportantEnvironment(output_of_set):
"""Extracts environment variables required for the toolchain to run from
a textual dump output by the cmd.exe 'set' command."""
envvars_to_save = (
'goma_.*', # TODO(scottmg): This is ugly, but needed for goma.
'include',
'lib',
'libpath',
'path',
'pathext',
'systemroot',
'temp',
'tmp',
)
env = {}
for line in output_of_set.splitlines():
for envvar in envvars_to_save:
if re.match(envvar + '=', line.lower()):
var, setting = line.split('=', 1)
if envvar == 'path':
# Our own rules (for running gyp-win-tool) and other actions in
# Chromium rely on python being in the path. Add the path to this
# python here so that if it's not in the path when ninja is run
# later, python will still be found.
setting = os.path.dirname(sys.executable) + os.pathsep + setting
env[var.upper()] = setting
break
for required in ('SYSTEMROOT', 'TEMP', 'TMP'):
if required not in env:
raise Exception('Environment variable "%s" '
'required to be set to valid path' % required)
return env | [
"def",
"_ExtractImportantEnvironment",
"(",
"output_of_set",
")",
":",
"envvars_to_save",
"=",
"(",
"'goma_.*'",
",",
"# TODO(scottmg): This is ugly, but needed for goma.",
"'include'",
",",
"'lib'",
",",
"'libpath'",
",",
"'path'",
",",
"'pathext'",
",",
"'systemroot'",
... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L949-L980 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/libs/metaparse/tools/string_headers.py | python | Namespace.end | (self) | Generate the closing part | Generate the closing part | [
"Generate",
"the",
"closing",
"part"
] | def end(self):
"""Generate the closing part"""
for depth in xrange(len(self.names) - 1, -1, -1):
self.out_f.write('{0}}}\n'.format(self.prefix(depth))) | [
"def",
"end",
"(",
"self",
")",
":",
"for",
"depth",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"names",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"self",
".",
"out_f",
".",
"write",
"(",
"'{0}}}\\n'",
".",
"format",
"(",
"sel... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/libs/metaparse/tools/string_headers.py#L33-L36 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/filters.py | python | do_batch | (
value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
) | A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example:
.. sourcecode:: html+jinja
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table> | A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example: | [
"A",
"filter",
"that",
"batches",
"items",
".",
"It",
"works",
"pretty",
"much",
"like",
"slice",
"just",
"the",
"other",
"way",
"round",
".",
"It",
"returns",
"a",
"list",
"of",
"lists",
"with",
"the",
"given",
"number",
"of",
"items",
".",
"If",
"you... | def do_batch(
value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
) -> "t.Iterator[t.List[V]]":
"""
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example:
.. sourcecode:: html+jinja
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
"""
tmp: "t.List[V]" = []
for item in value:
if len(tmp) == linecount:
yield tmp
tmp = []
tmp.append(item)
if tmp:
if fill_with is not None and len(tmp) < linecount:
tmp += [fill_with] * (linecount - len(tmp))
yield tmp | [
"def",
"do_batch",
"(",
"value",
":",
"\"t.Iterable[V]\"",
",",
"linecount",
":",
"int",
",",
"fill_with",
":",
"\"t.Optional[V]\"",
"=",
"None",
")",
"->",
"\"t.Iterator[t.List[V]]\"",
":",
"tmp",
":",
"\"t.List[V]\"",
"=",
"[",
"]",
"for",
"item",
"in",
"v... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L1093-L1127 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py | python | fromfunction | (function, shape, **kwargs) | return function(*args, **kwargs) | Construct an array by executing a function over each coordinate.
The resulting array therefore has a value ``fn(x, y, z)`` at
coordinate ``(x, y, z)``.
Parameters
----------
function : callable
The function is called with N parameters, where N is the rank of
`shape`. Each parameter represents the coordinates of the array
varying along a specific axis. For example, if `shape`
were ``(2, 2)``, then the parameters would be
``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of
the coordinate arrays passed to `function`.
dtype : data-type, optional
Data-type of the coordinate arrays passed to `function`.
By default, `dtype` is float.
Returns
-------
fromfunction : any
The result of the call to `function` is passed back directly.
Therefore the shape of `fromfunction` is completely determined by
`function`. If `function` returns a scalar value, the shape of
`fromfunction` would not match the `shape` parameter.
See Also
--------
indices, meshgrid
Notes
-----
Keywords other than `dtype` are passed to `function`.
Examples
--------
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
[False, True, False],
[False, False, True]])
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]]) | Construct an array by executing a function over each coordinate. | [
"Construct",
"an",
"array",
"by",
"executing",
"a",
"function",
"over",
"each",
"coordinate",
"."
] | def fromfunction(function, shape, **kwargs):
"""
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value ``fn(x, y, z)`` at
coordinate ``(x, y, z)``.
Parameters
----------
function : callable
The function is called with N parameters, where N is the rank of
`shape`. Each parameter represents the coordinates of the array
varying along a specific axis. For example, if `shape`
were ``(2, 2)``, then the parameters would be
``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of
the coordinate arrays passed to `function`.
dtype : data-type, optional
Data-type of the coordinate arrays passed to `function`.
By default, `dtype` is float.
Returns
-------
fromfunction : any
The result of the call to `function` is passed back directly.
Therefore the shape of `fromfunction` is completely determined by
`function`. If `function` returns a scalar value, the shape of
`fromfunction` would not match the `shape` parameter.
See Also
--------
indices, meshgrid
Notes
-----
Keywords other than `dtype` are passed to `function`.
Examples
--------
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
[False, True, False],
[False, False, True]])
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
"""
dtype = kwargs.pop('dtype', float)
args = indices(shape, dtype=dtype)
return function(*args, **kwargs) | [
"def",
"fromfunction",
"(",
"function",
",",
"shape",
",",
"*",
"*",
"kwargs",
")",
":",
"dtype",
"=",
"kwargs",
".",
"pop",
"(",
"'dtype'",
",",
"float",
")",
"args",
"=",
"indices",
"(",
"shape",
",",
"dtype",
"=",
"dtype",
")",
"return",
"function... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py#L1726-L1779 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/frontend/context.py | python | SourcePath.join | (self, *p) | return SourcePath(self.context, mozpath.join(self.value, *p)) | Lazy mozpath.join(self, *p), returning a new SourcePath instance.
In an ideal world, this wouldn't be required, but with the
external_source_dir business, and the fact that comm-central and
mozilla-central have directories in common, resolving a SourcePath
before doing mozpath.join doesn't work out properly. | Lazy mozpath.join(self, *p), returning a new SourcePath instance. | [
"Lazy",
"mozpath",
".",
"join",
"(",
"self",
"*",
"p",
")",
"returning",
"a",
"new",
"SourcePath",
"instance",
"."
] | def join(self, *p):
"""Lazy mozpath.join(self, *p), returning a new SourcePath instance.
In an ideal world, this wouldn't be required, but with the
external_source_dir business, and the fact that comm-central and
mozilla-central have directories in common, resolving a SourcePath
before doing mozpath.join doesn't work out properly.
"""
return SourcePath(self.context, mozpath.join(self.value, *p)) | [
"def",
"join",
"(",
"self",
",",
"*",
"p",
")",
":",
"return",
"SourcePath",
"(",
"self",
".",
"context",
",",
"mozpath",
".",
"join",
"(",
"self",
".",
"value",
",",
"*",
"p",
")",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/frontend/context.py#L342-L350 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/__init__.py | python | StreamUnaryClientInterceptor.intercept_stream_unary | (self, continuation, client_call_details,
request_iterator) | Intercepts a stream-unary invocation asynchronously.
Args:
continuation: A function that proceeds with the invocation by
executing the next interceptor in chain or invoking the
actual RPC on the underlying Channel. It is the interceptor's
responsibility to call it if it decides to move the RPC forward.
The interceptor can use
`response_future = continuation(client_call_details, request_iterator)`
to continue with the RPC. `continuation` returns an object that is
both a Call for the RPC and a Future. In the event of RPC completion,
the return Call-Future's result value will be the response message
of the RPC. Should the event terminate with non-OK status, the
returned Call-Future's exception value will be an RpcError.
client_call_details: A ClientCallDetails object describing the
outgoing RPC.
request_iterator: An iterator that yields request values for the RPC.
Returns:
An object that is both a Call for the RPC and a Future.
In the event of RPC completion, the return Call-Future's
result value will be the response message of the RPC.
Should the event terminate with non-OK status, the returned
Call-Future's exception value will be an RpcError. | Intercepts a stream-unary invocation asynchronously. | [
"Intercepts",
"a",
"stream",
"-",
"unary",
"invocation",
"asynchronously",
"."
] | def intercept_stream_unary(self, continuation, client_call_details,
request_iterator):
"""Intercepts a stream-unary invocation asynchronously.
Args:
continuation: A function that proceeds with the invocation by
executing the next interceptor in chain or invoking the
actual RPC on the underlying Channel. It is the interceptor's
responsibility to call it if it decides to move the RPC forward.
The interceptor can use
`response_future = continuation(client_call_details, request_iterator)`
to continue with the RPC. `continuation` returns an object that is
both a Call for the RPC and a Future. In the event of RPC completion,
the return Call-Future's result value will be the response message
of the RPC. Should the event terminate with non-OK status, the
returned Call-Future's exception value will be an RpcError.
client_call_details: A ClientCallDetails object describing the
outgoing RPC.
request_iterator: An iterator that yields request values for the RPC.
Returns:
An object that is both a Call for the RPC and a Future.
In the event of RPC completion, the return Call-Future's
result value will be the response message of the RPC.
Should the event terminate with non-OK status, the returned
Call-Future's exception value will be an RpcError.
"""
raise NotImplementedError() | [
"def",
"intercept_stream_unary",
"(",
"self",
",",
"continuation",
",",
"client_call_details",
",",
"request_iterator",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/__init__.py#L498-L525 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetCflagsObjC | (self, configname) | return cflags_objc | Returns flags that need to be added to .m compilations. | Returns flags that need to be added to .m compilations. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"m",
"compilations",
"."
] | def GetCflagsObjC(self, configname):
"""Returns flags that need to be added to .m compilations."""
self.configname = configname
cflags_objc = []
self._AddObjectiveCGarbageCollectionFlags(cflags_objc)
self._AddObjectiveCARCFlags(cflags_objc)
self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc)
self.configname = None
return cflags_objc | [
"def",
"GetCflagsObjC",
"(",
"self",
",",
"configname",
")",
":",
"self",
".",
"configname",
"=",
"configname",
"cflags_objc",
"=",
"[",
"]",
"self",
".",
"_AddObjectiveCGarbageCollectionFlags",
"(",
"cflags_objc",
")",
"self",
".",
"_AddObjectiveCARCFlags",
"(",
... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L652-L660 | |
clasp-developers/clasp | 5287e5eb9bbd5e8da1e3a629a03d78bd71d01969 | debugger-tools/extend_lldb/print_function.py | python | lbt | (debugger, command, result, internal_dict) | Prints a simple stack trace of this thread. | Prints a simple stack trace of this thread. | [
"Prints",
"a",
"simple",
"stack",
"trace",
"of",
"this",
"thread",
"."
] | def lbt(debugger, command, result, internal_dict):
"""Prints a simple stack trace of this thread."""
target = debugger.GetSelectedTarget()
process = target.GetProcess()
thread = process.GetSelectedThread()
print("process id= %d" % process.GetProcessID() , file=result)
print("The number of frames = %d" % len(thread))
target = thread.GetProcess().GetTarget()
depth = thread.GetNumFrames()
mods = list(get_module_names(thread))
funcs = list(get_function_names(thread))
symbols = list(get_symbol_names(thread))
files = list(get_filenames(thread))
lines = list(get_line_numbers(thread))
addrs = list(get_pc_addresses(thread))
print("Backtrace to depth of %d" % depth)
if thread.GetStopReason() != lldb.eStopReasonInvalid:
desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason())
else:
desc = ""
print("Stack trace for thread id={0:#x} name={1} queue={2} ".format(
thread.GetThreadID(), thread.GetName(), thread.GetQueueName()) + desc,
file=result)
for i in range(depth):
try:
frame = thread.GetFrameAtIndex(i)
function = frame.GetFunction()
load_addr = addrs[i].GetLoadAddress(target)
if not function:
file_addr = addrs[i].GetFileAddress()
start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress()
symbol_offset = file_addr - start_addr
sym = symbols[i]
if (sym == None):
sym_start = extend_lldb.loadperf.lookup_address(load_addr)
if (sym_start):
sym = sym_start[0]
symbol_offset = load_addr-sym_start[1]
else:
sym = "UNKNOWN-SYM"
mmod = mods[i]
if (mmod == None):
mmod = ""
print(' frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}'.format(
num=i, addr=load_addr, mod=mmod, symbol=sym, offset=symbol_offset)
,file=result)
else:
print(' frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}'.format(
num=i, addr=load_addr, mod=mods[i],
func='%s [inlined]' % funcs[i] if frame.IsInlined() else funcs[i],
file=files[i], line=lines[i],
args=get_args_as_string(frame, showFuncName=False) if not frame.IsInlined() else '()')
,file=result)
except Error:
print("Could not print frame %d" % i)
print("Done backtrace") | [
"def",
"lbt",
"(",
"debugger",
",",
"command",
",",
"result",
",",
"internal_dict",
")",
":",
"target",
"=",
"debugger",
".",
"GetSelectedTarget",
"(",
")",
"process",
"=",
"target",
".",
"GetProcess",
"(",
")",
"thread",
"=",
"process",
".",
"GetSelectedT... | https://github.com/clasp-developers/clasp/blob/5287e5eb9bbd5e8da1e3a629a03d78bd71d01969/debugger-tools/extend_lldb/print_function.py#L307-L366 | ||
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/graph/common_lattices.py | python | Hypercube | (length: int, n_dim: int = 1, *, pbc: bool = True, **kwargs) | return Grid(length_vector, pbc=pbc, **kwargs) | r"""Constructs a hypercubic lattice with equal side length in all dimensions.
Periodic boundary conditions can also be imposed.
Args:
length: Side length of the hypercube; must always be >=1
n_dim: Dimension of the hypercube; must be at least 1.
pbc: Whether the hypercube should have periodic boundary conditions
(in all directions)
kwargs: Additional keyword arguments are passed on to the constructor of
:ref:`netket.graph.Lattice`.
Examples:
A 10x10x10 cubic lattice with periodic boundary conditions can be
constructed as follows:
>>> import netket
>>> g = netket.graph.Hypercube(10, n_dim=3, pbc=True)
>>> print(g.n_nodes)
1000 | r"""Constructs a hypercubic lattice with equal side length in all dimensions.
Periodic boundary conditions can also be imposed. | [
"r",
"Constructs",
"a",
"hypercubic",
"lattice",
"with",
"equal",
"side",
"length",
"in",
"all",
"dimensions",
".",
"Periodic",
"boundary",
"conditions",
"can",
"also",
"be",
"imposed",
"."
] | def Hypercube(length: int, n_dim: int = 1, *, pbc: bool = True, **kwargs) -> Lattice:
r"""Constructs a hypercubic lattice with equal side length in all dimensions.
Periodic boundary conditions can also be imposed.
Args:
length: Side length of the hypercube; must always be >=1
n_dim: Dimension of the hypercube; must be at least 1.
pbc: Whether the hypercube should have periodic boundary conditions
(in all directions)
kwargs: Additional keyword arguments are passed on to the constructor of
:ref:`netket.graph.Lattice`.
Examples:
A 10x10x10 cubic lattice with periodic boundary conditions can be
constructed as follows:
>>> import netket
>>> g = netket.graph.Hypercube(10, n_dim=3, pbc=True)
>>> print(g.n_nodes)
1000
"""
if not isinstance(length, int) or length <= 0:
raise TypeError("Argument `length` must be a positive integer")
length_vector = [length] * n_dim
return Grid(length_vector, pbc=pbc, **kwargs) | [
"def",
"Hypercube",
"(",
"length",
":",
"int",
",",
"n_dim",
":",
"int",
"=",
"1",
",",
"*",
",",
"pbc",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"->",
"Lattice",
":",
"if",
"not",
"isinstance",
"(",
"length",
",",
"int",
")",
"o... | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/graph/common_lattices.py#L142-L166 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/util/_doctools.py | python | TablePlotter.plot | (self, left, right, labels=None, vertical=True) | return fig | Plot left / right DataFrames in specified layout.
Parameters
----------
left : list of DataFrames before operation is applied
right : DataFrame of operation result
labels : list of str to be drawn as titles of left DataFrames
vertical : bool
If True, use vertical layout. If False, use horizontal layout. | Plot left / right DataFrames in specified layout. | [
"Plot",
"left",
"/",
"right",
"DataFrames",
"in",
"specified",
"layout",
"."
] | def plot(self, left, right, labels=None, vertical=True):
"""
Plot left / right DataFrames in specified layout.
Parameters
----------
left : list of DataFrames before operation is applied
right : DataFrame of operation result
labels : list of str to be drawn as titles of left DataFrames
vertical : bool
If True, use vertical layout. If False, use horizontal layout.
"""
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
if not isinstance(left, list):
left = [left]
left = [self._conv(l) for l in left]
right = self._conv(right)
hcells, vcells = self._get_cells(left, right, vertical)
if vertical:
figsize = self.cell_width * hcells, self.cell_height * vcells
else:
# include margin for titles
figsize = self.cell_width * hcells, self.cell_height * vcells
fig = plt.figure(figsize=figsize)
if vertical:
gs = gridspec.GridSpec(len(left), hcells)
# left
max_left_cols = max(self._shape(l)[1] for l in left)
max_left_rows = max(self._shape(l)[0] for l in left)
for i, (l, label) in enumerate(zip(left, labels)):
ax = fig.add_subplot(gs[i, 0:max_left_cols])
self._make_table(ax, l, title=label,
height=1.0 / max_left_rows)
# right
ax = plt.subplot(gs[:, max_left_cols:])
self._make_table(ax, right, title='Result', height=1.05 / vcells)
fig.subplots_adjust(top=0.9, bottom=0.05, left=0.05, right=0.95)
else:
max_rows = max(self._shape(df)[0] for df in left + [right])
height = 1.0 / np.max(max_rows)
gs = gridspec.GridSpec(1, hcells)
# left
i = 0
for l, label in zip(left, labels):
sp = self._shape(l)
ax = fig.add_subplot(gs[0, i:i + sp[1]])
self._make_table(ax, l, title=label, height=height)
i += sp[1]
# right
ax = plt.subplot(gs[0, i:])
self._make_table(ax, right, title='Result', height=height)
fig.subplots_adjust(top=0.85, bottom=0.05, left=0.05, right=0.95)
return fig | [
"def",
"plot",
"(",
"self",
",",
"left",
",",
"right",
",",
"labels",
"=",
"None",
",",
"vertical",
"=",
"True",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"matplotlib",
".",
"gridspec",
"as",
"gridspec",
"if",
"not",
"isin... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/util/_doctools.py#L45-L103 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | FlagValues.__contains__ | (self, name) | return name in self.FlagDict() | Returns True if name is a value (flag) in the dict. | Returns True if name is a value (flag) in the dict. | [
"Returns",
"True",
"if",
"name",
"is",
"a",
"value",
"(",
"flag",
")",
"in",
"the",
"dict",
"."
] | def __contains__(self, name):
"""Returns True if name is a value (flag) in the dict."""
return name in self.FlagDict() | [
"def",
"__contains__",
"(",
"self",
",",
"name",
")",
":",
"return",
"name",
"in",
"self",
".",
"FlagDict",
"(",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1180-L1182 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | script/update-makefiles.py | python | write_txt_file | (file_name, lines) | Write a text file with name `file_name` with the content given as a list of `lines` | Write a text file with name `file_name` with the content given as a list of `lines` | [
"Write",
"a",
"text",
"file",
"with",
"name",
"file_name",
"with",
"the",
"content",
"given",
"as",
"a",
"list",
"of",
"lines"
] | def write_txt_file(file_name, lines):
"""Write a text file with name `file_name` with the content given as a list of `lines`"""
with open(file_name, 'w') as file:
file.writelines(lines) | [
"def",
"write_txt_file",
"(",
"file_name",
",",
"lines",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'w'",
")",
"as",
"file",
":",
"file",
".",
"writelines",
"(",
"lines",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/script/update-makefiles.py#L58-L61 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/training/python/training/tuner.py | python | Tuner.next_trial | (self) | Switch to the next trial.
Ask the tuning service for a new trial for hyper-parameters tuning.
Returns:
A boolean indicating if a trial was assigned to the tuner.
Raises:
RuntimeError: If the tuner is initialized correctly. | Switch to the next trial. | [
"Switch",
"to",
"the",
"next",
"trial",
"."
] | def next_trial(self):
"""Switch to the next trial.
Ask the tuning service for a new trial for hyper-parameters tuning.
Returns:
A boolean indicating if a trial was assigned to the tuner.
Raises:
RuntimeError: If the tuner is initialized correctly.
"""
raise NotImplementedError("Calling an abstract method.") | [
"def",
"next_trial",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Calling an abstract method.\"",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/training/python/training/tuner.py#L49-L60 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | MaskedArray.__setstate__ | (self, state) | Restore the internal state of the masked array, for
pickling purposes. ``state`` is typically the output of the
``__getstate__`` output, and is a 5-tuple:
- class name
- a tuple giving the shape of the data
- a typecode for the data
- a binary string for the data
- a binary string for the mask. | Restore the internal state of the masked array, for
pickling purposes. ``state`` is typically the output of the
``__getstate__`` output, and is a 5-tuple: | [
"Restore",
"the",
"internal",
"state",
"of",
"the",
"masked",
"array",
"for",
"pickling",
"purposes",
".",
"state",
"is",
"typically",
"the",
"output",
"of",
"the",
"__getstate__",
"output",
"and",
"is",
"a",
"5",
"-",
"tuple",
":"
] | def __setstate__(self, state):
"""Restore the internal state of the masked array, for
pickling purposes. ``state`` is typically the output of the
``__getstate__`` output, and is a 5-tuple:
- class name
- a tuple giving the shape of the data
- a typecode for the data
- a binary string for the data
- a binary string for the mask.
"""
(_, shp, typ, isf, raw, msk, flv) = state
super(MaskedArray, self).__setstate__((shp, typ, isf, raw))
self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk))
self.fill_value = flv | [
"def",
"__setstate__",
"(",
"self",
",",
"state",
")",
":",
"(",
"_",
",",
"shp",
",",
"typ",
",",
"isf",
",",
"raw",
",",
"msk",
",",
"flv",
")",
"=",
"state",
"super",
"(",
"MaskedArray",
",",
"self",
")",
".",
"__setstate__",
"(",
"(",
"shp",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L6106-L6121 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/imports.py | python | TomboyHandler.notebook_exist_or_create | (self, notebook_title) | return self.dest_notebooks_dom_nodes[notebook_title] | Check if there's already a notebook with this title | Check if there's already a notebook with this title | [
"Check",
"if",
"there",
"s",
"already",
"a",
"notebook",
"with",
"this",
"title"
] | def notebook_exist_or_create(self, notebook_title):
"""Check if there's already a notebook with this title"""
if not notebook_title in self.dest_notebooks_dom_nodes:
self.dest_notebooks_dom_nodes[notebook_title] = self.dom.createElement("node")
self.dest_notebooks_dom_nodes[notebook_title].setAttribute("name", notebook_title)
self.dest_notebooks_dom_nodes[notebook_title].setAttribute("prog_lang", cons.RICH_TEXT_ID)
self.dest_top_dom.appendChild(self.dest_notebooks_dom_nodes[notebook_title])
return self.dest_notebooks_dom_nodes[notebook_title] | [
"def",
"notebook_exist_or_create",
"(",
"self",
",",
"notebook_title",
")",
":",
"if",
"not",
"notebook_title",
"in",
"self",
".",
"dest_notebooks_dom_nodes",
":",
"self",
".",
"dest_notebooks_dom_nodes",
"[",
"notebook_title",
"]",
"=",
"self",
".",
"dom",
".",
... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/imports.py#L1309-L1316 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/integrate/quadpack.py | python | _OptFunc.__call__ | (self, *args) | return self.opt | Return stored dict. | Return stored dict. | [
"Return",
"stored",
"dict",
"."
] | def __call__(self, *args):
"""Return stored dict."""
return self.opt | [
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"opt"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/integrate/quadpack.py#L727-L729 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicle.py | python | VehicleDomain.getTau | (self, vehID) | return self._getUniversal(tc.VAR_TAU, vehID) | getTau(string) -> double
Returns the driver's desired (minimum) headway time in s for this vehicle. | getTau(string) -> double | [
"getTau",
"(",
"string",
")",
"-",
">",
"double"
] | def getTau(self, vehID):
"""getTau(string) -> double
Returns the driver's desired (minimum) headway time in s for this vehicle.
"""
return self._getUniversal(tc.VAR_TAU, vehID) | [
"def",
"getTau",
"(",
"self",
",",
"vehID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_TAU",
",",
"vehID",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L682-L687 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiTabContainer.ButtonHitTest | (self, x, y) | return None | Tests if a button was hit.
:param integer `x`: the mouse `x` position;
:param integer `y`: the mouse `y` position.
:returns: and instance of :class:`AuiTabContainerButton` if a button was hit, ``None`` otherwise. | Tests if a button was hit. | [
"Tests",
"if",
"a",
"button",
"was",
"hit",
"."
] | def ButtonHitTest(self, x, y):
"""
Tests if a button was hit.
:param integer `x`: the mouse `x` position;
:param integer `y`: the mouse `y` position.
:returns: and instance of :class:`AuiTabContainerButton` if a button was hit, ``None`` otherwise.
"""
if not self._rect.Contains((x,y)):
return None
for button in self._buttons:
if button.rect.Contains((x,y)) and \
(button.cur_state & (AUI_BUTTON_STATE_HIDDEN|AUI_BUTTON_STATE_DISABLED)) == 0:
return button
for button in self._tab_close_buttons:
if button.rect.Contains((x,y)) and \
(button.cur_state & (AUI_BUTTON_STATE_HIDDEN|AUI_BUTTON_STATE_DISABLED)) == 0:
return button
return None | [
"def",
"ButtonHitTest",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"not",
"self",
".",
"_rect",
".",
"Contains",
"(",
"(",
"x",
",",
"y",
")",
")",
":",
"return",
"None",
"for",
"button",
"in",
"self",
".",
"_buttons",
":",
"if",
"button",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L1726-L1749 | |
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/streaming_aead/_streaming_aead.py | python | StreamingAead.new_encrypting_stream | (self, ciphertext_destination: BinaryIO,
associated_data: bytes) | Returns an encrypting stream that writes to ciphertext_destination.
The returned stream implements a writable but not seekable io.BufferedIOBase
interface. It only accepts binary data. For text, it needs to be wrapped
with io.TextIOWrapper.
The ciphertext_destination's write() method is expected to present one of
the following three behaviours in the case of a partial or failed write():
- return a non-negative integer number of bytes written
- return None (equivalent to returning 0)
- raise BlockingIOError with characters_written set correctly to a
non-negative integer (equivalent to returning that integer)
In the case of a full write, the number of bytes written should be returned.
The standard io.BufferedIOBase and io.RawIOBase base classes exhibit these
behaviours and are hence supported.
Args:
ciphertext_destination: A writable binary file object to which ciphertext
will be written. It must support write(), close(), closed, and
writable().
associated_data: Associated data to be used by the AEAD encryption. It is
not included in the ciphertext and must be passed in as a parameter for
decryption.
Returns:
An implementation of the io.RawIOBase interface that wraps around
'ciphertext_destination', such that any bytes written to the wrapper are
AEAD-encrypted using 'associated_data' as associated authenticated data.
Closing this wrapper also closes the ciphertext_source.
Raises:
tink.TinkError if the creation fails. | Returns an encrypting stream that writes to ciphertext_destination. | [
"Returns",
"an",
"encrypting",
"stream",
"that",
"writes",
"to",
"ciphertext_destination",
"."
] | def new_encrypting_stream(self, ciphertext_destination: BinaryIO,
associated_data: bytes) -> BinaryIO:
"""Returns an encrypting stream that writes to ciphertext_destination.
The returned stream implements a writable but not seekable io.BufferedIOBase
interface. It only accepts binary data. For text, it needs to be wrapped
with io.TextIOWrapper.
The ciphertext_destination's write() method is expected to present one of
the following three behaviours in the case of a partial or failed write():
- return a non-negative integer number of bytes written
- return None (equivalent to returning 0)
- raise BlockingIOError with characters_written set correctly to a
non-negative integer (equivalent to returning that integer)
In the case of a full write, the number of bytes written should be returned.
The standard io.BufferedIOBase and io.RawIOBase base classes exhibit these
behaviours and are hence supported.
Args:
ciphertext_destination: A writable binary file object to which ciphertext
will be written. It must support write(), close(), closed, and
writable().
associated_data: Associated data to be used by the AEAD encryption. It is
not included in the ciphertext and must be passed in as a parameter for
decryption.
Returns:
An implementation of the io.RawIOBase interface that wraps around
'ciphertext_destination', such that any bytes written to the wrapper are
AEAD-encrypted using 'associated_data' as associated authenticated data.
Closing this wrapper also closes the ciphertext_source.
Raises:
tink.TinkError if the creation fails.
"""
raise NotImplementedError() | [
"def",
"new_encrypting_stream",
"(",
"self",
",",
"ciphertext_destination",
":",
"BinaryIO",
",",
"associated_data",
":",
"bytes",
")",
"->",
"BinaryIO",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/streaming_aead/_streaming_aead.py#L33-L67 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/lookup.py | python | RosdepLookup.resolve | (self, rosdep_key, resource_name, installer_context) | return installer_key, resolution, dependencies | Resolve a :class:`RosdepDefinition` for a particular
os/version spec.
:param resource_name: resource (e.g. ROS package) to resolve key within
:param rosdep_key: rosdep key to resolve
:param os_name: OS name to use for resolution
:param os_version: OS name to use for resolution
:returns: *(installer_key, resolution, dependencies)*, ``(str,
[opaque], [str])``. *resolution* are the system
dependencies for the specified installer. The value is an
opaque list and meant to be interpreted by the
installer. *dependencies* is a list of rosdep keys that the
definition depends on.
:raises: :exc:`ResolutionError` If *rosdep_key* cannot be resolved for *resource_name* in *installer_context*
:raises: :exc:`rospkg.ResourceNotFound` if *resource_name* cannot be located | Resolve a :class:`RosdepDefinition` for a particular
os/version spec. | [
"Resolve",
"a",
":",
"class",
":",
"RosdepDefinition",
"for",
"a",
"particular",
"os",
"/",
"version",
"spec",
"."
] | def resolve(self, rosdep_key, resource_name, installer_context):
"""
Resolve a :class:`RosdepDefinition` for a particular
os/version spec.
:param resource_name: resource (e.g. ROS package) to resolve key within
:param rosdep_key: rosdep key to resolve
:param os_name: OS name to use for resolution
:param os_version: OS name to use for resolution
:returns: *(installer_key, resolution, dependencies)*, ``(str,
[opaque], [str])``. *resolution* are the system
dependencies for the specified installer. The value is an
opaque list and meant to be interpreted by the
installer. *dependencies* is a list of rosdep keys that the
definition depends on.
:raises: :exc:`ResolutionError` If *rosdep_key* cannot be resolved for *resource_name* in *installer_context*
:raises: :exc:`rospkg.ResourceNotFound` if *resource_name* cannot be located
"""
os_name, os_version = installer_context.get_os_name_and_version()
view = self.get_rosdep_view_for_resource(resource_name)
if view is None:
raise ResolutionError(rosdep_key, None, os_name, os_version, "[%s] does not have a rosdep view"%(resource_name))
try:
#print("KEYS", view.rosdep_defs.keys())
definition = view.lookup(rosdep_key)
except KeyError:
rd_debug(view)
raise ResolutionError(rosdep_key, None, os_name, os_version, "Cannot locate rosdep definition for [%s]"%(rosdep_key))
# check cache: the main motivation for the cache is that
# source rosdeps are expensive to resolve
if rosdep_key in self._resolve_cache:
cache_value = self._resolve_cache[rosdep_key]
cache_os_name = cache_value[0]
cache_os_version = cache_value[1]
cache_view_name = cache_value[2]
if cache_os_name == os_name and \
cache_os_version == os_version and \
cache_view_name == view.name:
return cache_value[3:]
# get the rosdep data for the platform
try:
installer_keys = installer_context.get_os_installer_keys(os_name)
default_key = installer_context.get_default_os_installer_key(os_name)
except KeyError:
raise ResolutionError(rosdep_key, definition.data, os_name, os_version, "Unsupported OS [%s]"%(os_name))
installer_key, rosdep_args_dict = definition.get_rule_for_platform(os_name, os_version, installer_keys, default_key)
# resolve the rosdep data for the platform
try:
installer = installer_context.get_installer(installer_key)
except KeyError:
raise ResolutionError(rosdep_key, definition.data, os_name, os_version, "Unsupported installer [%s]"%(installer_key))
resolution = installer.resolve(rosdep_args_dict)
dependencies = installer.get_depends(rosdep_args_dict)
# cache value
self._resolve_cache[rosdep_key] = os_name, os_version, view.name, installer_key, resolution, dependencies
return installer_key, resolution, dependencies | [
"def",
"resolve",
"(",
"self",
",",
"rosdep_key",
",",
"resource_name",
",",
"installer_context",
")",
":",
"os_name",
",",
"os_version",
"=",
"installer_context",
".",
"get_os_name_and_version",
"(",
")",
"view",
"=",
"self",
".",
"get_rosdep_view_for_resource",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/lookup.py#L423-L486 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/poplib.py | python | POP3.rpop | (self, user) | return self._shortcmd('RPOP %s' % user) | Not sure what this does. | Not sure what this does. | [
"Not",
"sure",
"what",
"this",
"does",
"."
] | def rpop(self, user):
"""Not sure what this does."""
return self._shortcmd('RPOP %s' % user) | [
"def",
"rpop",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"_shortcmd",
"(",
"'RPOP %s'",
"%",
"user",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/poplib.py#L264-L266 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/setup.py | python | find_provides | (docs) | return [] | Determine provides from PROVIDES
:return: List of provides (``['provides', ...]``)
:rtype: ``list`` | Determine provides from PROVIDES | [
"Determine",
"provides",
"from",
"PROVIDES"
] | def find_provides(docs):
"""
Determine provides from PROVIDES
:return: List of provides (``['provides', ...]``)
:rtype: ``list``
"""
filename = docs.get('meta.provides', 'PROVIDES').strip()
if filename and _os.path.isfile(filename):
fp = open(filename, encoding='utf-8')
try:
content = fp.read()
finally:
fp.close()
content = [item.strip() for item in content.splitlines()]
return [item for item in content if item and not item.startswith('#')]
return [] | [
"def",
"find_provides",
"(",
"docs",
")",
":",
"filename",
"=",
"docs",
".",
"get",
"(",
"'meta.provides'",
",",
"'PROVIDES'",
")",
".",
"strip",
"(",
")",
"if",
"filename",
"and",
"_os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"fp",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/setup.py#L139-L155 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/bond_core/smclib/python/smclib/statemap.py | python | FSMContext.getDebugFlag | (self) | return self._debug_flag | Returns the debug flag's current setting. | Returns the debug flag's current setting. | [
"Returns",
"the",
"debug",
"flag",
"s",
"current",
"setting",
"."
] | def getDebugFlag(self):
"""Returns the debug flag's current setting."""
return self._debug_flag | [
"def",
"getDebugFlag",
"(",
"self",
")",
":",
"return",
"self",
".",
"_debug_flag"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/bond_core/smclib/python/smclib/statemap.py#L84-L86 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py | python | find_next_tag | (file_desc: io.BufferedReader) | Get next tag in the file
:param file_desc:file descriptor
:return: string like '<sometag>' | Get next tag in the file
:param file_desc:file descriptor
:return: string like '<sometag>' | [
"Get",
"next",
"tag",
"in",
"the",
"file",
":",
"param",
"file_desc",
":",
"file",
"descriptor",
":",
"return",
":",
"string",
"like",
"<sometag",
">"
] | def find_next_tag(file_desc: io.BufferedReader) -> str:
"""
Get next tag in the file
:param file_desc:file descriptor
:return: string like '<sometag>'
"""
tag = b''
while True:
symbol = file_desc.read(1)
if symbol == b'':
raise Error('Unexpected end of Kaldi model')
if tag == b'' and symbol != b'<':
continue
elif symbol == b'<':
tag = b''
tag += symbol
if symbol != b'>':
continue
try:
return tag.decode('ascii')
except UnicodeDecodeError:
# Tag in Kaldi model always in ascii encoding
tag = b'' | [
"def",
"find_next_tag",
"(",
"file_desc",
":",
"io",
".",
"BufferedReader",
")",
"->",
"str",
":",
"tag",
"=",
"b''",
"while",
"True",
":",
"symbol",
"=",
"file_desc",
".",
"read",
"(",
"1",
")",
"if",
"symbol",
"==",
"b''",
":",
"raise",
"Error",
"(... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py#L149-L171 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/build/property.py | python | PropertyMap.find | (self, properties) | return self.find_replace (properties) | Return the value associated with properties
or any subset of it. If more than one
subset has value assigned to it, return the
value for the longest subset, if it's unique. | Return the value associated with properties
or any subset of it. If more than one
subset has value assigned to it, return the
value for the longest subset, if it's unique. | [
"Return",
"the",
"value",
"associated",
"with",
"properties",
"or",
"any",
"subset",
"of",
"it",
".",
"If",
"more",
"than",
"one",
"subset",
"has",
"value",
"assigned",
"to",
"it",
"return",
"the",
"value",
"for",
"the",
"longest",
"subset",
"if",
"it",
... | def find (self, properties):
""" Return the value associated with properties
or any subset of it. If more than one
subset has value assigned to it, return the
value for the longest subset, if it's unique.
"""
return self.find_replace (properties) | [
"def",
"find",
"(",
"self",
",",
"properties",
")",
":",
"return",
"self",
".",
"find_replace",
"(",
"properties",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/property.py#L444-L450 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32comext/authorization/demos/EditServiceSecurity.py | python | ServiceSecurity.PropertySheetPageCallback | (self, hwnd, msg, pagetype) | return None | Invoked each time a property sheet page is created or destroyed. | Invoked each time a property sheet page is created or destroyed. | [
"Invoked",
"each",
"time",
"a",
"property",
"sheet",
"page",
"is",
"created",
"or",
"destroyed",
"."
] | def PropertySheetPageCallback(self, hwnd, msg, pagetype):
"""Invoked each time a property sheet page is created or destroyed."""
## page types from SI_PAGE_TYPE enum: SI_PAGE_PERM SI_PAGE_ADVPERM SI_PAGE_AUDIT SI_PAGE_OWNER
## msg: PSPCB_CREATE, PSPCB_RELEASE, PSPCB_SI_INITDIALOG
return None | [
"def",
"PropertySheetPageCallback",
"(",
"self",
",",
"hwnd",
",",
"msg",
",",
"pagetype",
")",
":",
"## page types from SI_PAGE_TYPE enum: SI_PAGE_PERM SI_PAGE_ADVPERM SI_PAGE_AUDIT SI_PAGE_OWNER",
"## msg: PSPCB_CREATE, PSPCB_RELEASE, PSPCB_SI_INITDIALOG",
"return",
"None"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32comext/authorization/demos/EditServiceSecurity.py#L115-L119 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/bliptvXSL_api.py | python | xpathFunctions.bliptvFlvLinkGeneration | (self, context, arg) | Generate a link for the Blip.tv site.
Call example: 'mnvXpath:bliptvFlvLinkGeneration(.)'
return the url link | Generate a link for the Blip.tv site.
Call example: 'mnvXpath:bliptvFlvLinkGeneration(.)'
return the url link | [
"Generate",
"a",
"link",
"for",
"the",
"Blip",
".",
"tv",
"site",
".",
"Call",
"example",
":",
"mnvXpath",
":",
"bliptvFlvLinkGeneration",
"(",
".",
")",
"return",
"the",
"url",
"link"
] | def bliptvFlvLinkGeneration(self, context, arg):
'''Generate a link for the Blip.tv site.
Call example: 'mnvXpath:bliptvFlvLinkGeneration(.)'
return the url link
'''
flvFile = self.flvFilter(arg[0])
if len(flvFile):
flvFileLink = flvFile[0].attrib['url']
return '%s%s' % (common.linkWebPage('dummy', 'bliptv'), flvFileLink.replace('.flv', '').replace('http://blip.tv/file/get/', ''))
else:
return self.linkFilter(arg[0])[0] | [
"def",
"bliptvFlvLinkGeneration",
"(",
"self",
",",
"context",
",",
"arg",
")",
":",
"flvFile",
"=",
"self",
".",
"flvFilter",
"(",
"arg",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"flvFile",
")",
":",
"flvFileLink",
"=",
"flvFile",
"[",
"0",
"]",
".",
... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/bliptvXSL_api.py#L128-L138 | ||
GeometryCollective/boundary-first-flattening | 8250e5a0e85980ec50b5e8aa8f49dd6519f915cd | deps/nanogui/docs/exhale.py | python | ExhaleRoot.generateAPIRootSummary | (self) | Writes the library API root summary to the main library file. See the
documentation for the key ``afterBodySummary`` in :func:`exhale.generate`. | Writes the library API root summary to the main library file. See the
documentation for the key ``afterBodySummary`` in :func:`exhale.generate`. | [
"Writes",
"the",
"library",
"API",
"root",
"summary",
"to",
"the",
"main",
"library",
"file",
".",
"See",
"the",
"documentation",
"for",
"the",
"key",
"afterBodySummary",
"in",
":",
"func",
":",
"exhale",
".",
"generate",
"."
] | def generateAPIRootSummary(self):
'''
Writes the library API root summary to the main library file. See the
documentation for the key ``afterBodySummary`` in :func:`exhale.generate`.
'''
try:
with open(self.full_root_file_path, "a") as generated_index:
generated_index.write("{}\n\n".format(self.root_file_summary))
except Exception as e:
exclaimError("Unable to create the root api summary: {}".format(e)) | [
"def",
"generateAPIRootSummary",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"full_root_file_path",
",",
"\"a\"",
")",
"as",
"generated_index",
":",
"generated_index",
".",
"write",
"(",
"\"{}\\n\\n\"",
".",
"format",
"(",
"self",
".... | https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/docs/exhale.py#L2908-L2917 | ||
UlordChain/UlordChain | b6288141e9744e89b1901f330c3797ff5f161d62 | contrib/devtools/security-check.py | python | check_ELF_NX | (executable) | return have_gnu_stack and not have_wx | Check that no sections are writable and executable (including the stack) | Check that no sections are writable and executable (including the stack) | [
"Check",
"that",
"no",
"sections",
"are",
"writable",
"and",
"executable",
"(",
"including",
"the",
"stack",
")"
] | def check_ELF_NX(executable):
'''
Check that no sections are writable and executable (including the stack)
'''
have_wx = False
have_gnu_stack = False
for (typ, flags) in get_ELF_program_headers(executable):
if typ == 'GNU_STACK':
have_gnu_stack = True
if 'W' in flags and 'E' in flags: # section is both writable and executable
have_wx = True
return have_gnu_stack and not have_wx | [
"def",
"check_ELF_NX",
"(",
"executable",
")",
":",
"have_wx",
"=",
"False",
"have_gnu_stack",
"=",
"False",
"for",
"(",
"typ",
",",
"flags",
")",
"in",
"get_ELF_program_headers",
"(",
"executable",
")",
":",
"if",
"typ",
"==",
"'GNU_STACK'",
":",
"have_gnu_... | https://github.com/UlordChain/UlordChain/blob/b6288141e9744e89b1901f330c3797ff5f161d62/contrib/devtools/security-check.py#L61-L72 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/format.py | python | read_array | (fp, allow_pickle=False, pickle_kwargs=None) | return array | Read an array from an NPY file.
Parameters
----------
fp : file_like object
If this is not a real file object, then this may take extra memory
and time.
allow_pickle : bool, optional
Whether to allow writing pickled data. Default: False
.. versionchanged:: 1.16.3
Made default False in response to CVE-2019-6446.
pickle_kwargs : dict
Additional keyword arguments to pass to pickle.load. These are only
useful when loading object arrays saved on Python 2 when using
Python 3.
Returns
-------
array : ndarray
The array from the data on disk.
Raises
------
ValueError
If the data is invalid, or allow_pickle=False and the file contains
an object array. | Read an array from an NPY file. | [
"Read",
"an",
"array",
"from",
"an",
"NPY",
"file",
"."
] | def read_array(fp, allow_pickle=False, pickle_kwargs=None):
"""
Read an array from an NPY file.
Parameters
----------
fp : file_like object
If this is not a real file object, then this may take extra memory
and time.
allow_pickle : bool, optional
Whether to allow writing pickled data. Default: False
.. versionchanged:: 1.16.3
Made default False in response to CVE-2019-6446.
pickle_kwargs : dict
Additional keyword arguments to pass to pickle.load. These are only
useful when loading object arrays saved on Python 2 when using
Python 3.
Returns
-------
array : ndarray
The array from the data on disk.
Raises
------
ValueError
If the data is invalid, or allow_pickle=False and the file contains
an object array.
"""
version = read_magic(fp)
_check_version(version)
shape, fortran_order, dtype = _read_array_header(fp, version)
if len(shape) == 0:
count = 1
else:
count = numpy.multiply.reduce(shape, dtype=numpy.int64)
# Now read the actual data.
if dtype.hasobject:
# The array contained Python objects. We need to unpickle the data.
if not allow_pickle:
raise ValueError("Object arrays cannot be loaded when "
"allow_pickle=False")
if pickle_kwargs is None:
pickle_kwargs = {}
try:
array = pickle.load(fp, **pickle_kwargs)
except UnicodeError as err:
if sys.version_info[0] >= 3:
# Friendlier error message
raise UnicodeError("Unpickling a python object failed: %r\n"
"You may need to pass the encoding= option "
"to numpy.load" % (err,))
raise
else:
if isfileobj(fp):
# We can use the fast fromfile() function.
array = numpy.fromfile(fp, dtype=dtype, count=count)
else:
# This is not a real file. We have to read it the
# memory-intensive way.
# crc32 module fails on reads greater than 2 ** 32 bytes,
# breaking large reads from gzip streams. Chunk reads to
# BUFFER_SIZE bytes to avoid issue and reduce memory overhead
# of the read. In non-chunked case count < max_read_count, so
# only one read is performed.
# Use np.ndarray instead of np.empty since the latter does
# not correctly instantiate zero-width string dtypes; see
# https://github.com/numpy/numpy/pull/6430
array = numpy.ndarray(count, dtype=dtype)
if dtype.itemsize > 0:
# If dtype.itemsize == 0 then there's nothing more to read
max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize)
for i in range(0, count, max_read_count):
read_count = min(max_read_count, count - i)
read_size = int(read_count * dtype.itemsize)
data = _read_bytes(fp, read_size, "array data")
array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype,
count=read_count)
if fortran_order:
array.shape = shape[::-1]
array = array.transpose()
else:
array.shape = shape
return array | [
"def",
"read_array",
"(",
"fp",
",",
"allow_pickle",
"=",
"False",
",",
"pickle_kwargs",
"=",
"None",
")",
":",
"version",
"=",
"read_magic",
"(",
"fp",
")",
"_check_version",
"(",
"version",
")",
"shape",
",",
"fortran_order",
",",
"dtype",
"=",
"_read_ar... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/format.py#L695-L787 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/utils/history.py | python | pipe_literal_representer | (dumper, data) | return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') | Create a representer for pipe literals, used internally for pyyaml. | Create a representer for pipe literals, used internally for pyyaml. | [
"Create",
"a",
"representer",
"for",
"pipe",
"literals",
"used",
"internally",
"for",
"pyyaml",
"."
] | def pipe_literal_representer(dumper, data):
"""Create a representer for pipe literals, used internally for pyyaml."""
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') | [
"def",
"pipe_literal_representer",
"(",
"dumper",
",",
"data",
")",
":",
"return",
"dumper",
".",
"represent_scalar",
"(",
"'tag:yaml.org,2002:str'",
",",
"data",
",",
"style",
"=",
"'|'",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/utils/history.py#L395-L397 | |
NERSC/timemory | 431912b360ff50d1a160d7826e2eea04fbd1037f | scripts/gprof2dot.py | python | DotWriter.wrap_function_name | (self, name) | return name | Split the function name on multiple lines. | Split the function name on multiple lines. | [
"Split",
"the",
"function",
"name",
"on",
"multiple",
"lines",
"."
] | def wrap_function_name(self, name):
"""Split the function name on multiple lines."""
if len(name) > 32:
ratio = 2.0/3.0
height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
width = max(len(name)/height, 32)
# TODO: break lines in symbols
name = textwrap.fill(name, width, break_long_words=False)
# Take away spaces
name = name.replace(", ", ",")
name = name.replace("> >", ">>")
name = name.replace("> >", ">>") # catch consecutive
return name | [
"def",
"wrap_function_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"len",
"(",
"name",
")",
">",
"32",
":",
"ratio",
"=",
"2.0",
"/",
"3.0",
"height",
"=",
"max",
"(",
"int",
"(",
"len",
"(",
"name",
")",
"/",
"(",
"1.0",
"-",
"ratio",
")",... | https://github.com/NERSC/timemory/blob/431912b360ff50d1a160d7826e2eea04fbd1037f/scripts/gprof2dot.py#L2974-L2989 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | bindings/experimental/distrdf/python/DistRDF/CppWorkflow.py | python | CppWorkflow._explore_graph | (self, node, range_id, parent_id) | Recursively traverses the graph nodes in DFS order and, for each of
them, adds a new node to the C++ workflow.
Args:
node (Node): object that contains the information to add the
corresponding node to the C++ workflow.
range_id (int): id of the current range. Needed to assign a name to a
partial Snapshot output file.
parent_id (int): id of the parent node in the C++ workflow. | Recursively traverses the graph nodes in DFS order and, for each of
them, adds a new node to the C++ workflow. | [
"Recursively",
"traverses",
"the",
"graph",
"nodes",
"in",
"DFS",
"order",
"and",
"for",
"each",
"of",
"them",
"adds",
"a",
"new",
"node",
"to",
"the",
"C",
"++",
"workflow",
"."
] | def _explore_graph(self, node, range_id, parent_id):
"""
Recursively traverses the graph nodes in DFS order and, for each of
them, adds a new node to the C++ workflow.
Args:
node (Node): object that contains the information to add the
corresponding node to the C++ workflow.
range_id (int): id of the current range. Needed to assign a name to a
partial Snapshot output file.
parent_id (int): id of the parent node in the C++ workflow.
"""
node_id = self.add_node(node.operation, range_id, parent_id)
for child_node in node.children:
self._explore_graph(child_node, range_id, node_id) | [
"def",
"_explore_graph",
"(",
"self",
",",
"node",
",",
"range_id",
",",
"parent_id",
")",
":",
"node_id",
"=",
"self",
".",
"add_node",
"(",
"node",
".",
"operation",
",",
"range_id",
",",
"parent_id",
")",
"for",
"child_node",
"in",
"node",
".",
"child... | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/experimental/distrdf/python/DistRDF/CppWorkflow.py#L120-L135 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | libcxx/utils/libcxx/sym_check/extract.py | python | extract_symbols | (lib_file, static_lib=None) | return extractor.extract(lib_file) | Extract and return a list of symbols extracted from a static or dynamic
library. The symbols are extracted using NM or readelf. They are then
filtered and formated. Finally they symbols are made unique. | Extract and return a list of symbols extracted from a static or dynamic
library. The symbols are extracted using NM or readelf. They are then
filtered and formated. Finally they symbols are made unique. | [
"Extract",
"and",
"return",
"a",
"list",
"of",
"symbols",
"extracted",
"from",
"a",
"static",
"or",
"dynamic",
"library",
".",
"The",
"symbols",
"are",
"extracted",
"using",
"NM",
"or",
"readelf",
".",
"They",
"are",
"then",
"filtered",
"and",
"formated",
... | def extract_symbols(lib_file, static_lib=None):
"""
Extract and return a list of symbols extracted from a static or dynamic
library. The symbols are extracted using NM or readelf. They are then
filtered and formated. Finally they symbols are made unique.
"""
if static_lib is None:
_, ext = os.path.splitext(lib_file)
static_lib = True if ext in ['.a'] else False
if ReadElfExtractor.find_tool() and not static_lib:
extractor = ReadElfExtractor(static_lib=static_lib)
else:
extractor = NMExtractor(static_lib=static_lib)
return extractor.extract(lib_file) | [
"def",
"extract_symbols",
"(",
"lib_file",
",",
"static_lib",
"=",
"None",
")",
":",
"if",
"static_lib",
"is",
"None",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"lib_file",
")",
"static_lib",
"=",
"True",
"if",
"ext",
"in",
... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/libcxx/utils/libcxx/sym_check/extract.py#L188-L201 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/models/link.py | python | Link.is_hash_allowed | (self, hashes) | return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash) | Return True if the link has a hash and it is allowed. | Return True if the link has a hash and it is allowed. | [
"Return",
"True",
"if",
"the",
"link",
"has",
"a",
"hash",
"and",
"it",
"is",
"allowed",
"."
] | def is_hash_allowed(self, hashes):
# type: (Optional[Hashes]) -> bool
"""
Return True if the link has a hash and it is allowed.
"""
if hashes is None or not self.has_hash:
return False
# Assert non-None so mypy knows self.hash_name and self.hash are str.
assert self.hash_name is not None
assert self.hash is not None
return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash) | [
"def",
"is_hash_allowed",
"(",
"self",
",",
"hashes",
")",
":",
"# type: (Optional[Hashes]) -> bool",
"if",
"hashes",
"is",
"None",
"or",
"not",
"self",
".",
"has_hash",
":",
"return",
"False",
"# Assert non-None so mypy knows self.hash_name and self.hash are str.",
"asse... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/models/link.py#L234-L245 | |
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/jedi/jedi/imports.py | python | strip_imports | (scopes) | return result | Here we strip the imports - they don't get resolved necessarily.
Really used anymore? Merge with remove_star_imports? | Here we strip the imports - they don't get resolved necessarily.
Really used anymore? Merge with remove_star_imports? | [
"Here",
"we",
"strip",
"the",
"imports",
"-",
"they",
"don",
"t",
"get",
"resolved",
"necessarily",
".",
"Really",
"used",
"anymore?",
"Merge",
"with",
"remove_star_imports?"
] | def strip_imports(scopes):
"""
Here we strip the imports - they don't get resolved necessarily.
Really used anymore? Merge with remove_star_imports?
"""
result = []
for s in scopes:
if isinstance(s, pr.Import):
result += ImportPath(s).follow()
else:
result.append(s)
return result | [
"def",
"strip_imports",
"(",
"scopes",
")",
":",
"result",
"=",
"[",
"]",
"for",
"s",
"in",
"scopes",
":",
"if",
"isinstance",
"(",
"s",
",",
"pr",
".",
"Import",
")",
":",
"result",
"+=",
"ImportPath",
"(",
"s",
")",
".",
"follow",
"(",
")",
"el... | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/imports.py#L377-L388 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/locale.py | python | resetlocale | (category=LC_ALL) | Sets the locale for category to the default setting.
The default setting is determined by calling
getdefaultlocale(). category defaults to LC_ALL. | Sets the locale for category to the default setting. | [
"Sets",
"the",
"locale",
"for",
"category",
"to",
"the",
"default",
"setting",
"."
] | def resetlocale(category=LC_ALL):
""" Sets the locale for category to the default setting.
The default setting is determined by calling
getdefaultlocale(). category defaults to LC_ALL.
"""
_setlocale(category, _build_localename(getdefaultlocale())) | [
"def",
"resetlocale",
"(",
"category",
"=",
"LC_ALL",
")",
":",
"_setlocale",
"(",
"category",
",",
"_build_localename",
"(",
"getdefaultlocale",
"(",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/locale.py#L610-L618 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/_basinhopping.py | python | AdaptiveStepsize.report | (self, accept, **kwargs) | called by basinhopping to report the result of the step | called by basinhopping to report the result of the step | [
"called",
"by",
"basinhopping",
"to",
"report",
"the",
"result",
"of",
"the",
"step"
] | def report(self, accept, **kwargs):
"called by basinhopping to report the result of the step"
if accept:
self.naccept += 1 | [
"def",
"report",
"(",
"self",
",",
"accept",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"accept",
":",
"self",
".",
"naccept",
"+=",
"1"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_basinhopping.py#L244-L247 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py | python | MyNavigationToolbar.is_zoom_mode | (self) | return self._myMode == MyNavigationToolbar.NAVIGATION_MODE_ZOOM | check whether the tool bar is in zoom mode
Returns
------- | check whether the tool bar is in zoom mode
Returns
------- | [
"check",
"whether",
"the",
"tool",
"bar",
"is",
"in",
"zoom",
"mode",
"Returns",
"-------"
] | def is_zoom_mode(self):
"""
check whether the tool bar is in zoom mode
Returns
-------
"""
return self._myMode == MyNavigationToolbar.NAVIGATION_MODE_ZOOM | [
"def",
"is_zoom_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_myMode",
"==",
"MyNavigationToolbar",
".",
"NAVIGATION_MODE_ZOOM"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py#L1833-L1840 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/mac_tool.py | python | MacTool._CommandifyName | (self, name_string) | return name_string.title().replace("-", "") | Transforms a tool name like copy-info-plist to CopyInfoPlist | Transforms a tool name like copy-info-plist to CopyInfoPlist | [
"Transforms",
"a",
"tool",
"name",
"like",
"copy",
"-",
"info",
"-",
"plist",
"to",
"CopyInfoPlist"
] | def _CommandifyName(self, name_string):
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
return name_string.title().replace("-", "") | [
"def",
"_CommandifyName",
"(",
"self",
",",
"name_string",
")",
":",
"return",
"name_string",
".",
"title",
"(",
")",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/mac_tool.py#L45-L47 | |
Komnomnomnom/swigibpy | cfd307fdbfaffabc69a2dc037538d7e34a8b8daf | swigibpy.py | python | OrderComboLeg.__eq__ | (self, other) | return _swigibpy.OrderComboLeg___eq__(self, other) | __eq__(OrderComboLeg self, OrderComboLeg other) -> bool | __eq__(OrderComboLeg self, OrderComboLeg other) -> bool | [
"__eq__",
"(",
"OrderComboLeg",
"self",
"OrderComboLeg",
"other",
")",
"-",
">",
"bool"
] | def __eq__(self, other):
"""__eq__(OrderComboLeg self, OrderComboLeg other) -> bool"""
return _swigibpy.OrderComboLeg___eq__(self, other) | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"_swigibpy",
".",
"OrderComboLeg___eq__",
"(",
"self",
",",
"other",
")"
] | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1822-L1824 | |
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/message.py | python | Message.SetInParent | (self) | Mark this as present in the parent.
This normally happens automatically when you assign a field of a
sub-message, but sometimes you want to make the sub-message
present while keeping it empty. If you find yourself using this,
you may want to reconsider your design. | Mark this as present in the parent. | [
"Mark",
"this",
"as",
"present",
"in",
"the",
"parent",
"."
] | def SetInParent(self):
"""Mark this as present in the parent.
This normally happens automatically when you assign a field of a
sub-message, but sometimes you want to make the sub-message
present while keeping it empty. If you find yourself using this,
you may want to reconsider your design."""
raise NotImplementedError | [
"def",
"SetInParent",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/message.py#L124-L131 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pickletools.py | python | read_long4 | (f) | return decode_long(data) | r"""
>>> import StringIO
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
255L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
32767L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
-256L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
-32768L
>>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
0L | r"""
>>> import StringIO
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
255L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
32767L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
-256L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
-32768L
>>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
0L | [
"r",
">>>",
"import",
"StringIO",
">>>",
"read_long4",
"(",
"StringIO",
".",
"StringIO",
"(",
"\\",
"x02",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"xff",
"\\",
"x00",
"))",
"255L",
">>>",
"read_long4",
"(",
"StringIO",
".",
"StringIO",
"(",
"\\",
... | def read_long4(f):
r"""
>>> import StringIO
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
255L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
32767L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
-256L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
-32768L
>>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
0L
"""
n = read_int4(f)
if n < 0:
raise ValueError("long4 byte count < 0: %d" % n)
data = f.read(n)
if len(data) != n:
raise ValueError("not enough data in stream to read long4")
return decode_long(data) | [
"def",
"read_long4",
"(",
"f",
")",
":",
"n",
"=",
"read_int4",
"(",
"f",
")",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"long4 byte count < 0: %d\"",
"%",
"n",
")",
"data",
"=",
"f",
".",
"read",
"(",
"n",
")",
"if",
"len",
"(",
"d... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pickletools.py#L654-L675 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py | python | Bits._setuintbe | (self, uintbe, length=None) | Set the bitstring to a big-endian unsigned int interpretation. | Set the bitstring to a big-endian unsigned int interpretation. | [
"Set",
"the",
"bitstring",
"to",
"a",
"big",
"-",
"endian",
"unsigned",
"int",
"interpretation",
"."
] | def _setuintbe(self, uintbe, length=None):
"""Set the bitstring to a big-endian unsigned int interpretation."""
if length is not None and length % 8 != 0:
raise CreationError("Big-endian integers must be whole-byte. "
"Length = {0} bits.", length)
self._setuint(uintbe, length) | [
"def",
"_setuintbe",
"(",
"self",
",",
"uintbe",
",",
"length",
"=",
"None",
")",
":",
"if",
"length",
"is",
"not",
"None",
"and",
"length",
"%",
"8",
"!=",
"0",
":",
"raise",
"CreationError",
"(",
"\"Big-endian integers must be whole-byte. \"",
"\"Length = {0... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L1443-L1448 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/models.py | python | Response.next | (self) | return self._next | Returns a PreparedRequest for the next request in a redirect chain, if there is one. | Returns a PreparedRequest for the next request in a redirect chain, if there is one. | [
"Returns",
"a",
"PreparedRequest",
"for",
"the",
"next",
"request",
"in",
"a",
"redirect",
"chain",
"if",
"there",
"is",
"one",
"."
] | def next(self):
"""Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
return self._next | [
"def",
"next",
"(",
"self",
")",
":",
"return",
"self",
".",
"_next"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/models.py#L720-L722 | |
NVlabs/fermat | 06e8c03ac59ab440cbb13897f90631ef1861e769 | contrib/assimp-4.1.0/port/PyAssimp/pyassimp/core.py | python | _finalize_mesh | (mesh, target) | Building of meshes is a bit specific.
We override here the various datasets that can
not be process as regular fields.
For instance, the length of the normals array is
mNumVertices (no mNumNormals is available) | Building of meshes is a bit specific. | [
"Building",
"of",
"meshes",
"is",
"a",
"bit",
"specific",
"."
] | def _finalize_mesh(mesh, target):
""" Building of meshes is a bit specific.
We override here the various datasets that can
not be process as regular fields.
For instance, the length of the normals array is
mNumVertices (no mNumNormals is available)
"""
nb_vertices = getattr(mesh, "mNumVertices")
def fill(name):
mAttr = getattr(mesh, name)
if numpy:
if mAttr:
data = numpy.array([make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)], dtype=numpy.float32)
setattr(target, name[1:].lower(), data)
else:
setattr(target, name[1:].lower(), numpy.array([], dtype="float32"))
else:
if mAttr:
data = [make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)]
setattr(target, name[1:].lower(), data)
else:
setattr(target, name[1:].lower(), [])
def fillarray(name):
mAttr = getattr(mesh, name)
data = []
for index, mSubAttr in enumerate(mAttr):
if mSubAttr:
data.append([make_tuple(getattr(mesh, name)[index][i]) for i in range(nb_vertices)])
if numpy:
setattr(target, name[1:].lower(), numpy.array(data, dtype=numpy.float32))
else:
setattr(target, name[1:].lower(), data)
fill("mNormals")
fill("mTangents")
fill("mBitangents")
fillarray("mColors")
fillarray("mTextureCoords")
# prepare faces
if numpy:
faces = numpy.array([f.indices for f in target.faces], dtype=numpy.int32)
else:
faces = [f.indices for f in target.faces]
setattr(target, 'faces', faces) | [
"def",
"_finalize_mesh",
"(",
"mesh",
",",
"target",
")",
":",
"nb_vertices",
"=",
"getattr",
"(",
"mesh",
",",
"\"mNumVertices\"",
")",
"def",
"fill",
"(",
"name",
")",
":",
"mAttr",
"=",
"getattr",
"(",
"mesh",
",",
"name",
")",
"if",
"numpy",
":",
... | https://github.com/NVlabs/fermat/blob/06e8c03ac59ab440cbb13897f90631ef1861e769/contrib/assimp-4.1.0/port/PyAssimp/pyassimp/core.py#L362-L413 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/mx2onnx/_op_translations.py | python | convert_min | (node, **kwargs) | Map MXNet's min operator attributes to onnx's ReduceMin operator
and return the created node. | Map MXNet's min operator attributes to onnx's ReduceMin operator
and return the created node. | [
"Map",
"MXNet",
"s",
"min",
"operator",
"attributes",
"to",
"onnx",
"s",
"ReduceMin",
"operator",
"and",
"return",
"the",
"created",
"node",
"."
] | def convert_min(node, **kwargs):
"""Map MXNet's min operator attributes to onnx's ReduceMin operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
mx_axis = attrs.get("axis", None)
axes = convert_string_to_list(str(mx_axis)) if mx_axis is not None else None
keepdims = get_boolean_attribute_value(attrs, "keepdims")
if axes is not None:
node = onnx.helper.make_node(
'ReduceMin',
inputs=input_nodes,
outputs=[name],
axes=axes,
keepdims=keepdims,
name=name
)
return [node]
else:
node = onnx.helper.make_node(
'ReduceMin',
inputs=input_nodes,
outputs=[name],
keepdims=keepdims,
name=name
)
return [node] | [
"def",
"convert_min",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"mx_axis",
"=",
"attrs",
".",
"get",
"(",
"\"axis\"",
",",
"None",
")",
"axes",
"=",
... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L1186-L1217 | ||
zeakey/DeepSkeleton | dc70170f8fd2ec8ca1157484ce66129981104486 | scripts/cpp_lint.py | python | CheckForMultilineCommentsAndStrings | (filename, clean_lines, linenum, error) | Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Logs an error if we see /* ... */ or "..." that extend past one line. | [
"Logs",
"an",
"error",
"if",
"we",
"see",
"/",
"*",
"...",
"*",
"/",
"or",
"...",
"that",
"extend",
"past",
"one",
"line",
"."
] | def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
"""Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Remove all \\ (escaped backslashes) from the line. They are OK, and the
# second (escaped) slash may trigger later \" detection erroneously.
line = line.replace('\\\\', '')
if line.count('/*') > line.count('*/'):
error(filename, linenum, 'readability/multiline_comment', 5,
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. '
'Consider replacing these with //-style comments, '
'with #if 0...#endif, '
'or with more clearly structured multi-line comments.')
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. '
'Use C++11 raw strings or concatenation instead.') | [
"def",
"CheckForMultilineCommentsAndStrings",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the",
"# secon... | https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L1526-L1561 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/editor/color/coloreditor.py | python | SyntEditView.ToggleBookmarkEvent | (self, event, pos = -1) | return 0 | Toggle a bookmark at the specified or current position | Toggle a bookmark at the specified or current position | [
"Toggle",
"a",
"bookmark",
"at",
"the",
"specified",
"or",
"current",
"position"
] | def ToggleBookmarkEvent(self, event, pos = -1):
"""Toggle a bookmark at the specified or current position
"""
if pos==-1:
pos, end = self.GetSel()
startLine = self.LineFromChar(pos)
self.GetDocument().MarkerToggle(startLine+1, MARKER_BOOKMARK)
return 0 | [
"def",
"ToggleBookmarkEvent",
"(",
"self",
",",
"event",
",",
"pos",
"=",
"-",
"1",
")",
":",
"if",
"pos",
"==",
"-",
"1",
":",
"pos",
",",
"end",
"=",
"self",
".",
"GetSel",
"(",
")",
"startLine",
"=",
"self",
".",
"LineFromChar",
"(",
"pos",
")... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/editor/color/coloreditor.py#L297-L304 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | delimitedList | (expr, delim=",", combine=False) | Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` is set to ``True``, the matching tokens are
returned as a single token string, with the delimiters included;
otherwise, the matching tokens are returned as a list of tokens,
with the delimiters suppressed.
Example::
delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] | Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` is set to ``True``, the matching tokens are
returned as a single token string, with the delimiters included;
otherwise, the matching tokens are returned as a list of tokens,
with the delimiters suppressed. | [
"Helper",
"to",
"define",
"a",
"delimited",
"list",
"of",
"expressions",
"-",
"the",
"delimiter",
"defaults",
"to",
".",
"By",
"default",
"the",
"list",
"elements",
"and",
"delimiters",
"can",
"have",
"intervening",
"whitespace",
"and",
"comments",
"but",
"thi... | def delimitedList(expr, delim=",", combine=False):
"""Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` is set to ``True``, the matching tokens are
returned as a single token string, with the delimiters included;
otherwise, the matching tokens are returned as a list of tokens,
with the delimiters suppressed.
Example::
delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
"""
dlName = _ustr(expr) + " [" + _ustr(delim) + " " + _ustr(expr) + "]..."
if combine:
return Combine(expr + ZeroOrMore(delim + expr)).setName(dlName)
else:
return (expr + ZeroOrMore(Suppress(delim) + expr)).setName(dlName) | [
"def",
"delimitedList",
"(",
"expr",
",",
"delim",
"=",
"\",\"",
",",
"combine",
"=",
"False",
")",
":",
"dlName",
"=",
"_ustr",
"(",
"expr",
")",
"+",
"\" [\"",
"+",
"_ustr",
"(",
"delim",
")",
"+",
"\" \"",
"+",
"_ustr",
"(",
"expr",
")",
"+",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L5329-L5348 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/core/tensor/array_method.py | python | ArrayMethodMixin.size | (self) | return shape.prod() | r"""Returns the size of the self :class:`~.Tensor`.
The returned value is a subclass of :class:`tuple`. | r"""Returns the size of the self :class:`~.Tensor`.
The returned value is a subclass of :class:`tuple`. | [
"r",
"Returns",
"the",
"size",
"of",
"the",
"self",
":",
"class",
":",
"~",
".",
"Tensor",
".",
"The",
"returned",
"value",
"is",
"a",
"subclass",
"of",
":",
"class",
":",
"tuple",
"."
] | def size(self):
r"""Returns the size of the self :class:`~.Tensor`.
The returned value is a subclass of :class:`tuple`.
"""
shape = self.shape
if shape.__class__ is tuple:
return np.prod(self.shape).item()
return shape.prod() | [
"def",
"size",
"(",
"self",
")",
":",
"shape",
"=",
"self",
".",
"shape",
"if",
"shape",
".",
"__class__",
"is",
"tuple",
":",
"return",
"np",
".",
"prod",
"(",
"self",
".",
"shape",
")",
".",
"item",
"(",
")",
"return",
"shape",
".",
"prod",
"("... | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/core/tensor/array_method.py#L427-L434 | |
tkn-tub/ns3-gym | 19bfe0a583e641142609939a090a09dfc63a095f | utils/grid.py | python | GraphicRenderer.get_height | (self) | return self.__height | ! Get Height
@param self this object
@return height | ! Get Height | [
"!",
"Get",
"Height"
] | def get_height(self):
"""! Get Height
@param self this object
@return height
"""
return self.__height | [
"def",
"get_height",
"(",
"self",
")",
":",
"return",
"self",
".",
"__height"
] | https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/utils/grid.py#L1027-L1032 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/metrics/python/ops/set_ops.py | python | set_union | (a, b, validate_indices=True) | return _set_operation(a, b, "union", validate_indices) | Compute set union of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be
sorted in row-major order.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the
unions. | Compute set union of elements in last dimension of `a` and `b`. | [
"Compute",
"set",
"union",
"of",
"elements",
"in",
"last",
"dimension",
"of",
"a",
"and",
"b",
"."
] | def set_union(a, b, validate_indices=True):
"""Compute set union of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be
sorted in row-major order.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the
unions.
"""
return _set_operation(a, b, "union", validate_indices) | [
"def",
"set_union",
"(",
"a",
",",
"b",
",",
"validate_indices",
"=",
"True",
")",
":",
"return",
"_set_operation",
"(",
"a",
",",
"b",
",",
"\"union\"",
",",
"validate_indices",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/metrics/python/ops/set_ops.py#L188-L207 | |
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | scripts/cpp_lint.py | python | _FunctionState.End | (self) | Stop analyzing function body. | Stop analyzing function body. | [
"Stop",
"analyzing",
"function",
"body",
"."
] | def End(self):
"""Stop analyzing function body."""
self.in_a_function = False | [
"def",
"End",
"(",
"self",
")",
":",
"self",
".",
"in_a_function",
"=",
"False"
] | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/scripts/cpp_lint.py#L861-L863 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/enum.py | python | _decompose | (flag, value) | return members, not_covered | Extract all members from the value. | Extract all members from the value. | [
"Extract",
"all",
"members",
"from",
"the",
"value",
"."
] | def _decompose(flag, value):
"""Extract all members from the value."""
# _decompose is only called if the value is not named
not_covered = value
negative = value < 0
# issue29167: wrap accesses to _value2member_map_ in a list to avoid race
# conditions between iterating over it and having more pseudo-
# members added to it
if negative:
# only check for named flags
flags_to_check = [
(m, v)
for v, m in list(flag._value2member_map_.items())
if m.name is not None
]
else:
# check for named flags and powers-of-two flags
flags_to_check = [
(m, v)
for v, m in list(flag._value2member_map_.items())
if m.name is not None or _power_of_two(v)
]
members = []
for member, member_value in flags_to_check:
if member_value and member_value & value == member_value:
members.append(member)
not_covered &= ~member_value
if not members and value in flag._value2member_map_:
members.append(flag._value2member_map_[value])
members.sort(key=lambda m: m._value_, reverse=True)
if len(members) > 1 and members[0].value == value:
# we have the breakdown, don't need the value member itself
members.pop(0)
return members, not_covered | [
"def",
"_decompose",
"(",
"flag",
",",
"value",
")",
":",
"# _decompose is only called if the value is not named",
"not_covered",
"=",
"value",
"negative",
"=",
"value",
"<",
"0",
"# issue29167: wrap accesses to _value2member_map_ in a list to avoid race",
"# conditio... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/enum.py#L877-L910 | |
cksystemsgroup/scalloc | 049857919b5fa1d539c9e4206e353daca2e87394 | tools/cpplint.py | python | UpdateIncludeState | (filename, include_state, io=codecs) | return True | Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise. | Fill up the include_state with new includes found from the file. | [
"Fill",
"up",
"the",
"include_state",
"with",
"new",
"includes",
"found",
"from",
"the",
"file",
"."
] | def UpdateIncludeState(filename, include_state, io=codecs):
"""Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
# The value formatting is cute, but not really used right now.
# What matters here is that the key is in include_state.
include_state.setdefault(include, '%s:%d' % (filename, linenum))
return True | [
"def",
"UpdateIncludeState",
"(",
"filename",
",",
"include_state",
",",
"io",
"=",
"codecs",
")",
":",
"headerfile",
"=",
"None",
"try",
":",
"headerfile",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
"excep... | https://github.com/cksystemsgroup/scalloc/blob/049857919b5fa1d539c9e4206e353daca2e87394/tools/cpplint.py#L4342-L4368 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/common/extensions/docs/examples/apps/hello-python/oauth2/__init__.py | python | Server._get_signature_method | (self, request) | return signature_method | Figure out the signature with some defaults. | Figure out the signature with some defaults. | [
"Figure",
"out",
"the",
"signature",
"with",
"some",
"defaults",
"."
] | def _get_signature_method(self, request):
"""Figure out the signature with some defaults."""
try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method | [
"def",
"_get_signature_method",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"signature_method",
"=",
"request",
".",
"get_parameter",
"(",
"'oauth_signature_method'",
")",
"except",
":",
"signature_method",
"=",
"SIGNATURE_METHOD",
"try",
":",
"# Get the sign... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/docs/examples/apps/hello-python/oauth2/__init__.py#L622-L636 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | cmake/developer_package/cpplint/cpplint.py | python | FileInfo.IsSource | (self) | return _IsSourceExtension(self.Extension()[1:]) | File has a source file extension. | File has a source file extension. | [
"File",
"has",
"a",
"source",
"file",
"extension",
"."
] | def IsSource(self):
"""File has a source file extension."""
return _IsSourceExtension(self.Extension()[1:]) | [
"def",
"IsSource",
"(",
"self",
")",
":",
"return",
"_IsSourceExtension",
"(",
"self",
".",
"Extension",
"(",
")",
"[",
"1",
":",
"]",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/cmake/developer_package/cpplint/cpplint.py#L1405-L1407 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py | python | aggregate_metric_map | (names_to_tuples) | return dict(zip(metric_names, value_ops)), dict(zip(metric_names, update_ops)) | Aggregates the metric names to tuple dictionary.
This function is useful for pairing metric names with their associated value
and update ops when the list of metrics is long. For example:
metrics_to_values, metrics_to_updates = slim.metrics.aggregate_metric_map({
'Mean Absolute Error': new_slim.metrics.streaming_mean_absolute_error(
predictions, labels, weights),
'Mean Relative Error': new_slim.metrics.streaming_mean_relative_error(
predictions, labels, labels, weights),
'RMSE Linear': new_slim.metrics.streaming_root_mean_squared_error(
predictions, labels, weights),
'RMSE Log': new_slim.metrics.streaming_root_mean_squared_error(
predictions, labels, weights),
})
Args:
names_to_tuples: a map of metric names to tuples, each of which contain the
pair of (value_tensor, update_op) from a streaming metric.
Returns:
A dictionary from metric names to value ops and a dictionary from metric
names to update ops. | Aggregates the metric names to tuple dictionary. | [
"Aggregates",
"the",
"metric",
"names",
"to",
"tuple",
"dictionary",
"."
] | def aggregate_metric_map(names_to_tuples):
"""Aggregates the metric names to tuple dictionary.
This function is useful for pairing metric names with their associated value
and update ops when the list of metrics is long. For example:
metrics_to_values, metrics_to_updates = slim.metrics.aggregate_metric_map({
'Mean Absolute Error': new_slim.metrics.streaming_mean_absolute_error(
predictions, labels, weights),
'Mean Relative Error': new_slim.metrics.streaming_mean_relative_error(
predictions, labels, labels, weights),
'RMSE Linear': new_slim.metrics.streaming_root_mean_squared_error(
predictions, labels, weights),
'RMSE Log': new_slim.metrics.streaming_root_mean_squared_error(
predictions, labels, weights),
})
Args:
names_to_tuples: a map of metric names to tuples, each of which contain the
pair of (value_tensor, update_op) from a streaming metric.
Returns:
A dictionary from metric names to value ops and a dictionary from metric
names to update ops.
"""
metric_names = names_to_tuples.keys()
value_ops, update_ops = zip(*names_to_tuples.values())
return dict(zip(metric_names, value_ops)), dict(zip(metric_names, update_ops)) | [
"def",
"aggregate_metric_map",
"(",
"names_to_tuples",
")",
":",
"metric_names",
"=",
"names_to_tuples",
".",
"keys",
"(",
")",
"value_ops",
",",
"update_ops",
"=",
"zip",
"(",
"*",
"names_to_tuples",
".",
"values",
"(",
")",
")",
"return",
"dict",
"(",
"zip... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py#L1882-L1909 | |
apache/trafficserver | 92d238a8fad483c58bc787f784b2ceae73aed532 | plugins/experimental/traffic_dump/post_process.py | python | parse_args | () | return parser.parse_args() | Parse the command line arguments. | Parse the command line arguments. | [
"Parse",
"the",
"command",
"line",
"arguments",
"."
] | def parse_args():
''' Parse the command line arguments.
'''
parser = argparse.ArgumentParser(description=description)
parser.add_argument("in_dir", type=str,
help='''The input directory of traffic_dump replay
files. The expectation is that this will contain
sub-directories that themselves contain replay files.
This is written to accommodate the directory populated
by traffic_dump via the --logdir option.''')
parser.add_argument("out_dir", type=str,
help="The output directory of post processed replay files.")
parser.add_argument("-n", "--num_sessions", type=int, default=10,
help='''The maximum number of sessions merged into
single replay output files. The default is 10.''')
parser.add_argument("--no-human-readable", action="store_true",
help='''By default, post processor will generate replay
files that are spaced out in a human readable format.
This turns off that behavior and leaves the files as
single-line entries.''')
parser.add_argument("--no-fabricate-proxy-requests", action="store_true",
help='''By default, post processor will fabricate proxy
requests and server responses for transactions served
out of the proxy. Presumably in replay conditions,
these fabricated requests and responses will not hurt
anything because the Proxy Verifier server will not
notice if the proxy replies locally in replay
conditions. However, if it doesn't reply locally, then
the server will not know how to reply to these
requests. Using this option turns off this fabrication
behavior.''')
parser.add_argument("-j", "--num_threads", type=int, default=32,
help='''The maximum number of threads to use.''')
parser.add_argument("-d", "--debug", action="store_true",
help="Enable debug level logging.")
return parser.parse_args() | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"parser",
".",
"add_argument",
"(",
"\"in_dir\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'''The input directory of traffic_dum... | https://github.com/apache/trafficserver/blob/92d238a8fad483c58bc787f784b2ceae73aed532/plugins/experimental/traffic_dump/post_process.py#L333-L369 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/core/setup.py | python | visibility_define | (config) | Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string). | Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string). | [
"Return",
"the",
"define",
"value",
"to",
"use",
"for",
"NPY_VISIBILITY_HIDDEN",
"(",
"may",
"be",
"empty",
"string",
")",
"."
] | def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string)."""
hide = '__attribute__((visibility("hidden")))'
if config.check_gcc_function_attribute(hide, 'hideme'):
return hide
else:
return '' | [
"def",
"visibility_define",
"(",
"config",
")",
":",
"hide",
"=",
"'__attribute__((visibility(\"hidden\")))'",
"if",
"config",
".",
"check_gcc_function_attribute",
"(",
"hide",
",",
"'hideme'",
")",
":",
"return",
"hide",
"else",
":",
"return",
"''"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/setup.py#L389-L396 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/venv/__init__.py | python | EnvBuilder.post_setup | (self, context) | Hook for post-setup modification of the venv. Subclasses may install
additional packages or scripts here, add activation shell scripts, etc.
:param context: The information for the environment creation request
being processed. | Hook for post-setup modification of the venv. Subclasses may install
additional packages or scripts here, add activation shell scripts, etc. | [
"Hook",
"for",
"post",
"-",
"setup",
"modification",
"of",
"the",
"venv",
".",
"Subclasses",
"may",
"install",
"additional",
"packages",
"or",
"scripts",
"here",
"add",
"activation",
"shell",
"scripts",
"etc",
"."
] | def post_setup(self, context):
"""
Hook for post-setup modification of the venv. Subclasses may install
additional packages or scripts here, add activation shell scripts, etc.
:param context: The information for the environment creation request
being processed.
"""
pass | [
"def",
"post_setup",
"(",
"self",
",",
"context",
")",
":",
"pass"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/venv/__init__.py#L305-L313 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py | python | generate | (env) | SCons entry point for this tool.
Args:
env: The SCons Environment to modify.
NOTE: SCons requires the use of this name, which fails lint. | SCons entry point for this tool. | [
"SCons",
"entry",
"point",
"for",
"this",
"tool",
"."
] | def generate(env):
'''SCons entry point for this tool.
Args:
env: The SCons Environment to modify.
NOTE: SCons requires the use of this name, which fails lint.
'''
nacl_utils.AddCommandLineOptions()
env.AddMethod(AllNaClModules)
env.AddMethod(AllNaClStaticLibraries)
env.AddMethod(AppendOptCCFlags)
env.AddMethod(AppendArchFlags)
env.AddMethod(FilterOut)
env.AddMethod(InstallPrebuilt)
env.AddMethod(NaClProgram)
env.AddMethod(NaClTestProgram)
env.AddMethod(NaClStaticLib)
env.AddMethod(NaClModules)
env.AddMethod(NaClStaticLibraries)
env.AddMethod(NaClStrippedInstall) | [
"def",
"generate",
"(",
"env",
")",
":",
"nacl_utils",
".",
"AddCommandLineOptions",
"(",
")",
"env",
".",
"AddMethod",
"(",
"AllNaClModules",
")",
"env",
".",
"AddMethod",
"(",
"AllNaClStaticLibraries",
")",
"env",
".",
"AddMethod",
"(",
"AppendOptCCFlags",
"... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py#L450-L471 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py | python | PrecompiledHeader.GetPchBuildCommands | (self, arch) | return [] | Not used on Windows as there are no additional build steps required
(instead, existing steps are modified in GetFlagsModifications below). | Not used on Windows as there are no additional build steps required
(instead, existing steps are modified in GetFlagsModifications below). | [
"Not",
"used",
"on",
"Windows",
"as",
"there",
"are",
"no",
"additional",
"build",
"steps",
"required",
"(",
"instead",
"existing",
"steps",
"are",
"modified",
"in",
"GetFlagsModifications",
"below",
")",
"."
] | def GetPchBuildCommands(self, arch):
"""Not used on Windows as there are no additional build steps required
(instead, existing steps are modified in GetFlagsModifications below)."""
return [] | [
"def",
"GetPchBuildCommands",
"(",
"self",
",",
"arch",
")",
":",
"return",
"[",
"]"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py#L907-L910 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/lib2to3/fixer_base.py | python | BaseFix.finish_tree | (self, tree, filename) | Some fixers need to maintain tree-wide state.
This method is called once, at the conclusion of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from. | Some fixers need to maintain tree-wide state.
This method is called once, at the conclusion of tree fix-up. | [
"Some",
"fixers",
"need",
"to",
"maintain",
"tree",
"-",
"wide",
"state",
".",
"This",
"method",
"is",
"called",
"once",
"at",
"the",
"conclusion",
"of",
"tree",
"fix",
"-",
"up",
"."
] | def finish_tree(self, tree, filename):
"""Some fixers need to maintain tree-wide state.
This method is called once, at the conclusion of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from.
"""
pass | [
"def",
"finish_tree",
"(",
"self",
",",
"tree",
",",
"filename",
")",
":",
"pass"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lib2to3/fixer_base.py#L159-L166 | ||
potassco/clingo | e0c91d8f95cc28de1c480a871f9c97c30de83d40 | examples/clingo/dl/app.py | python | _evaluate | (term: TheoryTerm) | Evaluates the operators in a theory term in the same fashion as clingo
evaluates its arithmetic functions. | Evaluates the operators in a theory term in the same fashion as clingo
evaluates its arithmetic functions. | [
"Evaluates",
"the",
"operators",
"in",
"a",
"theory",
"term",
"in",
"the",
"same",
"fashion",
"as",
"clingo",
"evaluates",
"its",
"arithmetic",
"functions",
"."
] | def _evaluate(term: TheoryTerm) -> Symbol:
'''
Evaluates the operators in a theory term in the same fashion as clingo
evaluates its arithmetic functions.
'''
# tuples
if term.type == TheoryTermType.Tuple:
return Tuple_([_evaluate(x) for x in term.arguments])
# functions and arithmetic operations
if term.type == TheoryTermType.Function:
# binary operations
if term.name in _BOP and len(term.arguments) == 2:
term_a = _evaluate(term.arguments[0])
term_b = _evaluate(term.arguments[1])
if term_a.type != SymbolType.Number or term_b.type != SymbolType.Number:
raise RuntimeError("Invalid Binary Operation")
if term.name in ("/", "\\") and term_b.number == 0:
raise RuntimeError("Division by Zero")
return Number(_BOP[term.name](term_a.number, term_b.number))
# unary operations
if term.name == "-" and len(term.arguments) == 1:
term_a = _evaluate(term.arguments[0])
if term_a.type == SymbolType.Number:
return Number(-term_a.number)
if term_a.type == SymbolType.Function and term_a.name:
return Function(term_a.name, term_a.arguments, not term_a.positive)
raise RuntimeError("Invalid Unary Operation")
# functions
return Function(term.name, [_evaluate(x) for x in term.arguments])
# constants
if term.type == TheoryTermType.Symbol:
return Function(term.name)
# numbers
if term.type == TheoryTermType.Number:
return Number(term.number)
raise RuntimeError("Invalid Syntax") | [
"def",
"_evaluate",
"(",
"term",
":",
"TheoryTerm",
")",
"->",
"Symbol",
":",
"# tuples",
"if",
"term",
".",
"type",
"==",
"TheoryTermType",
".",
"Tuple",
":",
"return",
"Tuple_",
"(",
"[",
"_evaluate",
"(",
"x",
")",
"for",
"x",
"in",
"term",
".",
"... | https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/examples/clingo/dl/app.py#L51-L98 | ||
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/cpp_lint.py | python | IsCppString | (line) | return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant. | Does line terminate so, that the next symbol is in string constant. | [
"Does",
"line",
"terminate",
"so",
"that",
"the",
"next",
"symbol",
"is",
"in",
"string",
"constant",
"."
] | def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | [
"def",
"IsCppString",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"r'\\\\'",
",",
"'XX'",
")",
"# after this, \\\\\" does not match to \\\"",
"return",
"(",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
... | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L1045-L1059 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/core.py | python | open_files | (
urlpath,
mode="rb",
compression=None,
encoding="utf8",
errors=None,
name_function=None,
num=1,
protocol=None,
newline=None,
**kwargs
) | return [
OpenFile(
fs,
path,
mode=mode,
compression=compression,
encoding=encoding,
errors=errors,
newline=newline,
)
for path in paths
] | Given a path or paths, return a list of ``OpenFile`` objects.
For writing, a str path must contain the "*" character, which will be filled
in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
For either reading or writing, can instead provide explicit list of paths.
Parameters
----------
urlpath: string or list
Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
to read from alternative filesystems. To read from multiple files you
can pass a globstring or a list of paths, with the caveat that they
must all have the same protocol.
mode: 'rb', 'wt', etc.
compression: string
Compression to use. See ``dask.bytes.compression.files`` for options.
encoding: str
For text mode only
errors: None or str
Passed to TextIOWrapper in text mode
name_function: function or None
if opening a set of files for writing, those files do not yet exist,
so we need to generate their names by formatting the urlpath for
each sequence number
num: int [1]
if writing mode, number of files we expect to create (passed to
name+function)
protocol: str or None
If given, overrides the protocol found in the URL.
newline: bytes or None
Used for line terminator in text mode. If None, uses system default;
if blank, uses no translation.
**kwargs: dict
Extra options that make sense to a particular storage connection, e.g.
host, port, username, password, etc.
Examples
--------
>>> files = open_files('2015-*-*.csv') # doctest: +SKIP
>>> files = open_files(
... 's3://bucket/2015-*-*.csv.gz', compression='gzip'
... ) # doctest: +SKIP
Returns
-------
List of ``OpenFile`` objects. | Given a path or paths, return a list of ``OpenFile`` objects. | [
"Given",
"a",
"path",
"or",
"paths",
"return",
"a",
"list",
"of",
"OpenFile",
"objects",
"."
] | def open_files(
urlpath,
mode="rb",
compression=None,
encoding="utf8",
errors=None,
name_function=None,
num=1,
protocol=None,
newline=None,
**kwargs
):
""" Given a path or paths, return a list of ``OpenFile`` objects.
For writing, a str path must contain the "*" character, which will be filled
in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
For either reading or writing, can instead provide explicit list of paths.
Parameters
----------
urlpath: string or list
Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
to read from alternative filesystems. To read from multiple files you
can pass a globstring or a list of paths, with the caveat that they
must all have the same protocol.
mode: 'rb', 'wt', etc.
compression: string
Compression to use. See ``dask.bytes.compression.files`` for options.
encoding: str
For text mode only
errors: None or str
Passed to TextIOWrapper in text mode
name_function: function or None
if opening a set of files for writing, those files do not yet exist,
so we need to generate their names by formatting the urlpath for
each sequence number
num: int [1]
if writing mode, number of files we expect to create (passed to
name+function)
protocol: str or None
If given, overrides the protocol found in the URL.
newline: bytes or None
Used for line terminator in text mode. If None, uses system default;
if blank, uses no translation.
**kwargs: dict
Extra options that make sense to a particular storage connection, e.g.
host, port, username, password, etc.
Examples
--------
>>> files = open_files('2015-*-*.csv') # doctest: +SKIP
>>> files = open_files(
... 's3://bucket/2015-*-*.csv.gz', compression='gzip'
... ) # doctest: +SKIP
Returns
-------
List of ``OpenFile`` objects.
"""
chain = _un_chain(urlpath, kwargs)
if len(chain) > 1:
kwargs = chain[0][2]
inkwargs = kwargs
urlpath = False
for i, ch in enumerate(chain):
urls, protocol, kw = ch
if isinstance(urls, str):
if not urlpath and split_protocol(urls)[1]:
urlpath = protocol + "://" + split_protocol(urls)[1]
else:
if not urlpath and any(split_protocol(u)[1] for u in urls):
urlpath = [protocol + "://" + split_protocol(u)[1] for u in urls]
if i == 0:
continue
inkwargs["target_protocol"] = protocol
inkwargs["target_options"] = kw.copy()
inkwargs["fo"] = urls
inkwargs = inkwargs["target_options"]
protocol = chain[0][1]
fs, fs_token, paths = get_fs_token_paths(
urlpath,
mode,
num=num,
name_function=name_function,
storage_options=kwargs,
protocol=protocol,
)
return [
OpenFile(
fs,
path,
mode=mode,
compression=compression,
encoding=encoding,
errors=errors,
newline=newline,
)
for path in paths
] | [
"def",
"open_files",
"(",
"urlpath",
",",
"mode",
"=",
"\"rb\"",
",",
"compression",
"=",
"None",
",",
"encoding",
"=",
"\"utf8\"",
",",
"errors",
"=",
"None",
",",
"name_function",
"=",
"None",
",",
"num",
"=",
"1",
",",
"protocol",
"=",
"None",
",",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/core.py#L140-L239 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | _FunctionState.Count | (self) | Count line in current function body. | Count line in current function body. | [
"Count",
"line",
"in",
"current",
"function",
"body",
"."
] | def Count(self):
"""Count line in current function body."""
if self.in_a_function:
self.lines_in_function += 1 | [
"def",
"Count",
"(",
"self",
")",
":",
"if",
"self",
".",
"in_a_function",
":",
"self",
".",
"lines_in_function",
"+=",
"1"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1054-L1057 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DropSource.GetDataObject | (*args, **kwargs) | return _misc_.DropSource_GetDataObject(*args, **kwargs) | GetDataObject(self) -> DataObject | GetDataObject(self) -> DataObject | [
"GetDataObject",
"(",
"self",
")",
"-",
">",
"DataObject"
] | def GetDataObject(*args, **kwargs):
"""GetDataObject(self) -> DataObject"""
return _misc_.DropSource_GetDataObject(*args, **kwargs) | [
"def",
"GetDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DropSource_GetDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5516-L5518 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Mazar/MazAr_Admin/apps/smsg_r/smsapp/templatetags/mytags.py | python | country_code_to_name | (code) | return "" | Returns country name from its code
@param code: Country 2-letters code
@type code: str
@return: Country full name
@rtype: str | Returns country name from its code | [
"Returns",
"country",
"name",
"from",
"its",
"code"
] | def country_code_to_name(code):
"""
Returns country name from its code
@param code: Country 2-letters code
@type code: str
@return: Country full name
@rtype: str
"""
try:
country = pycountry.countries.get(alpha2=code)
if country:
return country.name
except KeyError:
return code
return "" | [
"def",
"country_code_to_name",
"(",
"code",
")",
":",
"try",
":",
"country",
"=",
"pycountry",
".",
"countries",
".",
"get",
"(",
"alpha2",
"=",
"code",
")",
"if",
"country",
":",
"return",
"country",
".",
"name",
"except",
"KeyError",
":",
"return",
"co... | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Mazar/MazAr_Admin/apps/smsg_r/smsapp/templatetags/mytags.py#L59-L73 | |
google/certificate-transparency | 2588562fd306a447958471b6f06c1069619c1641 | python/ct/crypto/in_memory_merkle_tree.py | python | InMemoryMerkleTree.get_consistency_proof | (self, tree_size_1, tree_size_2=None) | return self._calculate_subproof(
tree_size_1, self.__leaves[:tree_size_2], True) | Returns a consistency proof between two snapshots of the tree. | Returns a consistency proof between two snapshots of the tree. | [
"Returns",
"a",
"consistency",
"proof",
"between",
"two",
"snapshots",
"of",
"the",
"tree",
"."
] | def get_consistency_proof(self, tree_size_1, tree_size_2=None):
"""Returns a consistency proof between two snapshots of the tree."""
if tree_size_2 is None:
tree_size_2 = self.tree_size()
if tree_size_1 > self.tree_size() or tree_size_2 > self.tree_size():
raise ValueError("Requested proof for sizes beyond current tree:"
" current tree: %d tree_size_1 %d tree_size_2 %d" % (
self.tree_size(), tree_size_1, tree_size_2))
if tree_size_1 > tree_size_2:
raise ValueError("tree_size_1 must be less than tree_size_2")
if tree_size_1 == tree_size_2 or tree_size_1 == 0:
return []
return self._calculate_subproof(
tree_size_1, self.__leaves[:tree_size_2], True) | [
"def",
"get_consistency_proof",
"(",
"self",
",",
"tree_size_1",
",",
"tree_size_2",
"=",
"None",
")",
":",
"if",
"tree_size_2",
"is",
"None",
":",
"tree_size_2",
"=",
"self",
".",
"tree_size",
"(",
")",
"if",
"tree_size_1",
">",
"self",
".",
"tree_size",
... | https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/ct/crypto/in_memory_merkle_tree.py#L80-L96 | |
eclipse/omr | 056e7c9ce9d503649190bc5bd9931fac30b4e4bc | jitbuilder/apigen/genutils.py | python | PrettyPrinter.outdent | (self) | Decrease the indent level | Decrease the indent level | [
"Decrease",
"the",
"indent",
"level"
] | def outdent(self):
"""Decrease the indent level"""
self.indent_level -= 1
if self.indent_level < 0:
self.indent_level = 0 | [
"def",
"outdent",
"(",
"self",
")",
":",
"self",
".",
"indent_level",
"-=",
"1",
"if",
"self",
".",
"indent_level",
"<",
"0",
":",
"self",
".",
"indent_level",
"=",
"0"
] | https://github.com/eclipse/omr/blob/056e7c9ce9d503649190bc5bd9931fac30b4e4bc/jitbuilder/apigen/genutils.py#L500-L504 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/framework/python/framework/tensor_util.py | python | _assert_same_base_type | (items, expected_type=None) | return expected_type | r"""Asserts all items are of the same base type.
Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected type. If not specified, assert all items are
of the same base type.
Returns:
Validated type, or none if neither expected_type nor items provided.
Raises:
ValueError: If any types do not match. | r"""Asserts all items are of the same base type. | [
"r",
"Asserts",
"all",
"items",
"are",
"of",
"the",
"same",
"base",
"type",
"."
] | def _assert_same_base_type(items, expected_type=None):
r"""Asserts all items are of the same base type.
Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected type. If not specified, assert all items are
of the same base type.
Returns:
Validated type, or none if neither expected_type nor items provided.
Raises:
ValueError: If any types do not match.
"""
original_item_str = None
for item in items:
if item is not None:
item_type = item.dtype.base_dtype
if not expected_type:
expected_type = item_type
original_item_str = item.name if hasattr(item, 'name') else str(item)
elif expected_type != item_type:
raise ValueError('%s, type=%s, must be of the same type (%s)%s.' % (
item.name if hasattr(item, 'name') else str(item),
item_type, expected_type,
(' as %s' % original_item_str) if original_item_str else ''))
return expected_type | [
"def",
"_assert_same_base_type",
"(",
"items",
",",
"expected_type",
"=",
"None",
")",
":",
"original_item_str",
"=",
"None",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"is",
"not",
"None",
":",
"item_type",
"=",
"item",
".",
"dtype",
".",
"base_dtyp... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/framework/python/framework/tensor_util.py#L38-L65 | |
apache/trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | install/python-installer/scripts/common.py | python | time_elapse | (func) | return wrapper | time elapse decorator | time elapse decorator | [
"time",
"elapse",
"decorator"
] | def time_elapse(func):
""" time elapse decorator """
def wrapper(*args, **kwargs):
start_time = time.time()
output = func(*args, **kwargs)
end_time = time.time()
seconds = end_time - start_time
hours = seconds / 3600
seconds = seconds % 3600
minutes = seconds / 60
seconds = seconds % 60
print '\nTime Cost: %d hour(s) %d minute(s) %d second(s)' % (hours, minutes, seconds)
return output
return wrapper | [
"def",
"time_elapse",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"output",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"end_time... | https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/install/python-installer/scripts/common.py#L647-L660 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/multiprocessing/managers.py | python | RebuildProxy | (func, token, serializer, kwds) | Function used for unpickling proxy objects.
If possible the shared object is returned, or otherwise a proxy for it. | Function used for unpickling proxy objects. | [
"Function",
"used",
"for",
"unpickling",
"proxy",
"objects",
"."
] | def RebuildProxy(func, token, serializer, kwds):
'''
Function used for unpickling proxy objects.
If possible the shared object is returned, or otherwise a proxy for it.
'''
server = getattr(current_process(), '_manager_server', None)
if server and server.address == token.address:
return server.id_to_obj[token.id][0]
else:
incref = (
kwds.pop('incref', True) and
not getattr(current_process(), '_inheriting', False)
)
return func(token, serializer, incref=incref, **kwds) | [
"def",
"RebuildProxy",
"(",
"func",
",",
"token",
",",
"serializer",
",",
"kwds",
")",
":",
"server",
"=",
"getattr",
"(",
"current_process",
"(",
")",
",",
"'_manager_server'",
",",
"None",
")",
"if",
"server",
"and",
"server",
".",
"address",
"==",
"to... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/multiprocessing/managers.py#L830-L845 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_wx/objpanel.py | python | ObjPanelMixin.add_buttons | (self, parent, sizer,
is_modal=False,
standartbuttons=['apply', 'restore', 'cancel'],
buttons=[],
defaultbutton='apply',
) | Add a button row to sizer | Add a button row to sizer | [
"Add",
"a",
"button",
"row",
"to",
"sizer"
] | def add_buttons(self, parent, sizer,
is_modal=False,
standartbuttons=['apply', 'restore', 'cancel'],
buttons=[],
defaultbutton='apply',
):
"""
Add a button row to sizer
"""
# print '\nadd_buttons is_modal',is_modal
# print ' standartbuttons',standartbuttons
# print ' buttons',buttons
if parent is None:
parent = self
# print 'add_buttons'
# print ' buttons=',buttons
self.data_standartbuttons = {
'apply': ('Apply', self.on_apply, 'Apply current values'),
'restore': ('Restore', self.on_restore, 'Restore previous values'),
'ok': ('OK', self.on_ok, 'Apply and close window'),
'cancel': ('Cancel', self.on_cancel, 'Cancel and close window')
}
# compose button row on bottom of panel
allbuttons = []
# add custom buttons
allbuttons += buttons
# print '\n allbuttons',allbuttons
# print ' buttons',buttons,len(buttons),is_modal&(len(buttons)==0)
if is_modal & (len(buttons) == 0):
# if in dialog mode use only OK and cancel by default
standartbuttons = []
# add standart buttons
# print ' standartbuttons=',standartbuttons
for key in standartbuttons:
# print ' append:',key
allbuttons.append(self.data_standartbuttons[key])
if (len(allbuttons) > 0) | is_modal:
self.add_hline(sizer)
# Init the context help button.
# And even include help text about the help button :-)
if is_modal & (len(buttons) == 0):
# standartbuttons=[]
# print 'add_buttons modal buttons',buttons
btnsizer = wx.StdDialogButtonSizer()
# standartbuttons=[]
#helpbutton = wx.ContextHelpButton(self.parent)
#helpbutton.SetHelpText(' Click to put application\n into context sensitive help mode.')
#btnsizer.AddButton(helpbutton )
else:
if defaultbutton == '':
defaultbutton = 'Apply'
# print 'add_buttons ',allbuttons
btnsizer = wx.BoxSizer(wx.HORIZONTAL)
# add help button
# print ' allbuttons',allbuttons
# create button widgets
for (name, function, info) in allbuttons:
b = wx.Button(parent, -1, name, (2, 2))
self.Bind(wx.EVT_BUTTON, function, b)
b.SetHelpText(info)
if defaultbutton == name:
b.SetDefault()
if is_modal & (len(buttons) == 0):
# print ' create button modal',name,is_modal
btnsizer.AddButton(b)
else:
# print ' create button',name,is_modal
btnsizer.Add(b)
if is_modal & (len(buttons) == 0):
# print ' Add OK and CANCEL'
# add OK and CANCEL if panel appears in separate window
b = wx.Button(parent, wx.ID_OK)
b.SetHelpText('Apply values and close window')
#self.Bind(wx.EVT_BUTTON, self.on_ok_modal, b)
if defaultbutton == '':
# set apply button default if there is no other default
b.SetDefault()
btnsizer.AddButton(b)
# print 'Add OK',b
# add cancel
b = wx.Button(parent, wx.ID_CANCEL)
b.SetHelpText('Ignore modifications and close window')
btnsizer.AddButton(b)
# print 'Add cancel',b
btnsizer.Realize()
# else:
# btnsizer.Realize()
# if wx.Platform != "__WXMSW__":
# btn = wx.ContextHelpButton(self)
# btnsizer.AddButton(btn)
# btnsizer.Realize()
#b = csel.ColourSelect(self.parent, -1, 'test', (255,0,0), size = wx.DefaultSize)
# sizer.Add(b)
# add buttomrow to main
#sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
#widget=wx.StaticText(self.parent, -1,'That is it!!')
# sizer.Add(widget)
# TEST
#btnsizer = wx.StdDialogButtonSizer()
# if wx.Platform != "__WXMSW__":
# btn = wx.ContextHelpButton(self)
# btnsizer.AddButton(btn)
## btn = wx.Button(self, wx.ID_OK)
## btn.SetHelpText("The OK button completes the dialog")
# btn.SetDefault()
# btnsizer.AddButton(btn)
##
## btn = wx.Button(self, wx.ID_CANCEL)
## btn.SetHelpText("The Cancel button cnacels the dialog. (Cool, huh?)")
# btnsizer.AddButton(btn)
# btnsizer.Realize()
###
sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) | [
"def",
"add_buttons",
"(",
"self",
",",
"parent",
",",
"sizer",
",",
"is_modal",
"=",
"False",
",",
"standartbuttons",
"=",
"[",
"'apply'",
",",
"'restore'",
",",
"'cancel'",
"]",
",",
"buttons",
"=",
"[",
"]",
",",
"defaultbutton",
"=",
"'apply'",
",",
... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L3449-L3582 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/nn_ops.py | python | Conv2DTranspose.__init__ | (self, out_channel, kernel_size, pad_mode="valid", pad=0,
pad_list=None, mode=1, stride=1, dilation=1, group=1, data_format="NCHW") | Initialize Conv2DTranspose. | Initialize Conv2DTranspose. | [
"Initialize",
"Conv2DTranspose",
"."
] | def __init__(self, out_channel, kernel_size, pad_mode="valid", pad=0,
pad_list=None, mode=1, stride=1, dilation=1, group=1, data_format="NCHW"):
"""Initialize Conv2DTranspose."""
super(Conv2DTranspose, self).__init__(out_channel, kernel_size, pad_mode, pad,
pad_list, mode, stride, dilation, group, data_format) | [
"def",
"__init__",
"(",
"self",
",",
"out_channel",
",",
"kernel_size",
",",
"pad_mode",
"=",
"\"valid\"",
",",
"pad",
"=",
"0",
",",
"pad_list",
"=",
"None",
",",
"mode",
"=",
"1",
",",
"stride",
"=",
"1",
",",
"dilation",
"=",
"1",
",",
"group",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/nn_ops.py#L2106-L2110 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | SplitterWindow.IsSplit | (*args, **kwargs) | return _windows_.SplitterWindow_IsSplit(*args, **kwargs) | IsSplit(self) -> bool
Is the window split? | IsSplit(self) -> bool | [
"IsSplit",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsSplit(*args, **kwargs):
"""
IsSplit(self) -> bool
Is the window split?
"""
return _windows_.SplitterWindow_IsSplit(*args, **kwargs) | [
"def",
"IsSplit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"SplitterWindow_IsSplit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1517-L1523 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/ttk.py | python | Checkbutton.invoke | (self) | return self.tk.call(self._w, "invoke") | Toggles between the selected and deselected states and
invokes the associated command. If the widget is currently
selected, sets the option variable to the offvalue option
and deselects the widget; otherwise, sets the option variable
to the option onvalue.
Returns the result of the associated command. | Toggles between the selected and deselected states and
invokes the associated command. If the widget is currently
selected, sets the option variable to the offvalue option
and deselects the widget; otherwise, sets the option variable
to the option onvalue. | [
"Toggles",
"between",
"the",
"selected",
"and",
"deselected",
"states",
"and",
"invokes",
"the",
"associated",
"command",
".",
"If",
"the",
"widget",
"is",
"currently",
"selected",
"sets",
"the",
"option",
"variable",
"to",
"the",
"offvalue",
"option",
"and",
... | def invoke(self):
"""Toggles between the selected and deselected states and
invokes the associated command. If the widget is currently
selected, sets the option variable to the offvalue option
and deselects the widget; otherwise, sets the option variable
to the option onvalue.
Returns the result of the associated command."""
return self.tk.call(self._w, "invoke") | [
"def",
"invoke",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"invoke\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L636-L644 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/input.py | python | DependencyGraphNode.FindCycles | (self) | return results | Returns a list of cycles in the graph, where each cycle is its own list. | Returns a list of cycles in the graph, where each cycle is its own list. | [
"Returns",
"a",
"list",
"of",
"cycles",
"in",
"the",
"graph",
"where",
"each",
"cycle",
"is",
"its",
"own",
"list",
"."
] | def FindCycles(self):
"""
Returns a list of cycles in the graph, where each cycle is its own list.
"""
results = []
visited = set()
def Visit(node, path):
for child in node.dependents:
if child in path:
results.append([child] + path[:path.index(child) + 1])
elif not child in visited:
visited.add(child)
Visit(child, [child] + path)
visited.add(self)
Visit(self, [self])
return results | [
"def",
"FindCycles",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"visited",
"=",
"set",
"(",
")",
"def",
"Visit",
"(",
"node",
",",
"path",
")",
":",
"for",
"child",
"in",
"node",
".",
"dependents",
":",
"if",
"child",
"in",
"path",
":",
"re... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/input.py#L1586-L1604 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | SpinEvent.SetValue | (*args, **kwargs) | return _controls_.SpinEvent_SetValue(*args, **kwargs) | SetValue(self, int value) | SetValue(self, int value) | [
"SetValue",
"(",
"self",
"int",
"value",
")"
] | def SetValue(*args, **kwargs):
"""SetValue(self, int value)"""
return _controls_.SpinEvent_SetValue(*args, **kwargs) | [
"def",
"SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SpinEvent_SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2448-L2450 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/npyio.py | python | BagObj.__dir__ | (self) | return list(object.__getattribute__(self, '_obj').keys()) | Enables dir(bagobj) to list the files in an NpzFile.
This also enables tab-completion in an interpreter or IPython. | Enables dir(bagobj) to list the files in an NpzFile. | [
"Enables",
"dir",
"(",
"bagobj",
")",
"to",
"list",
"the",
"files",
"in",
"an",
"NpzFile",
"."
] | def __dir__(self):
"""
Enables dir(bagobj) to list the files in an NpzFile.
This also enables tab-completion in an interpreter or IPython.
"""
return list(object.__getattribute__(self, '_obj').keys()) | [
"def",
"__dir__",
"(",
"self",
")",
":",
"return",
"list",
"(",
"object",
".",
"__getattribute__",
"(",
"self",
",",
"'_obj'",
")",
".",
"keys",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/npyio.py#L91-L97 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/memory_inspector/memory_inspector/frontends/background_tasks.py | python | TracerMain_ | (log, storage_path, backend_name, device_id, pid, interval,
count, trace_native_heap) | return 0 | Entry point for the background periodic tracer task. | Entry point for the background periodic tracer task. | [
"Entry",
"point",
"for",
"the",
"background",
"periodic",
"tracer",
"task",
"."
] | def TracerMain_(log, storage_path, backend_name, device_id, pid, interval,
count, trace_native_heap):
"""Entry point for the background periodic tracer task."""
# Initialize storage.
storage = file_storage.Storage(storage_path)
# Initialize the backend.
backend = backends.GetBackend(backend_name)
for k, v in storage.LoadSettings(backend_name).iteritems():
backend.settings[k] = v
# Initialize the device.
device = backends.GetDevice(backend_name, device_id)
for k, v in storage.LoadSettings(device_id).iteritems():
device.settings[k] = v
# Start periodic tracing.
process = device.GetProcess(pid)
log.put((1, 'Starting trace (%d dumps x %s s.). Device: %s, process: %s' % (
count, interval, device.name, process.name)))
datetime_str = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M')
archive_name = '%s - %s - %s' % (datetime_str, device.name, process.name)
archive = storage.OpenArchive(archive_name, create=True)
heaps_to_symbolize = []
for i in xrange(1, count + 1): # [1, count] range is easier to handle.
process = device.GetProcess(pid)
if not process:
log.put((100, 'Process %d died.' % pid))
return 1
# Calculate the completion rate proportionally to 80%. We keep the remaining
# 20% for the final symbolization step (just an approximate estimation).
completion = 80 * i / count
log.put((completion, 'Dumping trace %d of %d' % (i, count)))
archive.StartNewSnapshot()
# Freeze the process, so that the mmaps and the heap dump are consistent.
process.Freeze()
try:
if trace_native_heap:
nheap = process.DumpNativeHeap()
log.put((completion,
'Dumped %d native allocations' % len(nheap.allocations)))
# TODO(primiano): memdump has the bad habit of sending SIGCONT to the
# process. Fix that, so we are the only one in charge of controlling it.
mmaps = process.DumpMemoryMaps()
log.put((completion, 'Dumped %d memory maps' % len(mmaps)))
archive.StoreMemMaps(mmaps)
if trace_native_heap:
nheap.RelativizeStackFrames(mmaps)
nheap.CalculateResidentSize(mmaps)
archive.StoreNativeHeap(nheap)
heaps_to_symbolize += [nheap]
finally:
process.Unfreeze()
if i < count:
time.sleep(interval)
if heaps_to_symbolize:
log.put((90, 'Symbolizing'))
symbols = backend.ExtractSymbols(
heaps_to_symbolize, device.settings['native_symbol_paths'] or '')
expected_symbols_count = len(set.union(
*[set(x.stack_frames.iterkeys()) for x in heaps_to_symbolize]))
log.put((99, 'Symbolization complete. Got %d symbols (%.1f%%).' % (
len(symbols), 100.0 * len(symbols) / expected_symbols_count)))
archive.StoreSymbols(symbols)
log.put((100, 'Trace complete.'))
return 0 | [
"def",
"TracerMain_",
"(",
"log",
",",
"storage_path",
",",
"backend_name",
",",
"device_id",
",",
"pid",
",",
"interval",
",",
"count",
",",
"trace_native_heap",
")",
":",
"# Initialize storage.",
"storage",
"=",
"file_storage",
".",
"Storage",
"(",
"storage_pa... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/memory_inspector/memory_inspector/frontends/background_tasks.py#L54-L125 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/contrib/layers/nn.py | python | sequence_topk_avg_pooling | (input, row, col, topks, channel_num) | return out | The :attr:`topks` is a list with incremental values in this function. For each topk,
it will average the topk features as an output feature for each channel of every
input sequence. Both :attr:`row` and :attr:`col` are LodTensor, which provide height
and width information for :attr:`input` tensor. If feature size of input sequence is less
than topk, it will padding 0 at the back.
.. code-block:: text
If channel_num is 2 and given row LoDTensor and col LoDTensor as follows:
row.lod = [[5, 4]]
col.lod = [[6, 7]]
input is a LoDTensor with input.lod[0][i] = channel_num * row.lod[0][i] * col.lod[0][i]
input.lod = [[60, 56]] # where 60 = channel_num * 5 * 6
input.dims = [116, 1] # where 116 = 60 + 56
If topks is [1, 3, 5], then we get a 1-level LoDTensor:
out.lod = [[5, 4]] # share Lod info with row LodTensor
out.dims = [9, 6] # where 6 = len(topks) * channel_num
Args:
input (Variable): The input should be 2D LodTensor with dims[1] equals 1.
row (Variable): The row should be 1-level LodTensor to provide the height information
of the input tensor data.
col (Variable): The col should be 1-level LodTensor to provide the width information
of the input tensor data.
topks (list): A list of incremental value to average the topk feature.
channel_num (int): The number of input channel.
Returns:
Variable: output LodTensor specified by this layer.
Examples:
.. code-block:: python
import numpy as np
from paddle.fluid import layers
from paddle.fluid import contrib
x_lod_tensor = layers.data(name='x', shape=[1], lod_level=1)
row_lod_tensor = layers.data(name='row', shape=[6], lod_level=1)
col_lod_tensor = layers.data(name='col', shape=[6], lod_level=1)
out = contrib.sequence_topk_avg_pooling(input=x_lod_tensor,
row=row_lod_tensor,
col=col_lod_tensor,
topks=[1, 3, 5],
channel_num=5) | The :attr:`topks` is a list with incremental values in this function. For each topk,
it will average the topk features as an output feature for each channel of every
input sequence. Both :attr:`row` and :attr:`col` are LodTensor, which provide height
and width information for :attr:`input` tensor. If feature size of input sequence is less
than topk, it will padding 0 at the back. | [
"The",
":",
"attr",
":",
"topks",
"is",
"a",
"list",
"with",
"incremental",
"values",
"in",
"this",
"function",
".",
"For",
"each",
"topk",
"it",
"will",
"average",
"the",
"topk",
"features",
"as",
"an",
"output",
"feature",
"for",
"each",
"channel",
"of... | def sequence_topk_avg_pooling(input, row, col, topks, channel_num):
"""
The :attr:`topks` is a list with incremental values in this function. For each topk,
it will average the topk features as an output feature for each channel of every
input sequence. Both :attr:`row` and :attr:`col` are LodTensor, which provide height
and width information for :attr:`input` tensor. If feature size of input sequence is less
than topk, it will padding 0 at the back.
.. code-block:: text
If channel_num is 2 and given row LoDTensor and col LoDTensor as follows:
row.lod = [[5, 4]]
col.lod = [[6, 7]]
input is a LoDTensor with input.lod[0][i] = channel_num * row.lod[0][i] * col.lod[0][i]
input.lod = [[60, 56]] # where 60 = channel_num * 5 * 6
input.dims = [116, 1] # where 116 = 60 + 56
If topks is [1, 3, 5], then we get a 1-level LoDTensor:
out.lod = [[5, 4]] # share Lod info with row LodTensor
out.dims = [9, 6] # where 6 = len(topks) * channel_num
Args:
input (Variable): The input should be 2D LodTensor with dims[1] equals 1.
row (Variable): The row should be 1-level LodTensor to provide the height information
of the input tensor data.
col (Variable): The col should be 1-level LodTensor to provide the width information
of the input tensor data.
topks (list): A list of incremental value to average the topk feature.
channel_num (int): The number of input channel.
Returns:
Variable: output LodTensor specified by this layer.
Examples:
.. code-block:: python
import numpy as np
from paddle.fluid import layers
from paddle.fluid import contrib
x_lod_tensor = layers.data(name='x', shape=[1], lod_level=1)
row_lod_tensor = layers.data(name='row', shape=[6], lod_level=1)
col_lod_tensor = layers.data(name='col', shape=[6], lod_level=1)
out = contrib.sequence_topk_avg_pooling(input=x_lod_tensor,
row=row_lod_tensor,
col=col_lod_tensor,
topks=[1, 3, 5],
channel_num=5)
"""
helper = LayerHelper('sequence_topk_avg_pooling', **locals())
out = helper.create_variable_for_type_inference(dtype=helper.input_dtype())
pos = helper.create_variable_for_type_inference(
dtype=helper.input_dtype(), stop_gradient=True)
helper.append_op(
type='sequence_topk_avg_pooling',
inputs={'X': input,
'ROW': row,
'COLUMN': col},
outputs={'Out': out,
'pos': pos},
attrs={'topks': topks,
'channel_num': channel_num})
return out | [
"def",
"sequence_topk_avg_pooling",
"(",
"input",
",",
"row",
",",
"col",
",",
"topks",
",",
"channel_num",
")",
":",
"helper",
"=",
"LayerHelper",
"(",
"'sequence_topk_avg_pooling'",
",",
"*",
"*",
"locals",
"(",
")",
")",
"out",
"=",
"helper",
".",
"crea... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/layers/nn.py#L334-L399 | |
facebookresearch/ELF | 1f790173095cd910976d9f651b80beb872ec5d12 | rlpytorch/trainer/trainer.py | python | Evaluator.__init__ | (self, name="eval", stats=True, verbose=False, actor_name="actor") | Initialization for Evaluator. Accepted arguments: ``num_games``, ``batch_size``, ``num_minibatch`` | Initialization for Evaluator. Accepted arguments: ``num_games``, ``batch_size``, ``num_minibatch`` | [
"Initialization",
"for",
"Evaluator",
".",
"Accepted",
"arguments",
":",
"num_games",
"batch_size",
"num_minibatch"
] | def __init__(self, name="eval", stats=True, verbose=False, actor_name="actor"):
''' Initialization for Evaluator. Accepted arguments: ``num_games``, ``batch_size``, ``num_minibatch``
'''
if stats:
self.stats = Stats(name)
child_providers = [ self.stats.args ]
else:
self.stats = None
child_providers = []
self.name = name
self.actor_name = actor_name
self.verbose = verbose
self.args = ArgsProvider(
call_from = self,
define_args = [
("keys_in_reply", "")
],
more_args = ["num_games", "batchsize", "num_minibatch"],
on_get_args = self._on_get_args,
child_providers = child_providers
) | [
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"\"eval\"",
",",
"stats",
"=",
"True",
",",
"verbose",
"=",
"False",
",",
"actor_name",
"=",
"\"actor\"",
")",
":",
"if",
"stats",
":",
"self",
".",
"stats",
"=",
"Stats",
"(",
"name",
")",
"child_pro... | https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/rlpytorch/trainer/trainer.py#L21-L42 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.