nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/operator.py | python | imatmul | (a, b) | return a | Same as a @= b. | Same as a | [
"Same",
"as",
"a"
] | def imatmul(a, b):
"Same as a @= b."
a @= b
return a | [
"def",
"imatmul",
"(",
"a",
",",
"b",
")",
":",
"a",
"@=",
"b",
"return",
"a"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/operator.py#L375-L378 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | libcxx/utils/gdb/libcxx/printers.py | python | StdStringPrinter._get_short_size | (self, short_field, short_size) | Short size depends on both endianness and a compile-time define. | Short size depends on both endianness and a compile-time define. | [
"Short",
"size",
"depends",
"on",
"both",
"endianness",
"and",
"a",
"compile",
"-",
"time",
"define",
"."
] | def _get_short_size(self, short_field, short_size):
"""Short size depends on both endianness and a compile-time define."""
# If the padding field is present after all this indirection, then string
# was compiled with _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT defined.
field = short_field.type.fields()[1].type.fields()[0]
libcpp_abi_alternate_string_layout = field.name and "__padding" in field.name
# This logical structure closely follows the original code (which is clearer
# in C++). Keep them parallel to make them easier to compare.
if libcpp_abi_alternate_string_layout:
if _libcpp_big_endian:
return short_size >> 1
else:
return short_size
elif _libcpp_big_endian:
return short_size
else:
return short_size >> 1 | [
"def",
"_get_short_size",
"(",
"self",
",",
"short_field",
",",
"short_size",
")",
":",
"# If the padding field is present after all this indirection, then string",
"# was compiled with _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT defined.",
"field",
"=",
"short_field",
".",
"type",
".",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/libcxx/utils/gdb/libcxx/printers.py#L195-L213 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | VersionInfo.ToString | (*args, **kwargs) | return _core_.VersionInfo_ToString(*args, **kwargs) | ToString(self) -> String | ToString(self) -> String | [
"ToString",
"(",
"self",
")",
"-",
">",
"String"
] | def ToString(*args, **kwargs):
"""ToString(self) -> String"""
return _core_.VersionInfo_ToString(*args, **kwargs) | [
"def",
"ToString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"VersionInfo_ToString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L16581-L16583 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/screen.py | python | screen.crlf | (self) | This advances the cursor with CRLF properties.
The cursor will line wrap and the screen may scroll. | This advances the cursor with CRLF properties.
The cursor will line wrap and the screen may scroll. | [
"This",
"advances",
"the",
"cursor",
"with",
"CRLF",
"properties",
".",
"The",
"cursor",
"will",
"line",
"wrap",
"and",
"the",
"screen",
"may",
"scroll",
"."
] | def crlf(self):
"""This advances the cursor with CRLF properties.
The cursor will line wrap and the screen may scroll.
"""
self.cr()
self.lf() | [
"def",
"crlf",
"(",
"self",
")",
":",
"self",
".",
"cr",
"(",
")",
"self",
".",
"lf",
"(",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/screen.py#L117-L123 | ||
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/enumerations/enumeratedclasses.py | python | EnumeratedClass.string | (self) | return self.string_ | Return the string identifying this enumeration. | Return the string identifying this enumeration. | [
"Return",
"the",
"string",
"identifying",
"this",
"enumeration",
"."
] | def string(self):
"""Return the string identifying this enumeration."""
return self.string_ | [
"def",
"string",
"(",
"self",
")",
":",
"return",
"self",
".",
"string_"
] | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/enumerations/enumeratedclasses.py#L39-L41 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/nntplib.py | python | NNTP._putline | (self, line) | Internal: send one line to the server, appending CRLF.
The `line` must be a bytes-like object. | Internal: send one line to the server, appending CRLF.
The `line` must be a bytes-like object. | [
"Internal",
":",
"send",
"one",
"line",
"to",
"the",
"server",
"appending",
"CRLF",
".",
"The",
"line",
"must",
"be",
"a",
"bytes",
"-",
"like",
"object",
"."
] | def _putline(self, line):
"""Internal: send one line to the server, appending CRLF.
The `line` must be a bytes-like object."""
sys.audit("nntplib.putline", self, line)
line = line + _CRLF
if self.debugging > 1: print('*put*', repr(line))
self.file.write(line)
self.file.flush() | [
"def",
"_putline",
"(",
"self",
",",
"line",
")",
":",
"sys",
".",
"audit",
"(",
"\"nntplib.putline\"",
",",
"self",
",",
"line",
")",
"line",
"=",
"line",
"+",
"_CRLF",
"if",
"self",
".",
"debugging",
">",
"1",
":",
"print",
"(",
"'*put*'",
",",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/nntplib.py#L441-L448 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/gui/DirectFrame.py | python | DirectFrame.__reinitComponent | (self, name, component_class, states, **kwargs) | Recreates the given component using the given keyword args. | Recreates the given component using the given keyword args. | [
"Recreates",
"the",
"given",
"component",
"using",
"the",
"given",
"keyword",
"args",
"."
] | def __reinitComponent(self, name, component_class, states, **kwargs):
"""Recreates the given component using the given keyword args."""
assert name in ("geom", "image", "text")
# constants should be local to or default arguments of constructors
for c in range(self['numStates']):
component_name = name + str(c)
try:
state = states[c]
except IndexError:
state = states[-1]
if self.hascomponent(component_name):
if state is None:
self.destroycomponent(component_name)
else:
self[component_name + "_" + name] = state
else:
if state is None:
return
kwargs[name] = state
self.createcomponent(
component_name,
(),
name,
component_class,
(),
parent=self.stateNodePath[c],
**kwargs
) | [
"def",
"__reinitComponent",
"(",
"self",
",",
"name",
",",
"component_class",
",",
"states",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"name",
"in",
"(",
"\"geom\"",
",",
"\"image\"",
",",
"\"text\"",
")",
"# constants should be local to or default arguments of... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/gui/DirectFrame.py#L60-L91 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/difflib.py | python | get_close_matches | (word, possibilities, n=3, cutoff=0.6) | return [x for score, x in result] | Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of strings).
Optional arg n (default 3) is the maximum number of close matches to
return. n must be > 0.
Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
that don't score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned
in a list, sorted by similarity score, most similar first.
>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except'] | Use SequenceMatcher to return list of the best "good enough" matches. | [
"Use",
"SequenceMatcher",
"to",
"return",
"list",
"of",
"the",
"best",
"good",
"enough",
"matches",
"."
] | def get_close_matches(word, possibilities, n=3, cutoff=0.6):
"""Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of strings).
Optional arg n (default 3) is the maximum number of close matches to
return. n must be > 0.
Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
that don't score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned
in a list, sorted by similarity score, most similar first.
>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except']
"""
if not n > 0:
raise ValueError("n must be > 0: %r" % (n,))
if not 0.0 <= cutoff <= 1.0:
raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
result = []
s = SequenceMatcher()
s.set_seq2(word)
for x in possibilities:
s.set_seq1(x)
if s.real_quick_ratio() >= cutoff and \
s.quick_ratio() >= cutoff and \
s.ratio() >= cutoff:
result.append((s.ratio(), x))
# Move the best scorers to head of list
result = heapq.nlargest(n, result)
# Strip scores for the best n matches
return [x for score, x in result] | [
"def",
"get_close_matches",
"(",
"word",
",",
"possibilities",
",",
"n",
"=",
"3",
",",
"cutoff",
"=",
"0.6",
")",
":",
"if",
"not",
"n",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"n must be > 0: %r\"",
"%",
"(",
"n",
",",
")",
")",
"if",
"not",
... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/difflib.py#L704-L750 | |
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/bandit/data_containers.py | python | HistoricalData.json_payload | (self) | return {'arms_sampled': json_arms_sampled} | Construct a json serializeable and MOE REST recognizeable dictionary of the historical data. | Construct a json serializeable and MOE REST recognizeable dictionary of the historical data. | [
"Construct",
"a",
"json",
"serializeable",
"and",
"MOE",
"REST",
"recognizeable",
"dictionary",
"of",
"the",
"historical",
"data",
"."
] | def json_payload(self):
"""Construct a json serializeable and MOE REST recognizeable dictionary of the historical data."""
json_arms_sampled = {}
for name, arm in self._arms_sampled.iteritems():
json_arms_sampled[name] = arm.json_payload()
return {'arms_sampled': json_arms_sampled} | [
"def",
"json_payload",
"(",
"self",
")",
":",
"json_arms_sampled",
"=",
"{",
"}",
"for",
"name",
",",
"arm",
"in",
"self",
".",
"_arms_sampled",
".",
"iteritems",
"(",
")",
":",
"json_arms_sampled",
"[",
"name",
"]",
"=",
"arm",
".",
"json_payload",
"(",... | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/bandit/data_containers.py#L202-L207 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/handlers.py | python | BaseHandler.run | (self, application) | Invoke the application | Invoke the application | [
"Invoke",
"the",
"application"
] | def run(self, application):
"""Invoke the application"""
# Note to self: don't move the close()! Asynchronous servers shouldn't
# call close() from finish_response(), so if you close() anywhere but
# the double-error branch here, you'll break asynchronous servers by
# prematurely closing. Async servers must return from 'run()' without
# closing if there might still be output to iterate over.
try:
self.setup_environ()
self.result = application(self.environ, self.start_response)
self.finish_response()
except (ConnectionAbortedError, BrokenPipeError, ConnectionResetError):
# We expect the client to close the connection abruptly from time
# to time.
return
except:
try:
self.handle_error()
except:
# If we get an error handling an error, just give up already!
self.close()
raise | [
"def",
"run",
"(",
"self",
",",
"application",
")",
":",
"# Note to self: don't move the close()! Asynchronous servers shouldn't",
"# call close() from finish_response(), so if you close() anywhere but",
"# the double-error branch here, you'll break asynchronous servers by",
"# prematurely cl... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/handlers.py#L128-L149 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/ttk.py | python | _format_optdict | (optdict, script=False, ignore=None) | return _flatten(opts) | Formats optdict to a tuple to pass it to tk.call.
E.g. (script=False):
{'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
('-foreground', 'blue', '-padding', '1 2 3 4') | Formats optdict to a tuple to pass it to tk.call. | [
"Formats",
"optdict",
"to",
"a",
"tuple",
"to",
"pass",
"it",
"to",
"tk",
".",
"call",
"."
] | def _format_optdict(optdict, script=False, ignore=None):
"""Formats optdict to a tuple to pass it to tk.call.
E.g. (script=False):
{'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
('-foreground', 'blue', '-padding', '1 2 3 4')"""
opts = []
for opt, value in optdict.items():
if not ignore or opt not in ignore:
opts.append("-%s" % opt)
if value is not None:
opts.append(_format_optvalue(value, script))
return _flatten(opts) | [
"def",
"_format_optdict",
"(",
"optdict",
",",
"script",
"=",
"False",
",",
"ignore",
"=",
"None",
")",
":",
"opts",
"=",
"[",
"]",
"for",
"opt",
",",
"value",
"in",
"optdict",
".",
"items",
"(",
")",
":",
"if",
"not",
"ignore",
"or",
"opt",
"not",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/ttk.py#L61-L75 | |
kevin-ssy/Optical-Flow-Guided-Feature | 07d4501a29002ee7821c38c1820e4a64c1acf6e8 | lib/caffe-action/python/caffe/detector.py | python | Detector.configure_crop | (self, context_pad) | Configure crop dimensions and amount of context for cropping.
If context is included, make the special input mean for context padding.
Parameters
----------
context_pad : amount of context for cropping. | Configure crop dimensions and amount of context for cropping.
If context is included, make the special input mean for context padding. | [
"Configure",
"crop",
"dimensions",
"and",
"amount",
"of",
"context",
"for",
"cropping",
".",
"If",
"context",
"is",
"included",
"make",
"the",
"special",
"input",
"mean",
"for",
"context",
"padding",
"."
] | def configure_crop(self, context_pad):
"""
Configure crop dimensions and amount of context for cropping.
If context is included, make the special input mean for context padding.
Parameters
----------
context_pad : amount of context for cropping.
"""
# crop dimensions
in_ = self.inputs[0]
tpose = self.transformer.transpose[in_]
inv_tpose = [tpose[t] for t in tpose]
self.crop_dims = np.array(self.blobs[in_].data.shape[1:])[inv_tpose]
#.transpose(inv_tpose)
# context padding
self.context_pad = context_pad
if self.context_pad:
in_ = self.inputs[0]
transpose = self.transformer.transpose.get(in_)
channel_order = self.transformer.channel_swap.get(in_)
raw_scale = self.transformer.raw_scale.get(in_)
# Padding context crops needs the mean in unprocessed input space.
mean = self.transformer.mean.get(in_)
if mean is not None:
inv_transpose = [transpose[t] for t in transpose]
crop_mean = mean.copy().transpose(inv_transpose)
if channel_order is not None:
channel_order_inverse = [channel_order.index(i)
for i in range(crop_mean.shape[2])]
crop_mean = crop_mean[:, :, channel_order_inverse]
if raw_scale is not None:
crop_mean /= raw_scale
self.crop_mean = crop_mean
else:
self.crop_mean = np.zeros(self.crop_dims, dtype=np.float32) | [
"def",
"configure_crop",
"(",
"self",
",",
"context_pad",
")",
":",
"# crop dimensions",
"in_",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
"tpose",
"=",
"self",
".",
"transformer",
".",
"transpose",
"[",
"in_",
"]",
"inv_tpose",
"=",
"[",
"tpose",
"[",
... | https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/python/caffe/detector.py#L181-L216 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/xcode_ninja.py | python | _TargetFromSpec | (old_spec, params) | return ninja_target | Create fake target for xcode-ninja wrapper. | Create fake target for xcode-ninja wrapper. | [
"Create",
"fake",
"target",
"for",
"xcode",
"-",
"ninja",
"wrapper",
"."
] | def _TargetFromSpec(old_spec, params):
""" Create fake target for xcode-ninja wrapper. """
# Determine ninja top level build dir (e.g. /path/to/out).
ninja_toplevel = None
jobs = 0
if params:
options = params['options']
ninja_toplevel = \
os.path.join(options.toplevel_dir,
gyp.generator.ninja.ComputeOutputDir(params))
jobs = params.get('generator_flags', {}).get('xcode_ninja_jobs', 0)
target_name = old_spec.get('target_name')
product_name = old_spec.get('product_name', target_name)
product_extension = old_spec.get('product_extension')
ninja_target = {}
ninja_target['target_name'] = target_name
ninja_target['product_name'] = product_name
if product_extension:
ninja_target['product_extension'] = product_extension
ninja_target['toolset'] = old_spec.get('toolset')
ninja_target['default_configuration'] = old_spec.get('default_configuration')
ninja_target['configurations'] = {}
# Tell Xcode to look in |ninja_toplevel| for build products.
new_xcode_settings = {}
if ninja_toplevel:
new_xcode_settings['CONFIGURATION_BUILD_DIR'] = \
"%s/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)" % ninja_toplevel
if 'configurations' in old_spec:
for config in old_spec['configurations']:
old_xcode_settings = \
old_spec['configurations'][config].get('xcode_settings', {})
if 'IPHONEOS_DEPLOYMENT_TARGET' in old_xcode_settings:
new_xcode_settings['CODE_SIGNING_REQUIRED'] = "NO"
new_xcode_settings['IPHONEOS_DEPLOYMENT_TARGET'] = \
old_xcode_settings['IPHONEOS_DEPLOYMENT_TARGET']
for key in ['BUNDLE_LOADER', 'TEST_HOST']:
if key in old_xcode_settings:
new_xcode_settings[key] = old_xcode_settings[key]
ninja_target['configurations'][config] = {}
ninja_target['configurations'][config]['xcode_settings'] = \
new_xcode_settings
ninja_target['mac_bundle'] = old_spec.get('mac_bundle', 0)
ninja_target['mac_xctest_bundle'] = old_spec.get('mac_xctest_bundle', 0)
ninja_target['ios_app_extension'] = old_spec.get('ios_app_extension', 0)
ninja_target['ios_watchkit_extension'] = \
old_spec.get('ios_watchkit_extension', 0)
ninja_target['ios_watchkit_app'] = old_spec.get('ios_watchkit_app', 0)
ninja_target['type'] = old_spec['type']
if ninja_toplevel:
ninja_target['actions'] = [
{
'action_name': 'Compile and copy %s via ninja' % target_name,
'inputs': [],
'outputs': [],
'action': [
'env',
'PATH=%s' % os.environ['PATH'],
'ninja',
'-C',
new_xcode_settings['CONFIGURATION_BUILD_DIR'],
target_name,
],
'message': 'Compile and copy %s via ninja' % target_name,
},
]
if jobs > 0:
ninja_target['actions'][0]['action'].extend(('-j', jobs))
return ninja_target | [
"def",
"_TargetFromSpec",
"(",
"old_spec",
",",
"params",
")",
":",
"# Determine ninja top level build dir (e.g. /path/to/out).",
"ninja_toplevel",
"=",
"None",
"jobs",
"=",
"0",
"if",
"params",
":",
"options",
"=",
"params",
"[",
"'options'",
"]",
"ninja_toplevel",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/xcode_ninja.py#L56-L129 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | NLP/parser.py | python | dobj_dependence | (row) | dependence type is direct obj, predicate is a verb and object is a noun
:param row: (('dog', 'NN'), 'case', ('over', 'IN'))
:return: True or False | dependence type is direct obj, predicate is a verb and object is a noun
:param row: (('dog', 'NN'), 'case', ('over', 'IN'))
:return: True or False | [
"dependence",
"type",
"is",
"direct",
"obj",
"predicate",
"is",
"a",
"verb",
"and",
"object",
"is",
"a",
"noun",
":",
"param",
"row",
":",
"((",
"dog",
"NN",
")",
"case",
"(",
"over",
"IN",
"))",
":",
"return",
":",
"True",
"or",
"False"
] | def dobj_dependence(row):
"""
dependence type is direct obj, predicate is a verb and object is a noun
:param row: (('dog', 'NN'), 'case', ('over', 'IN'))
:return: True or False
"""
if row[1] == "dobj" and "V" in row[0][1] and "NN" in row[2][1]:
print(row)
return True
else:
return False | [
"def",
"dobj_dependence",
"(",
"row",
")",
":",
"if",
"row",
"[",
"1",
"]",
"==",
"\"dobj\"",
"and",
"\"V\"",
"in",
"row",
"[",
"0",
"]",
"[",
"1",
"]",
"and",
"\"NN\"",
"in",
"row",
"[",
"2",
"]",
"[",
"1",
"]",
":",
"print",
"(",
"row",
")"... | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/NLP/parser.py#L58-L68 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Sizer.ComputeFittingClientSize | (*args, **kwargs) | return _core_.Sizer_ComputeFittingClientSize(*args, **kwargs) | ComputeFittingClientSize(self, Window window) -> Size
Computes client area size for ``window`` so that it matches the
sizer's minimal size. Unlike `GetMinSize`, this method accounts for
other constraints imposed on ``window``, namely display's size
(returned size will never be too large for the display) and maximum
window size if previously set by `wx.Window.SetMaxSize`.
The returned value is suitable for passing to
`wx.Window.SetClientSize` or `wx`Window.SetMinClientSize`. | ComputeFittingClientSize(self, Window window) -> Size | [
"ComputeFittingClientSize",
"(",
"self",
"Window",
"window",
")",
"-",
">",
"Size"
] | def ComputeFittingClientSize(*args, **kwargs):
"""
ComputeFittingClientSize(self, Window window) -> Size
Computes client area size for ``window`` so that it matches the
sizer's minimal size. Unlike `GetMinSize`, this method accounts for
other constraints imposed on ``window``, namely display's size
(returned size will never be too large for the display) and maximum
window size if previously set by `wx.Window.SetMaxSize`.
The returned value is suitable for passing to
`wx.Window.SetClientSize` or `wx`Window.SetMinClientSize`.
"""
return _core_.Sizer_ComputeFittingClientSize(*args, **kwargs) | [
"def",
"ComputeFittingClientSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Sizer_ComputeFittingClientSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L14848-L14861 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/examples/python/diagnose_unwind.py | python | diagnose_unwind | (debugger, command, result, dict) | Gather diagnostic information to help debug incorrect unwind (backtrace)
behavior in lldb. When there is a backtrace that doesn't look
correct, run this command with the correct thread selected and a
large amount of diagnostic information will be printed, it is likely
to be helpful when reporting the problem. | Gather diagnostic information to help debug incorrect unwind (backtrace)
behavior in lldb. When there is a backtrace that doesn't look
correct, run this command with the correct thread selected and a
large amount of diagnostic information will be printed, it is likely
to be helpful when reporting the problem. | [
"Gather",
"diagnostic",
"information",
"to",
"help",
"debug",
"incorrect",
"unwind",
"(",
"backtrace",
")",
"behavior",
"in",
"lldb",
".",
"When",
"there",
"is",
"a",
"backtrace",
"that",
"doesn",
"t",
"look",
"correct",
"run",
"this",
"command",
"with",
"th... | def diagnose_unwind(debugger, command, result, dict):
"""
Gather diagnostic information to help debug incorrect unwind (backtrace)
behavior in lldb. When there is a backtrace that doesn't look
correct, run this command with the correct thread selected and a
large amount of diagnostic information will be printed, it is likely
to be helpful when reporting the problem.
"""
command_args = shlex.split(command)
parser = create_diagnose_unwind_options()
try:
(options, args) = parser.parse_args(command_args)
except:
return
target = debugger.GetSelectedTarget()
if target:
process = target.GetProcess()
if process:
thread = process.GetSelectedThread()
if thread:
lldb_versions_match = re.search(
r'[lL][lL][dD][bB]-(\d+)([.](\d+))?([.](\d+))?',
debugger.GetVersionString())
lldb_version = 0
lldb_minor = 0
if len(lldb_versions_match.groups()
) >= 1 and lldb_versions_match.groups()[0]:
lldb_major = int(lldb_versions_match.groups()[0])
if len(lldb_versions_match.groups()
) >= 5 and lldb_versions_match.groups()[4]:
lldb_minor = int(lldb_versions_match.groups()[4])
modules_seen = []
addresses_seen = []
print 'LLDB version %s' % debugger.GetVersionString()
print 'Unwind diagnostics for thread %d' % thread.GetIndexID()
print ""
print "============================================================================================="
print ""
print "OS plugin setting:"
debugger.HandleCommand(
"settings show target.process.python-os-plugin-path")
print ""
print "Live register context:"
thread.SetSelectedFrame(0)
debugger.HandleCommand("register read")
print ""
print "============================================================================================="
print ""
print "lldb's unwind algorithm:"
print ""
frame_num = 0
for frame in thread.frames:
if not frame.IsInlined():
this_module = backtrace_print_frame(
target, frame_num, frame.GetPC(), frame.GetFP())
print_stack_frame(process, frame.GetFP())
print ""
if this_module is not None:
modules_seen.append(this_module)
addresses_seen.append(frame.GetPC())
frame_num = frame_num + 1
print ""
print "============================================================================================="
print ""
print "Simple stack walk algorithm:"
print ""
(module_list, address_list) = simple_backtrace(debugger)
if module_list and module_list is not None:
modules_seen += module_list
if address_list and address_list is not None:
addresses_seen = set(addresses_seen)
addresses_seen.update(set(address_list))
print ""
print "============================================================================================="
print ""
print "Modules seen in stack walks:"
print ""
modules_already_seen = set()
for module in modules_seen:
if module is not None and module.GetFileSpec().GetFilename() is not None:
if not module.GetFileSpec().GetFilename() in modules_already_seen:
debugger.HandleCommand(
'image list %s' %
module.GetFileSpec().GetFilename())
modules_already_seen.add(
module.GetFileSpec().GetFilename())
print ""
print "============================================================================================="
print ""
print "Disassembly ofaddresses seen in stack walks:"
print ""
additional_addresses_to_disassemble = addresses_seen
for frame in thread.frames:
if not frame.IsInlined():
print "--------------------------------------------------------------------------------------"
print ""
print "Disassembly of %s, frame %d, address 0x%x" % (frame.GetFunctionName(), frame.GetFrameID(), frame.GetPC())
print ""
if target.triple[
0:6] == "x86_64" or target.triple[
0:4] == "i386":
debugger.HandleCommand(
'disassemble -F att -a 0x%x' % frame.GetPC())
else:
debugger.HandleCommand(
'disassemble -a 0x%x' %
frame.GetPC())
if frame.GetPC() in additional_addresses_to_disassemble:
additional_addresses_to_disassemble.remove(
frame.GetPC())
for address in list(additional_addresses_to_disassemble):
print "--------------------------------------------------------------------------------------"
print ""
print "Disassembly of 0x%x" % address
print ""
if target.triple[
0:6] == "x86_64" or target.triple[
0:4] == "i386":
debugger.HandleCommand(
'disassemble -F att -a 0x%x' % address)
else:
debugger.HandleCommand('disassemble -a 0x%x' % address)
print ""
print "============================================================================================="
print ""
additional_addresses_to_show_unwind = addresses_seen
for frame in thread.frames:
if not frame.IsInlined():
print "--------------------------------------------------------------------------------------"
print ""
print "Unwind instructions for %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID())
print ""
debugger.HandleCommand(
'image show-unwind -a "0x%x"' % frame.GetPC())
if frame.GetPC() in additional_addresses_to_show_unwind:
additional_addresses_to_show_unwind.remove(
frame.GetPC())
for address in list(additional_addresses_to_show_unwind):
print "--------------------------------------------------------------------------------------"
print ""
print "Unwind instructions for 0x%x" % address
print ""
debugger.HandleCommand(
'image show-unwind -a "0x%x"' % address) | [
"def",
"diagnose_unwind",
"(",
"debugger",
",",
"command",
",",
"result",
",",
"dict",
")",
":",
"command_args",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"parser",
"=",
"create_diagnose_unwind_options",
"(",
")",
"try",
":",
"(",
"options",
",",
"a... | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/examples/python/diagnose_unwind.py#L147-L298 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/tpu/python/tpu/tpu_function.py | python | check_function_argument_count | (func, input_arity, infeed_queue) | return None | Validate the number of input arguments to a tpu function.
Args:
func: the Python function that will be called to generate the body
of a TPUFunction.
input_arity: the number of explicit arguments supplied by the
caller.
infeed_queue: if not None, the infeed queue that will supply
additional arguments to the function.
Returns:
None if function can be called with the supplied number of
arguments, or an error string if it cannot. | Validate the number of input arguments to a tpu function. | [
"Validate",
"the",
"number",
"of",
"input",
"arguments",
"to",
"a",
"tpu",
"function",
"."
] | def check_function_argument_count(func, input_arity, infeed_queue):
"""Validate the number of input arguments to a tpu function.
Args:
func: the Python function that will be called to generate the body
of a TPUFunction.
input_arity: the number of explicit arguments supplied by the
caller.
infeed_queue: if not None, the infeed queue that will supply
additional arguments to the function.
Returns:
None if function can be called with the supplied number of
arguments, or an error string if it cannot.
"""
def format_error(complaint, quantity):
return "%s %d argument%s" % (complaint, quantity, ""
if quantity == 1 else "s")
number_of_arguments_needed = input_arity
if infeed_queue is not None:
number_of_arguments_needed += infeed_queue.number_of_tuple_elements
arg_spec = tf_inspect.getargspec(func)
number_of_args = len(arg_spec.args)
if arg_spec.defaults is None:
number_of_defaults = 0
else:
number_of_defaults = len(arg_spec.defaults)
min_required_arguments = number_of_args - number_of_defaults
if number_of_arguments_needed < min_required_arguments:
# The required number of arguments is not enough to call the function.
if number_of_defaults == 0 and arg_spec.varargs is None:
return format_error("exactly", number_of_args)
else:
return format_error("at least", min_required_arguments)
if arg_spec.varargs is None and number_of_arguments_needed > number_of_args:
# The required number of arguments is too many to call the function.
if number_of_defaults == 0:
return format_error("exactly", number_of_args)
else:
return format_error("at most", number_of_args)
# Since there are varargs, func can accept any number of arguments
# greater than the minimum.
return None | [
"def",
"check_function_argument_count",
"(",
"func",
",",
"input_arity",
",",
"infeed_queue",
")",
":",
"def",
"format_error",
"(",
"complaint",
",",
"quantity",
")",
":",
"return",
"\"%s %d argument%s\"",
"%",
"(",
"complaint",
",",
"quantity",
",",
"\"\"",
"if... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tpu/python/tpu/tpu_function.py#L62-L105 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | FWCore/ParameterSet/python/Config.py | python | Process.extend | (self,other,items=()) | Look in other and find types that we can use | Look in other and find types that we can use | [
"Look",
"in",
"other",
"and",
"find",
"types",
"that",
"we",
"can",
"use"
] | def extend(self,other,items=()):
"""Look in other and find types that we can use"""
# enable explicit check to avoid overwriting of existing objects
self.__dict__['_Process__InExtendCall'] = True
seqs = dict()
tasksToAttach = dict()
mods = []
for name in dir(other):
#'from XX import *' ignores these, and so should we.
if name.startswith('_'):
continue
item = getattr(other,name)
if name == "source" or name == "looper":
# In these cases 'item' could be None if the specific object was not defined
if item is not None:
self.__setattr__(name,item)
elif isinstance(item,_ModuleSequenceType):
seqs[name]=item
elif isinstance(item,Task):
tasksToAttach[name] = item
elif isinstance(item,_Labelable):
self.__setattr__(name,item)
if not item.hasLabel_() :
item.setLabel(name)
elif isinstance(item,Schedule):
self.__setattr__(name,item)
elif isinstance(item,_Unlabelable):
self.add_(item)
elif isinstance(item,ProcessModifier):
mods.append(item)
elif isinstance(item,ProcessFragment):
self.extend(item)
#now create a sequence that uses the newly made items
for name,seq in seqs.items():
if id(seq) not in self._cloneToObjectDict:
self.__setattr__(name,seq)
else:
newSeq = self._cloneToObjectDict[id(seq)]
self.__dict__[name]=newSeq
self.__setObjectLabel(newSeq, name)
#now put in proper bucket
newSeq._place(name,self)
for name, task in tasksToAttach.items():
self.__setattr__(name, task)
#apply modifiers now that all names have been added
for item in mods:
item.apply(self)
self.__dict__['_Process__InExtendCall'] = False | [
"def",
"extend",
"(",
"self",
",",
"other",
",",
"items",
"=",
"(",
")",
")",
":",
"# enable explicit check to avoid overwriting of existing objects",
"self",
".",
"__dict__",
"[",
"'_Process__InExtendCall'",
"]",
"=",
"True",
"seqs",
"=",
"dict",
"(",
")",
"tas... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/Config.py#L715-L767 | ||
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/internal/charmm/topologyobjects.py | python | _CmapGrid.transpose | (self) | return self._transpose | Returns the transpose of the grid | Returns the transpose of the grid | [
"Returns",
"the",
"transpose",
"of",
"the",
"grid"
] | def transpose(self):
""" Returns the transpose of the grid """
try:
return self._transpose
except AttributeError:
pass
_transpose = []
size = len(self._data)
for i in range(self.resolution):
piece = [self[j] for j in range(i, size, self.resolution)]
_transpose += piece
self._transpose = _CmapGrid(self.resolution, _transpose)
return self._transpose | [
"def",
"transpose",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_transpose",
"except",
"AttributeError",
":",
"pass",
"_transpose",
"=",
"[",
"]",
"size",
"=",
"len",
"(",
"self",
".",
"_data",
")",
"for",
"i",
"in",
"range",
"(",
"sel... | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/internal/charmm/topologyobjects.py#L1176-L1188 | |
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/bindings-generator/clang/cindex.py | python | TranslationUnit.get_extent | (self, filename, locations) | return SourceRange.from_locations(start_location, end_location) | Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15))) | Obtain a SourceRange from this translation unit. | [
"Obtain",
"a",
"SourceRange",
"from",
"this",
"translation",
"unit",
"."
] | def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15)))
"""
f = self.get_file(filename)
if len(locations) < 2:
raise Exception('Must pass object with at least 2 elements')
start_location, end_location = locations
if hasattr(start_location, '__len__'):
start_location = SourceLocation.from_position(self, f,
start_location[0], start_location[1])
elif isinstance(start_location, int):
start_location = SourceLocation.from_offset(self, f,
start_location)
if hasattr(end_location, '__len__'):
end_location = SourceLocation.from_position(self, f,
end_location[0], end_location[1])
elif isinstance(end_location, int):
end_location = SourceLocation.from_offset(self, f, end_location)
assert isinstance(start_location, SourceLocation)
assert isinstance(end_location, SourceLocation)
return SourceRange.from_locations(start_location, end_location) | [
"def",
"get_extent",
"(",
"self",
",",
"filename",
",",
"locations",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"len",
"(",
"locations",
")",
"<",
"2",
":",
"raise",
"Exception",
"(",
"'Must pass object with at least 2 elements'... | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L2311-L2349 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | libcxx/utils/libcxx/util.py | python | killProcessAndChildren | (pid) | This function kills a process with ``pid`` and all its
running children (recursively). It is currently implemented
using the psutil module which provides a simple platform
neutral implementation.
TODO: Reimplement this without using psutil so we can
remove our dependency on it. | This function kills a process with ``pid`` and all its
running children (recursively). It is currently implemented
using the psutil module which provides a simple platform
neutral implementation. | [
"This",
"function",
"kills",
"a",
"process",
"with",
"pid",
"and",
"all",
"its",
"running",
"children",
"(",
"recursively",
")",
".",
"It",
"is",
"currently",
"implemented",
"using",
"the",
"psutil",
"module",
"which",
"provides",
"a",
"simple",
"platform",
... | def killProcessAndChildren(pid):
"""
This function kills a process with ``pid`` and all its
running children (recursively). It is currently implemented
using the psutil module which provides a simple platform
neutral implementation.
TODO: Reimplement this without using psutil so we can
remove our dependency on it.
"""
if platform.system() == 'AIX':
subprocess.call('kill -kill $(ps -o pid= -L{})'.format(pid), shell=True)
else:
import psutil
try:
psutilProc = psutil.Process(pid)
# Handle the different psutil API versions
try:
# psutil >= 2.x
children_iterator = psutilProc.children(recursive=True)
except AttributeError:
# psutil 1.x
children_iterator = psutilProc.get_children(recursive=True)
for child in children_iterator:
try:
child.kill()
except psutil.NoSuchProcess:
pass
psutilProc.kill()
except psutil.NoSuchProcess:
pass | [
"def",
"killProcessAndChildren",
"(",
"pid",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'AIX'",
":",
"subprocess",
".",
"call",
"(",
"'kill -kill $(ps -o pid= -L{})'",
".",
"format",
"(",
"pid",
")",
",",
"shell",
"=",
"True",
")",
"else",... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/libcxx/utils/libcxx/util.py#L246-L276 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/operator.py | python | rshift | (a, b) | return a >> b | Same as a >> b. | Same as a >> b. | [
"Same",
"as",
"a",
">>",
"b",
"."
] | def rshift(a, b):
"Same as a >> b."
return a >> b | [
"def",
"rshift",
"(",
"a",
",",
"b",
")",
":",
"return",
"a",
">>",
"b"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/operator.py#L128-L130 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py | python | VimPane.prepare | (self, method='new') | check window is OK, if not then create | check window is OK, if not then create | [
"check",
"window",
"is",
"OK",
"if",
"not",
"then",
"create"
] | def prepare(self, method='new'):
""" check window is OK, if not then create """
if not self.isPrepared():
self.create(method) | [
"def",
"prepare",
"(",
"self",
",",
"method",
"=",
"'new'",
")",
":",
"if",
"not",
"self",
".",
"isPrepared",
"(",
")",
":",
"self",
".",
"create",
"(",
"method",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L260-L263 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py | python | KMeansClustering.predict | (self, x, batch_size=None) | return super(KMeansClustering, self).predict(
x=x, batch_size=batch_size)[KMeansClustering.CLUSTER_IDX] | Predict cluster id for each element in x.
Args:
x: 2-D matrix or iterator.
batch_size: size to use for batching up x for querying the model.
Returns:
Array with same number of rows as x, containing cluster ids. | Predict cluster id for each element in x. | [
"Predict",
"cluster",
"id",
"for",
"each",
"element",
"in",
"x",
"."
] | def predict(self, x, batch_size=None):
"""Predict cluster id for each element in x.
Args:
x: 2-D matrix or iterator.
batch_size: size to use for batching up x for querying the model.
Returns:
Array with same number of rows as x, containing cluster ids.
"""
return super(KMeansClustering, self).predict(
x=x, batch_size=batch_size)[KMeansClustering.CLUSTER_IDX] | [
"def",
"predict",
"(",
"self",
",",
"x",
",",
"batch_size",
"=",
"None",
")",
":",
"return",
"super",
"(",
"KMeansClustering",
",",
"self",
")",
".",
"predict",
"(",
"x",
"=",
"x",
",",
"batch_size",
"=",
"batch_size",
")",
"[",
"KMeansClustering",
"."... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py#L170-L181 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/auibar.py | python | AuiToolBar.GetLabelSize | (self, label) | return GetLabelSize(dc, label, self._tool_orientation != AUI_TBTOOL_HORIZONTAL) | Returns the standard size of a toolbar item.
:param string `label`: a test label. | Returns the standard size of a toolbar item. | [
"Returns",
"the",
"standard",
"size",
"of",
"a",
"toolbar",
"item",
"."
] | def GetLabelSize(self, label):
"""
Returns the standard size of a toolbar item.
:param string `label`: a test label.
"""
dc = wx.ClientDC(self)
dc.SetFont(self._font)
return GetLabelSize(dc, label, self._tool_orientation != AUI_TBTOOL_HORIZONTAL) | [
"def",
"GetLabelSize",
"(",
"self",
",",
"label",
")",
":",
"dc",
"=",
"wx",
".",
"ClientDC",
"(",
"self",
")",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_font",
")",
"return",
"GetLabelSize",
"(",
"dc",
",",
"label",
",",
"self",
".",
"_tool_orientat... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L3211-L3221 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/cephadm/services/cephadmservice.py | python | CephadmService.purge | (self, service_name: str) | Called to carry out any purge tasks following service removal | Called to carry out any purge tasks following service removal | [
"Called",
"to",
"carry",
"out",
"any",
"purge",
"tasks",
"following",
"service",
"removal"
] | def purge(self, service_name: str) -> None:
"""Called to carry out any purge tasks following service removal"""
logger.debug(f'Purge called for {self.TYPE} - no action taken') | [
"def",
"purge",
"(",
"self",
",",
"service_name",
":",
"str",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"f'Purge called for {self.TYPE} - no action taken'",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/cephadm/services/cephadmservice.py#L423-L425 | ||
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/cef_parser.py | python | obj_class.get_attrib | (self, name) | return None | Return the first or only value for specified attribute. | Return the first or only value for specified attribute. | [
"Return",
"the",
"first",
"or",
"only",
"value",
"for",
"specified",
"attribute",
"."
] | def get_attrib(self, name):
""" Return the first or only value for specified attribute. """
if name in self.attribs:
if isinstance(self.attribs[name], list):
# the value is a list
return self.attribs[name][0]
else:
# the value is a string
return self.attribs[name]
return None | [
"def",
"get_attrib",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"attribs",
":",
"if",
"isinstance",
"(",
"self",
".",
"attribs",
"[",
"name",
"]",
",",
"list",
")",
":",
"# the value is a list",
"return",
"self",
".",
"attribs... | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/cef_parser.py#L976-L985 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/graph.py | python | DirectedGraph.Edges | (self) | return self._edges | Returns the set of edges of this graph. | Returns the set of edges of this graph. | [
"Returns",
"the",
"set",
"of",
"edges",
"of",
"this",
"graph",
"."
] | def Edges(self):
"""Returns the set of edges of this graph."""
return self._edges | [
"def",
"Edges",
"(",
"self",
")",
":",
"return",
"self",
".",
"_edges"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/graph.py#L98-L100 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py | python | _find_address_range | (addresses) | Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence. | Find a sequence of sorted deduplicated IPv#Address. | [
"Find",
"a",
"sequence",
"of",
"sorted",
"deduplicated",
"IPv#Address",
"."
] | def _find_address_range(addresses):
"""Find a sequence of sorted deduplicated IPv#Address.
Args:
addresses: a list of IPv#Address objects.
Yields:
A tuple containing the first and last IP addresses in the sequence.
"""
it = iter(addresses)
first = last = next(it)
for ip in it:
if ip._ip != last._ip + 1:
yield first, last
first = ip
last = ip
yield first, last | [
"def",
"_find_address_range",
"(",
"addresses",
")",
":",
"it",
"=",
"iter",
"(",
"addresses",
")",
"first",
"=",
"last",
"=",
"next",
"(",
"it",
")",
"for",
"ip",
"in",
"it",
":",
"if",
"ip",
".",
"_ip",
"!=",
"last",
".",
"_ip",
"+",
"1",
":",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py#L166-L183 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/formats/latex.py | python | TableBuilderAbstract.env_body | (self) | Environment body. | Environment body. | [
"Environment",
"body",
"."
] | def env_body(self) -> str:
"""Environment body.""" | [
"def",
"env_body",
"(",
"self",
")",
"->",
"str",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/latex.py#L388-L389 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/closure_compiler/compile2.py | python | Checker._log_debug | (self, msg, error=False) | Logs |msg| to stdout if --verbose/-v is passed when invoking this script.
Args:
msg: A debug message to log. | Logs |msg| to stdout if --verbose/-v is passed when invoking this script. | [
"Logs",
"|msg|",
"to",
"stdout",
"if",
"--",
"verbose",
"/",
"-",
"v",
"is",
"passed",
"when",
"invoking",
"this",
"script",
"."
] | def _log_debug(self, msg, error=False):
"""Logs |msg| to stdout if --verbose/-v is passed when invoking this script.
Args:
msg: A debug message to log.
"""
if self._verbose:
print "(INFO) %s" % msg | [
"def",
"_log_debug",
"(",
"self",
",",
"msg",
",",
"error",
"=",
"False",
")",
":",
"if",
"self",
".",
"_verbose",
":",
"print",
"\"(INFO) %s\"",
"%",
"msg"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/closure_compiler/compile2.py#L62-L69 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/mgr/dashboard/helper.py | python | DashboardTestCase.create_user | (cls, username, password, roles=None,
force_password=True, cmd_args=None) | :param username: The name of the user.
:type username: str
:param password: The password.
:type password: str
:param roles: A list of roles.
:type roles: list
:param force_password: Force the use of the specified password. This
will bypass the password complexity check. Defaults to 'True'.
:type force_password: bool
:param cmd_args: Additional command line arguments for the
'ac-user-create' command.
:type cmd_args: None | list[str] | :param username: The name of the user.
:type username: str
:param password: The password.
:type password: str
:param roles: A list of roles.
:type roles: list
:param force_password: Force the use of the specified password. This
will bypass the password complexity check. Defaults to 'True'.
:type force_password: bool
:param cmd_args: Additional command line arguments for the
'ac-user-create' command.
:type cmd_args: None | list[str] | [
":",
"param",
"username",
":",
"The",
"name",
"of",
"the",
"user",
".",
":",
"type",
"username",
":",
"str",
":",
"param",
"password",
":",
"The",
"password",
".",
":",
"type",
"password",
":",
"str",
":",
"param",
"roles",
":",
"A",
"list",
"of",
... | def create_user(cls, username, password, roles=None,
force_password=True, cmd_args=None):
# pylint: disable=too-many-arguments
"""
:param username: The name of the user.
:type username: str
:param password: The password.
:type password: str
:param roles: A list of roles.
:type roles: list
:param force_password: Force the use of the specified password. This
will bypass the password complexity check. Defaults to 'True'.
:type force_password: bool
:param cmd_args: Additional command line arguments for the
'ac-user-create' command.
:type cmd_args: None | list[str]
"""
try:
cls._ceph_cmd(['dashboard', 'ac-user-show', username])
cls._ceph_cmd(['dashboard', 'ac-user-delete', username])
except CommandFailedError as ex:
if ex.exitstatus != 2:
raise ex
user_create_args = [
'dashboard', 'ac-user-create', username
]
if force_password:
user_create_args.append('--force-password')
if cmd_args:
user_create_args.extend(cmd_args)
cls._ceph_cmd_with_secret(user_create_args, password)
if roles:
set_roles_args = ['dashboard', 'ac-user-set-roles', username]
for idx, role in enumerate(roles):
if isinstance(role, str):
set_roles_args.append(role)
else:
assert isinstance(role, dict)
rolename = 'test_role_{}'.format(idx)
try:
cls._ceph_cmd(['dashboard', 'ac-role-show', rolename])
cls._ceph_cmd(['dashboard', 'ac-role-delete', rolename])
except CommandFailedError as ex:
if ex.exitstatus != 2:
raise ex
cls._ceph_cmd(['dashboard', 'ac-role-create', rolename])
for mod, perms in role.items():
args = ['dashboard', 'ac-role-add-scope-perms', rolename, mod]
args.extend(perms)
cls._ceph_cmd(args)
set_roles_args.append(rolename)
cls._ceph_cmd(set_roles_args) | [
"def",
"create_user",
"(",
"cls",
",",
"username",
",",
"password",
",",
"roles",
"=",
"None",
",",
"force_password",
"=",
"True",
",",
"cmd_args",
"=",
"None",
")",
":",
"# pylint: disable=too-many-arguments",
"try",
":",
"cls",
".",
"_ceph_cmd",
"(",
"[",
... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/mgr/dashboard/helper.py#L93-L145 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/joblib/joblib/hashing.py | python | hash | (obj, hash_name='md5', coerce_mmap=False) | return hasher.hash(obj) | Quick calculation of a hash to identify uniquely Python objects
containing numpy arrays.
Parameters
-----------
hash_name: 'md5' or 'sha1'
Hashing algorithm used. sha1 is supposedly safer, but md5 is
faster.
coerce_mmap: boolean
Make no difference between np.memmap and np.ndarray | Quick calculation of a hash to identify uniquely Python objects
containing numpy arrays. | [
"Quick",
"calculation",
"of",
"a",
"hash",
"to",
"identify",
"uniquely",
"Python",
"objects",
"containing",
"numpy",
"arrays",
"."
] | def hash(obj, hash_name='md5', coerce_mmap=False):
""" Quick calculation of a hash to identify uniquely Python objects
containing numpy arrays.
Parameters
-----------
hash_name: 'md5' or 'sha1'
Hashing algorithm used. sha1 is supposedly safer, but md5 is
faster.
coerce_mmap: boolean
Make no difference between np.memmap and np.ndarray
"""
valid_hash_names = ('md5', 'sha1')
if hash_name not in valid_hash_names:
raise ValueError("Valid options for 'hash_name' are {}. "
"Got hash_name={!r} instead."
.format(valid_hash_names, hash_name))
if 'numpy' in sys.modules:
hasher = NumpyHasher(hash_name=hash_name, coerce_mmap=coerce_mmap)
else:
hasher = Hasher(hash_name=hash_name)
return hasher.hash(obj) | [
"def",
"hash",
"(",
"obj",
",",
"hash_name",
"=",
"'md5'",
",",
"coerce_mmap",
"=",
"False",
")",
":",
"valid_hash_names",
"=",
"(",
"'md5'",
",",
"'sha1'",
")",
"if",
"hash_name",
"not",
"in",
"valid_hash_names",
":",
"raise",
"ValueError",
"(",
"\"Valid ... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/hashing.py#L244-L266 | |
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | scripts/cpp_lint.py | python | _CppLintState.SetVerboseLevel | (self, level) | return last_verbose_level | Sets the module's verbosity, and returns the previous setting. | Sets the module's verbosity, and returns the previous setting. | [
"Sets",
"the",
"module",
"s",
"verbosity",
"and",
"returns",
"the",
"previous",
"setting",
"."
] | def SetVerboseLevel(self, level):
"""Sets the module's verbosity, and returns the previous setting."""
last_verbose_level = self.verbose_level
self.verbose_level = level
return last_verbose_level | [
"def",
"SetVerboseLevel",
"(",
"self",
",",
"level",
")",
":",
"last_verbose_level",
"=",
"self",
".",
"verbose_level",
"self",
".",
"verbose_level",
"=",
"level",
"return",
"last_verbose_level"
] | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/scripts/cpp_lint.py#L707-L711 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | BucketPointerArgument.GetLogArg | (self) | return "static_cast<const void*>(%s)" % self.name | Overridden from Argument. | Overridden from Argument. | [
"Overridden",
"from",
"Argument",
"."
] | def GetLogArg(self):
"""Overridden from Argument."""
return "static_cast<const void*>(%s)" % self.name | [
"def",
"GetLogArg",
"(",
"self",
")",
":",
"return",
"\"static_cast<const void*>(%s)\"",
"%",
"self",
".",
"name"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L6134-L6136 | |
nasa/meshNetwork | ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c | python/mesh/generic/slipMsg_li1.py | python | SLIPmsg_Li1.decodeSLIPmsgContents | (self, byteList, pos) | Helper function to strip special SLIP bytes from identified SLIP message.
Args:
byteList: Raw serial data array.
pos: Array position of start of SLIP message in raw serial data. | Helper function to strip special SLIP bytes from identified SLIP message. | [
"Helper",
"function",
"to",
"strip",
"special",
"SLIP",
"bytes",
"from",
"identified",
"SLIP",
"message",
"."
] | def decodeSLIPmsgContents(self, byteList, pos):
"""Helper function to strip special SLIP bytes from identified SLIP message.
Args:
byteList: Raw serial data array.
pos: Array position of start of SLIP message in raw serial data.
"""
while pos < len(byteList) and len(self.msg) < self.msgMaxLength:
byte = byteList[pos:pos+1]
if byte != SLIP_END: # parse msg contents
if byte == SLIP_ESC and (pos + 1) < len(byteList): # SLIP ESC character found (second condition guards against overflowing msg buffer)
byte = byteList[pos+1:pos+2]
if byte == SLIP_ESC_END: # replace ESC sequence with END character
self.msg = self.msg + SLIP_END
elif byte == SLIP_ESC_END_TDMA: # replace ESC sequence with TDMA END character
self.msg = self.msg + SLIP_END_TDMA
elif byte == SLIP_ESC_LI1_BAD_BYTE1:
self.msg = self.msg + LI1_BAD_BYTE1
elif byte == SLIP_ESC_LI1_BAD_BYTE2:
self.msg = self.msg + LI1_BAD_BYTE2
elif byte == SLIP_ESC_LI1_BAD_BYTE3:
self.msg = self.msg + LI1_BAD_BYTE3
elif byte == SLIP_ESC_LI1_BAD_BYTE4:
self.msg = self.msg + LI1_BAD_BYTE4
else: # replace ESC sequence with ESC character
self.msg = self.msg + SLIP_ESC
pos += 1
else: # insert raw SLIP msg byte into buffer
self.msg = self.msg + byte
self.msgLength += 1
else: # message end found
if(self.msgLength > 0): # guards against falsely identifying a message of zero length between two END characters
self.msgEnd = pos
break
#return msgBuffer
pos += 1 | [
"def",
"decodeSLIPmsgContents",
"(",
"self",
",",
"byteList",
",",
"pos",
")",
":",
"while",
"pos",
"<",
"len",
"(",
"byteList",
")",
"and",
"len",
"(",
"self",
".",
"msg",
")",
"<",
"self",
".",
"msgMaxLength",
":",
"byte",
"=",
"byteList",
"[",
"po... | https://github.com/nasa/meshNetwork/blob/ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c/python/mesh/generic/slipMsg_li1.py#L70-L107 | ||
fastmachinelearning/hls4ml | 58d761006250deed721d85fefea91201708f2165 | hls4ml/model/graph.py | python | ModelGraph.compile | (self) | Compile the generated project and link the library into current environment.
Users should call this function if they want to use `predict` functionality for simulation. | Compile the generated project and link the library into current environment. | [
"Compile",
"the",
"generated",
"project",
"and",
"link",
"the",
"library",
"into",
"current",
"environment",
"."
] | def compile(self):
"""Compile the generated project and link the library into current environment.
Users should call this function if they want to use `predict` functionality for simulation.
"""
self.write()
lib_name = self.config.backend.compile(self)
if self._top_function_lib is not None:
if platform.system() == "Linux":
dlclose_func = ctypes.CDLL('libdl.so').dlclose
elif platform.system() == "Darwin":
dlclose_func = ctypes.CDLL('libc.dylib').dlclose
dlclose_func.argtypes = [ctypes.c_void_p]
dlclose_func.restype = ctypes.c_int
dlclose_func(self._top_function_lib._handle)
self._top_function_lib = ctypes.cdll.LoadLibrary(lib_name) | [
"def",
"compile",
"(",
"self",
")",
":",
"self",
".",
"write",
"(",
")",
"lib_name",
"=",
"self",
".",
"config",
".",
"backend",
".",
"compile",
"(",
"self",
")",
"if",
"self",
".",
"_top_function_lib",
"is",
"not",
"None",
":",
"if",
"platform",
"."... | https://github.com/fastmachinelearning/hls4ml/blob/58d761006250deed721d85fefea91201708f2165/hls4ml/model/graph.py#L561-L579 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetPrintMagnification | (*args, **kwargs) | return _stc.StyledTextCtrl_GetPrintMagnification(*args, **kwargs) | GetPrintMagnification(self) -> int
Returns the print magnification. | GetPrintMagnification(self) -> int | [
"GetPrintMagnification",
"(",
"self",
")",
"-",
">",
"int"
] | def GetPrintMagnification(*args, **kwargs):
"""
GetPrintMagnification(self) -> int
Returns the print magnification.
"""
return _stc.StyledTextCtrl_GetPrintMagnification(*args, **kwargs) | [
"def",
"GetPrintMagnification",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetPrintMagnification",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3472-L3478 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/utils.py | python | invoke_progress_callbacks | (callbacks, bytes_transferred) | Calls all progress callbacks
:param callbacks: A list of progress callbacks to invoke
:param bytes_transferred: The number of bytes transferred. This is passed
to the callbacks. If no bytes were transferred the callbacks will not
be invoked because no progress was achieved. It is also possible
to receive a negative amount which comes from retrying a transfer
request. | Calls all progress callbacks | [
"Calls",
"all",
"progress",
"callbacks"
] | def invoke_progress_callbacks(callbacks, bytes_transferred):
"""Calls all progress callbacks
:param callbacks: A list of progress callbacks to invoke
:param bytes_transferred: The number of bytes transferred. This is passed
to the callbacks. If no bytes were transferred the callbacks will not
be invoked because no progress was achieved. It is also possible
to receive a negative amount which comes from retrying a transfer
request.
"""
# Only invoke the callbacks if bytes were actually transferred.
if bytes_transferred:
for callback in callbacks:
callback(bytes_transferred=bytes_transferred) | [
"def",
"invoke_progress_callbacks",
"(",
"callbacks",
",",
"bytes_transferred",
")",
":",
"# Only invoke the callbacks if bytes were actually transferred.",
"if",
"bytes_transferred",
":",
"for",
"callback",
"in",
"callbacks",
":",
"callback",
"(",
"bytes_transferred",
"=",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/utils.py#L128-L141 | ||
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/win/Source/bin/jinja2/filters.py | python | do_random | (environment, seq) | Return a random item from the sequence. | Return a random item from the sequence. | [
"Return",
"a",
"random",
"item",
"from",
"the",
"sequence",
"."
] | def do_random(environment, seq):
"""Return a random item from the sequence."""
try:
return choice(seq)
except IndexError:
return environment.undefined('No random item, sequence was empty.') | [
"def",
"do_random",
"(",
"environment",
",",
"seq",
")",
":",
"try",
":",
"return",
"choice",
"(",
"seq",
")",
"except",
"IndexError",
":",
"return",
"environment",
".",
"undefined",
"(",
"'No random item, sequence was empty.'",
")"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/filters.py#L277-L282 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | ctc_batch_cost | (y_true, y_pred, input_length, label_length) | return array_ops.expand_dims(
ctc.ctc_loss(
inputs=y_pred, labels=sparse_labels, sequence_length=input_length), 1) | Runs CTC loss algorithm on each batch element.
Args:
y_true: tensor `(samples, max_string_length)`
containing the truth labels.
y_pred: tensor `(samples, time_steps, num_categories)`
containing the prediction, or output of the softmax.
input_length: tensor `(samples, 1)` containing the sequence length for
each batch item in `y_pred`.
label_length: tensor `(samples, 1)` containing the sequence length for
each batch item in `y_true`.
Returns:
Tensor with shape (samples,1) containing the
CTC loss of each element. | Runs CTC loss algorithm on each batch element. | [
"Runs",
"CTC",
"loss",
"algorithm",
"on",
"each",
"batch",
"element",
"."
] | def ctc_batch_cost(y_true, y_pred, input_length, label_length):
"""Runs CTC loss algorithm on each batch element.
Args:
y_true: tensor `(samples, max_string_length)`
containing the truth labels.
y_pred: tensor `(samples, time_steps, num_categories)`
containing the prediction, or output of the softmax.
input_length: tensor `(samples, 1)` containing the sequence length for
each batch item in `y_pred`.
label_length: tensor `(samples, 1)` containing the sequence length for
each batch item in `y_true`.
Returns:
Tensor with shape (samples,1) containing the
CTC loss of each element.
"""
label_length = math_ops.cast(
array_ops.squeeze(label_length, axis=-1), dtypes_module.int32)
input_length = math_ops.cast(
array_ops.squeeze(input_length, axis=-1), dtypes_module.int32)
sparse_labels = math_ops.cast(
ctc_label_dense_to_sparse(y_true, label_length), dtypes_module.int32)
y_pred = math_ops.log(array_ops.transpose(y_pred, perm=[1, 0, 2]) + epsilon())
return array_ops.expand_dims(
ctc.ctc_loss(
inputs=y_pred, labels=sparse_labels, sequence_length=input_length), 1) | [
"def",
"ctc_batch_cost",
"(",
"y_true",
",",
"y_pred",
",",
"input_length",
",",
"label_length",
")",
":",
"label_length",
"=",
"math_ops",
".",
"cast",
"(",
"array_ops",
".",
"squeeze",
"(",
"label_length",
",",
"axis",
"=",
"-",
"1",
")",
",",
"dtypes_mo... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L6241-L6269 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/not_in_impl.py | python | _tensor_not_in_tuple | (x, y) | return not compile_utils.tensor_in_sequence(x, y) | Determine if a tensor not in a tuple.
Args:
x: Tensor
y: Tuple
Returns:
bool, if x not in y return true, x in y return false. | Determine if a tensor not in a tuple. | [
"Determine",
"if",
"a",
"tensor",
"not",
"in",
"a",
"tuple",
"."
] | def _tensor_not_in_tuple(x, y):
"""
Determine if a tensor not in a tuple.
Args:
x: Tensor
y: Tuple
Returns:
bool, if x not in y return true, x in y return false.
"""
return not compile_utils.tensor_in_sequence(x, y) | [
"def",
"_tensor_not_in_tuple",
"(",
"x",
",",
"y",
")",
":",
"return",
"not",
"compile_utils",
".",
"tensor_in_sequence",
"(",
"x",
",",
"y",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/not_in_impl.py#L121-L132 | |
google/skia | 82d65d0487bd72f5f7332d002429ec2dc61d2463 | infra/bots/recipes/perf_skottietrace.py | python | parse_trace | (trace_json, lottie_filename, api) | return output | parse_trace parses the specified trace JSON.
Parses the trace JSON and calculates the time of a single frame. Frame time is
considered the same as seek time + render time.
Note: The first seek is ignored because it is a constructor call.
A dictionary is returned that has the following structure:
{
'frame_max_us': 100,
'frame_min_us': 90,
'frame_avg_us': 95,
} | parse_trace parses the specified trace JSON. | [
"parse_trace",
"parses",
"the",
"specified",
"trace",
"JSON",
"."
] | def parse_trace(trace_json, lottie_filename, api):
"""parse_trace parses the specified trace JSON.
Parses the trace JSON and calculates the time of a single frame. Frame time is
considered the same as seek time + render time.
Note: The first seek is ignored because it is a constructor call.
A dictionary is returned that has the following structure:
{
'frame_max_us': 100,
'frame_min_us': 90,
'frame_avg_us': 95,
}
"""
step_result = api.run(
api.python.inline,
'parse %s trace' % lottie_filename,
program="""
import json
import sys
trace_output = sys.argv[1]
trace_json = json.loads(trace_output)
lottie_filename = sys.argv[2]
output_json_file = sys.argv[3]
perf_results = {}
frame_max = 0
frame_min = 0
frame_cumulative = 0
current_frame_duration = 0
total_frames = 0
frame_start = False
for trace in trace_json:
if '%s' in trace['name']:
if frame_start:
raise Exception('We got consecutive Animation::seek without a ' +
'render. Something is wrong.')
frame_start = True
current_frame_duration = trace['dur']
elif '%s' in trace['name']:
if not frame_start:
raise Exception('We got an Animation::render without a seek first. ' +
'Something is wrong.')
current_frame_duration += trace['dur']
frame_start = False
total_frames += 1
frame_max = max(frame_max, current_frame_duration)
frame_min = (min(frame_min, current_frame_duration)
if frame_min else current_frame_duration)
frame_cumulative += current_frame_duration
expected_dm_frames = %d
if total_frames != expected_dm_frames:
raise Exception(
'Got ' + str(total_frames) + ' frames instead of ' +
str(expected_dm_frames))
perf_results['frame_max_us'] = frame_max
perf_results['frame_min_us'] = frame_min
perf_results['frame_avg_us'] = frame_cumulative/total_frames
# Write perf_results to the output json.
with open(output_json_file, 'w') as f:
f.write(json.dumps(perf_results))
""" % (SEEK_TRACE_NAME, RENDER_TRACE_NAME, EXPECTED_DM_FRAMES),
args=[trace_json, lottie_filename, api.json.output()])
# Sanitize float outputs to 2 precision points.
output = dict(step_result.json.output)
output['frame_max_us'] = float("%.2f" % output['frame_max_us'])
output['frame_min_us'] = float("%.2f" % output['frame_min_us'])
output['frame_avg_us'] = float("%.2f" % output['frame_avg_us'])
return output | [
"def",
"parse_trace",
"(",
"trace_json",
",",
"lottie_filename",
",",
"api",
")",
":",
"step_result",
"=",
"api",
".",
"run",
"(",
"api",
".",
"python",
".",
"inline",
",",
"'parse %s trace'",
"%",
"lottie_filename",
",",
"program",
"=",
"\"\"\"\n import json... | https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/recipes/perf_skottietrace.py#L143-L216 | |
dartsim/dart | 495c82120c836005f2d136d4a50c8cc997fb879b | tools/cpplint.py | python | FileInfo.NoExtension | (self) | return '/'.join(self.Split()[0:2]) | File has no source file extension. | File has no source file extension. | [
"File",
"has",
"no",
"source",
"file",
"extension",
"."
] | def NoExtension(self):
"""File has no source file extension."""
return '/'.join(self.Split()[0:2]) | [
"def",
"NoExtension",
"(",
"self",
")",
":",
"return",
"'/'",
".",
"join",
"(",
"self",
".",
"Split",
"(",
")",
"[",
"0",
":",
"2",
"]",
")"
] | https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/tools/cpplint.py#L929-L931 | |
jbehley/point_labeler | bf22e6f255fe5c9f01979d2d670d0ac543ae6460 | scripts/io_utils.py | python | write_labels | (filename, labels) | write labels in given file. | write labels in given file. | [
"write",
"labels",
"in",
"given",
"file",
"."
] | def write_labels(filename, labels):
""" write labels in given file. """
arr = [struct.pack('<I', label) for label in labels]
contents = bytes()
for a in arr:
contents += a
with open(filename, "bw") as f:
f.write(contents) | [
"def",
"write_labels",
"(",
"filename",
",",
"labels",
")",
":",
"arr",
"=",
"[",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"label",
")",
"for",
"label",
"in",
"labels",
"]",
"contents",
"=",
"bytes",
"(",
")",
"for",
"a",
"in",
"arr",
":",
"content... | https://github.com/jbehley/point_labeler/blob/bf22e6f255fe5c9f01979d2d670d0ac543ae6460/scripts/io_utils.py#L20-L28 | ||
google/clif | cab24d6a105609a65c95a36a1712ae3c20c7b5df | clif/python/proto.py | python | _CppName | (desc) | return '::'+desc.fqname.replace('.', '::') | Return the fully qualified C++ name of the entity in |desc|. | Return the fully qualified C++ name of the entity in |desc|. | [
"Return",
"the",
"fully",
"qualified",
"C",
"++",
"name",
"of",
"the",
"entity",
"in",
"|desc|",
"."
] | def _CppName(desc):
"""Return the fully qualified C++ name of the entity in |desc|."""
return '::'+desc.fqname.replace('.', '::') | [
"def",
"_CppName",
"(",
"desc",
")",
":",
"return",
"'::'",
"+",
"desc",
".",
"fqname",
".",
"replace",
"(",
"'.'",
",",
"'::'",
")"
] | https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/proto.py#L60-L62 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/calendar.py | python | Calendar.itermonthdays | (self, year, month) | Like itermonthdates(), but will yield day numbers. For days outside
the specified month the day number is 0. | Like itermonthdates(), but will yield day numbers. For days outside
the specified month the day number is 0. | [
"Like",
"itermonthdates",
"()",
"but",
"will",
"yield",
"day",
"numbers",
".",
"For",
"days",
"outside",
"the",
"specified",
"month",
"the",
"day",
"number",
"is",
"0",
"."
] | def itermonthdays(self, year, month):
"""
Like itermonthdates(), but will yield day numbers. For days outside
the specified month the day number is 0.
"""
for date in self.itermonthdates(year, month):
if date.month != month:
yield 0
else:
yield date.day | [
"def",
"itermonthdays",
"(",
"self",
",",
"year",
",",
"month",
")",
":",
"for",
"date",
"in",
"self",
".",
"itermonthdates",
"(",
"year",
",",
"month",
")",
":",
"if",
"date",
".",
"month",
"!=",
"month",
":",
"yield",
"0",
"else",
":",
"yield",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/calendar.py#L183-L192 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/git_util.py | python | get_url | (path = '.') | Returns the origin url for the specified path. | Returns the origin url for the specified path. | [
"Returns",
"the",
"origin",
"url",
"for",
"the",
"specified",
"path",
"."
] | def get_url(path = '.'):
""" Returns the origin url for the specified path. """
if is_ue_fork(path):
return read_ue_fork_file(path)['url']
else:
cmd = "%s config --get remote.origin.url" % git_exe
result = exec_cmd(cmd, path)
if result['out'] != '':
return result['out'].strip()
return 'Unknown' | [
"def",
"get_url",
"(",
"path",
"=",
"'.'",
")",
":",
"if",
"is_ue_fork",
"(",
"path",
")",
":",
"return",
"read_ue_fork_file",
"(",
"path",
")",
"[",
"'url'",
"]",
"else",
":",
"cmd",
"=",
"\"%s config --get remote.origin.url\"",
"%",
"git_exe",
"result",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/git_util.py#L46-L55 | ||
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/SU2/util/ordered_dict.py | python | OrderedDict.__delitem__ | (self, key, dict_delitem=dict.__delitem__) | od.__delitem__(y) <==> del od[y] | od.__delitem__(y) <==> del od[y] | [
"od",
".",
"__delitem__",
"(",
"y",
")",
"<",
"==",
">",
"del",
"od",
"[",
"y",
"]"
] | def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is
# then removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev | [
"def",
"__delitem__",
"(",
"self",
",",
"key",
",",
"dict_delitem",
"=",
"dict",
".",
"__delitem__",
")",
":",
"# Deleting an existing item uses self.__map to find the link which is",
"# then removed by updating the links in the predecessor and successor nodes.",
"dict_delitem",
"(... | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/util/ordered_dict.py#L60-L67 | ||
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/MSVSUtil.py | python | InsertLargePdbShims | (target_list, target_dicts, vars) | return (target_list, target_dicts) | Insert a shim target that forces the linker to use 4KB pagesize PDBs.
This is a workaround for targets with PDBs greater than 1GB in size, the
limit for the 1KB pagesize PDBs created by the linker by default.
Arguments:
target_list: List of target pairs: 'base/base.gyp:base'.
target_dicts: Dict of target properties keyed on target pair.
vars: A dictionary of common GYP variables with generator-specific values.
Returns:
Tuple of the shimmed version of the inputs. | Insert a shim target that forces the linker to use 4KB pagesize PDBs. | [
"Insert",
"a",
"shim",
"target",
"that",
"forces",
"the",
"linker",
"to",
"use",
"4KB",
"pagesize",
"PDBs",
"."
] | def InsertLargePdbShims(target_list, target_dicts, vars):
"""Insert a shim target that forces the linker to use 4KB pagesize PDBs.
This is a workaround for targets with PDBs greater than 1GB in size, the
limit for the 1KB pagesize PDBs created by the linker by default.
Arguments:
target_list: List of target pairs: 'base/base.gyp:base'.
target_dicts: Dict of target properties keyed on target pair.
vars: A dictionary of common GYP variables with generator-specific values.
Returns:
Tuple of the shimmed version of the inputs.
"""
# Determine which targets need shimming.
targets_to_shim = []
for t in target_dicts:
target_dict = target_dicts[t]
# We only want to shim targets that have msvs_large_pdb enabled.
if not int(target_dict.get('msvs_large_pdb', 0)):
continue
# This is intended for executable, shared_library and loadable_module
# targets where every configuration is set up to produce a PDB output.
# If any of these conditions is not true then the shim logic will fail
# below.
targets_to_shim.append(t)
large_pdb_shim_cc = _GetLargePdbShimCcPath()
for t in targets_to_shim:
target_dict = target_dicts[t]
target_name = target_dict.get('target_name')
base_dict = _DeepCopySomeKeys(target_dict,
['configurations', 'default_configuration', 'toolset'])
# This is the dict for copying the source file (part of the GYP tree)
# to the intermediate directory of the project. This is necessary because
# we can't always build a relative path to the shim source file (on Windows
# GYP and the project may be on different drives), and Ninja hates absolute
# paths (it ends up generating the .obj and .obj.d alongside the source
# file, polluting GYPs tree).
copy_suffix = 'large_pdb_copy'
copy_target_name = target_name + '_' + copy_suffix
full_copy_target_name = _SuffixName(t, copy_suffix)
shim_cc_basename = os.path.basename(large_pdb_shim_cc)
shim_cc_dir = vars['SHARED_INTERMEDIATE_DIR'] + '/' + copy_target_name
shim_cc_path = shim_cc_dir + '/' + shim_cc_basename
copy_dict = copy.deepcopy(base_dict)
copy_dict['target_name'] = copy_target_name
copy_dict['type'] = 'none'
copy_dict['sources'] = [ large_pdb_shim_cc ]
copy_dict['copies'] = [{
'destination': shim_cc_dir,
'files': [ large_pdb_shim_cc ]
}]
# This is the dict for the PDB generating shim target. It depends on the
# copy target.
shim_suffix = 'large_pdb_shim'
shim_target_name = target_name + '_' + shim_suffix
full_shim_target_name = _SuffixName(t, shim_suffix)
shim_dict = copy.deepcopy(base_dict)
shim_dict['target_name'] = shim_target_name
shim_dict['type'] = 'static_library'
shim_dict['sources'] = [ shim_cc_path ]
shim_dict['dependencies'] = [ full_copy_target_name ]
# Set up the shim to output its PDB to the same location as the final linker
# target.
for config_name, config in shim_dict.get('configurations').iteritems():
pdb_path = _GetPdbPath(target_dict, config_name, vars)
# A few keys that we don't want to propagate.
for key in ['msvs_precompiled_header', 'msvs_precompiled_source', 'test']:
config.pop(key, None)
msvs = config.setdefault('msvs_settings', {})
# Update the compiler directives in the shim target.
compiler = msvs.setdefault('VCCLCompilerTool', {})
compiler['DebugInformationFormat'] = '3'
compiler['ProgramDataBaseFileName'] = pdb_path
# Set the explicit PDB path in the appropriate configuration of the
# original target.
config = target_dict['configurations'][config_name]
msvs = config.setdefault('msvs_settings', {})
linker = msvs.setdefault('VCLinkerTool', {})
linker['GenerateDebugInformation'] = 'true'
linker['ProgramDatabaseFile'] = pdb_path
# Add the new targets. They must go to the beginning of the list so that
# the dependency generation works as expected in ninja.
target_list.insert(0, full_copy_target_name)
target_list.insert(0, full_shim_target_name)
target_dicts[full_copy_target_name] = copy_dict
target_dicts[full_shim_target_name] = shim_dict
# Update the original target to depend on the shim target.
target_dict.setdefault('dependencies', []).append(full_shim_target_name)
return (target_list, target_dicts) | [
"def",
"InsertLargePdbShims",
"(",
"target_list",
",",
"target_dicts",
",",
"vars",
")",
":",
"# Determine which targets need shimming.",
"targets_to_shim",
"=",
"[",
"]",
"for",
"t",
"in",
"target_dicts",
":",
"target_dict",
"=",
"target_dicts",
"[",
"t",
"]",
"#... | 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/MSVSUtil.py#L168-L270 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xpathParserContext.xpathModValues | (self) | Implement the mod operation on XPath objects: @arg1 / @arg2
The numeric operators convert their operands to numbers as
if by calling the number function. | Implement the mod operation on XPath objects: | [
"Implement",
"the",
"mod",
"operation",
"on",
"XPath",
"objects",
":"
] | def xpathModValues(self):
"""Implement the mod operation on XPath objects: @arg1 / @arg2
The numeric operators convert their operands to numbers as
if by calling the number function. """
libxml2mod.xmlXPathModValues(self._o) | [
"def",
"xpathModValues",
"(",
"self",
")",
":",
"libxml2mod",
".",
"xmlXPathModValues",
"(",
"self",
".",
"_o",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6787-L6791 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/utils/check_cfc/check_cfc.py | python | replace_output_file | (args, new_name) | return args | Replaces the specified name of an output file with the specified name.
Assumes that the output file name is specified in the command line args. | Replaces the specified name of an output file with the specified name.
Assumes that the output file name is specified in the command line args. | [
"Replaces",
"the",
"specified",
"name",
"of",
"an",
"output",
"file",
"with",
"the",
"specified",
"name",
".",
"Assumes",
"that",
"the",
"output",
"file",
"name",
"is",
"specified",
"in",
"the",
"command",
"line",
"args",
"."
] | def replace_output_file(args, new_name):
"""Replaces the specified name of an output file with the specified name.
Assumes that the output file name is specified in the command line args."""
replaceidx = None
attached = False
for idx, val in enumerate(args):
if val == '-o':
replaceidx = idx + 1
attached = False
elif val.startswith('-o'):
replaceidx = idx
attached = True
if replaceidx is None:
raise Exception
replacement = new_name
if attached == True:
replacement = '-o' + new_name
args[replaceidx] = replacement
return args | [
"def",
"replace_output_file",
"(",
"args",
",",
"new_name",
")",
":",
"replaceidx",
"=",
"None",
"attached",
"=",
"False",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"val",
"==",
"'-o'",
":",
"replaceidx",
"=",
"idx",
"+"... | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/utils/check_cfc/check_cfc.py#L151-L170 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiNotebook.GetPage | (*args, **kwargs) | return _aui.AuiNotebook_GetPage(*args, **kwargs) | GetPage(self, size_t pageIdx) -> Window | GetPage(self, size_t pageIdx) -> Window | [
"GetPage",
"(",
"self",
"size_t",
"pageIdx",
")",
"-",
">",
"Window"
] | def GetPage(*args, **kwargs):
"""GetPage(self, size_t pageIdx) -> Window"""
return _aui.AuiNotebook_GetPage(*args, **kwargs) | [
"def",
"GetPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiNotebook_GetPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1321-L1323 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Canvas.tag_bind | (self, tagOrId, sequence=None, func=None, add=None) | return self._bind((self._w, 'bind', tagOrId),
sequence, func, add) | Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
An additional boolean parameter ADD specifies whether FUNC will be
called additionally to the other bound function or whether it will
replace the previous function. See bind for the return value. | Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. | [
"Bind",
"to",
"all",
"items",
"with",
"TAGORID",
"at",
"event",
"SEQUENCE",
"a",
"call",
"to",
"function",
"FUNC",
"."
] | def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
"""Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
An additional boolean parameter ADD specifies whether FUNC will be
called additionally to the other bound function or whether it will
replace the previous function. See bind for the return value."""
return self._bind((self._w, 'bind', tagOrId),
sequence, func, add) | [
"def",
"tag_bind",
"(",
"self",
",",
"tagOrId",
",",
"sequence",
"=",
"None",
",",
"func",
"=",
"None",
",",
"add",
"=",
"None",
")",
":",
"return",
"self",
".",
"_bind",
"(",
"(",
"self",
".",
"_w",
",",
"'bind'",
",",
"tagOrId",
")",
",",
"sequ... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2217-L2224 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/internetcontent/nv_python_libs/bliptv/bliptv_api.py | python | Videos.getVideos | (self, dir_dict, dictionaries) | return dictionaries | Parse a list made of categories and retrieve video meta data
return a dictionary of directory names and categories video meta data | Parse a list made of categories and retrieve video meta data
return a dictionary of directory names and categories video meta data | [
"Parse",
"a",
"list",
"made",
"of",
"categories",
"and",
"retrieve",
"video",
"meta",
"data",
"return",
"a",
"dictionary",
"of",
"directory",
"names",
"and",
"categories",
"video",
"meta",
"data"
] | def getVideos(self, dir_dict, dictionaries):
'''Parse a list made of categories and retrieve video meta data
return a dictionary of directory names and categories video meta data
'''
for sets in dir_dict:
if not isinstance(sets[1], list):
if sets[0] != '': # Add the nested dictionaries display name
dictionaries.append([self.massageDescription(sets[0]), self.channel_icon])
else:
dictionaries.append(['', '']) # Add the nested dictionary indicator
continue
temp_dictionary = []
for self.feed in sets[1]:
if self.categories:
self.tree_customize[self.tree_key]['__default__']['categories_id'] = self.feed_names['categories'][sets[0]]
self.tree_customize[self.tree_key]['__default__']['sort'] = self.feed
if '__all__' in self.config['urls']['tree.view'][self.tree_key]:
URL = self.config['urls']['tree.view'][self.tree_key]['__all__']
else:
URL = self.config['urls']['tree.view'][self.tree_key][self.feed]
temp_dictionary = self.config['item_parser'][URL[1]](self.makeURL(URL[0]), temp_dictionary)
if len(temp_dictionary):
if len(sets[0]): # Add the nested dictionaries display name
dictionaries.append([self.massageDescription(sets[0]), self.channel_icon])
for element in temp_dictionary:
dictionaries.append(element)
if len(sets[0]):
dictionaries.append(['', '']) # Add the nested dictionary indicator
return dictionaries | [
"def",
"getVideos",
"(",
"self",
",",
"dir_dict",
",",
"dictionaries",
")",
":",
"for",
"sets",
"in",
"dir_dict",
":",
"if",
"not",
"isinstance",
"(",
"sets",
"[",
"1",
"]",
",",
"list",
")",
":",
"if",
"sets",
"[",
"0",
"]",
"!=",
"''",
":",
"# ... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/bliptv/bliptv_api.py#L681-L709 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/math_grad.py | python | _AddNGrad | (op, grad) | return [grad] * len(op.inputs) | Copies the gradient to all inputs. | Copies the gradient to all inputs. | [
"Copies",
"the",
"gradient",
"to",
"all",
"inputs",
"."
] | def _AddNGrad(op, grad):
"""Copies the gradient to all inputs."""
# Not broadcasting.
return [grad] * len(op.inputs) | [
"def",
"_AddNGrad",
"(",
"op",
",",
"grad",
")",
":",
"# Not broadcasting.",
"return",
"[",
"grad",
"]",
"*",
"len",
"(",
"op",
".",
"inputs",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_grad.py#L697-L700 | |
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.addProduct | (self, molecule) | return self.dispatcher._checkResult(
Indigo._lib.indigoAddProduct(self.id, molecule.id)
) | Reaction method adds the given molecule copy to products
Args:
molecule (IndigoObject): molecule to be added
Returns:
int: 1 if the molecule was added correctly | Reaction method adds the given molecule copy to products | [
"Reaction",
"method",
"adds",
"the",
"given",
"molecule",
"copy",
"to",
"products"
] | def addProduct(self, molecule):
"""Reaction method adds the given molecule copy to products
Args:
molecule (IndigoObject): molecule to be added
Returns:
int: 1 if the molecule was added correctly
"""
self.dispatcher._setSessionId()
return self.dispatcher._checkResult(
Indigo._lib.indigoAddProduct(self.id, molecule.id)
) | [
"def",
"addProduct",
"(",
"self",
",",
"molecule",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"dispatcher",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoAddProduct",
"(",
"self",
".",
"id",
... | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L393-L405 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap.py | python | _resolve_name | (name, package, level) | return '{}.{}'.format(base, name) if name else base | Resolve a relative module name to an absolute one. | Resolve a relative module name to an absolute one. | [
"Resolve",
"a",
"relative",
"module",
"name",
"to",
"an",
"absolute",
"one",
"."
] | def _resolve_name(name, package, level):
"""Resolve a relative module name to an absolute one."""
bits = package.rsplit('.', level - 1)
if len(bits) < level:
raise ValueError('attempted relative import beyond top-level package')
base = bits[0]
return '{}.{}'.format(base, name) if name else base | [
"def",
"_resolve_name",
"(",
"name",
",",
"package",
",",
"level",
")",
":",
"bits",
"=",
"package",
".",
"rsplit",
"(",
"'.'",
",",
"level",
"-",
"1",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"level",
":",
"raise",
"ValueError",
"(",
"'attempted rel... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap.py#L864-L870 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | SimRobotSensor.setSetting | (self, name, val) | return _robotsim.SimRobotSensor_setSetting(self, name, val) | setSetting(SimRobotSensor self, std::string const & name, std::string const & val)
Sets the value of the named setting (you will need to manually cast an
int/float/etc to a str) | setSetting(SimRobotSensor self, std::string const & name, std::string const & val) | [
"setSetting",
"(",
"SimRobotSensor",
"self",
"std",
"::",
"string",
"const",
"&",
"name",
"std",
"::",
"string",
"const",
"&",
"val",
")"
] | def setSetting(self, name, val):
"""
setSetting(SimRobotSensor self, std::string const & name, std::string const & val)
Sets the value of the named setting (you will need to manually cast an
int/float/etc to a str)
"""
return _robotsim.SimRobotSensor_setSetting(self, name, val) | [
"def",
"setSetting",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"return",
"_robotsim",
".",
"SimRobotSensor_setSetting",
"(",
"self",
",",
"name",
",",
"val",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L7268-L7278 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/PyShell.py | python | ModifiedInterpreter.showsyntaxerror | (self, filename=None) | Extend base class method: Add Colorizing
Color the offending position instead of printing it and pointing at it
with a caret. | Extend base class method: Add Colorizing | [
"Extend",
"base",
"class",
"method",
":",
"Add",
"Colorizing"
] | def showsyntaxerror(self, filename=None):
"""Extend base class method: Add Colorizing
Color the offending position instead of printing it and pointing at it
with a caret.
"""
text = self.tkconsole.text
stuff = self.unpackerror()
if stuff:
msg, lineno, offset, line = stuff
if lineno == 1:
pos = "iomark + %d chars" % (offset-1)
else:
pos = "iomark linestart + %d lines + %d chars" % \
(lineno-1, offset-1)
text.tag_add("ERROR", pos)
text.see(pos)
char = text.get(pos)
if char and char in IDENTCHARS:
text.tag_add("ERROR", pos + " wordstart", pos)
self.tkconsole.resetoutput()
self.write("SyntaxError: %s\n" % str(msg))
else:
self.tkconsole.resetoutput()
InteractiveInterpreter.showsyntaxerror(self, filename)
self.tkconsole.showprompt() | [
"def",
"showsyntaxerror",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"text",
"=",
"self",
".",
"tkconsole",
".",
"text",
"stuff",
"=",
"self",
".",
"unpackerror",
"(",
")",
"if",
"stuff",
":",
"msg",
",",
"lineno",
",",
"offset",
",",
"line... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/PyShell.py#L679-L705 | ||
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | panreas_hnn/hed-globalweight/scripts/cpp_lint.py | python | CheckMakePairUsesDeduction | (filename, clean_lines, linenum, error) | Check that make_pair's template arguments are deduced.
G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
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. | Check that make_pair's template arguments are deduced. | [
"Check",
"that",
"make_pair",
"s",
"template",
"arguments",
"are",
"deduced",
"."
] | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
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]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template arguments from make_pair'
' OR use pair directly OR if appropriate, construct a pair directly') | [
"def",
"CheckMakePairUsesDeduction",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"match",
"=",
"_RE_PATTERN_EXPLICIT_MAKEPAIR",
".",
"search",
"(",
"line",
")",
"i... | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/scripts/cpp_lint.py#L4579-L4597 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | libcxx/utils/libcxx/util.py | python | executeCommand | (command, cwd=None, env=None, input=None, timeout=0) | return out, err, exitCode | Execute command ``command`` (list of arguments or string)
with
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
* Input to the command ``input`` (str), use string to pass
no input.
* Max execution time ``timeout`` (int) seconds. Use 0 for no timeout.
Returns a tuple (out, err, exitCode) where
* ``out`` (str) is the standard output of running the command
* ``err`` (str) is the standard error of running the command
* ``exitCode`` (int) is the exitCode of running the command
If the timeout is hit an ``ExecuteCommandTimeoutException``
is raised. | Execute command ``command`` (list of arguments or string)
with
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
* Input to the command ``input`` (str), use string to pass
no input.
* Max execution time ``timeout`` (int) seconds. Use 0 for no timeout. | [
"Execute",
"command",
"command",
"(",
"list",
"of",
"arguments",
"or",
"string",
")",
"with",
"*",
"working",
"directory",
"cwd",
"(",
"str",
")",
"use",
"None",
"to",
"use",
"the",
"current",
"working",
"directory",
"*",
"environment",
"env",
"(",
"dict",... | def executeCommand(command, cwd=None, env=None, input=None, timeout=0):
"""
Execute command ``command`` (list of arguments or string)
with
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
* Input to the command ``input`` (str), use string to pass
no input.
* Max execution time ``timeout`` (int) seconds. Use 0 for no timeout.
Returns a tuple (out, err, exitCode) where
* ``out`` (str) is the standard output of running the command
* ``err`` (str) is the standard error of running the command
* ``exitCode`` (int) is the exitCode of running the command
If the timeout is hit an ``ExecuteCommandTimeoutException``
is raised.
"""
if input is not None:
input = to_bytes(input)
p = subprocess.Popen(command, cwd=cwd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env, close_fds=kUseCloseFDs)
timerObject = None
hitTimeOut = False
try:
if timeout > 0:
def killProcess():
# We may be invoking a shell so we need to kill the
# process and all its children.
nonlocal hitTimeOut
hitTimeOut = True
killProcessAndChildren(p.pid)
timerObject = threading.Timer(timeout, killProcess)
timerObject.start()
out, err = p.communicate(input=input)
exitCode = p.wait()
finally:
if timerObject != None:
timerObject.cancel()
# Ensure the resulting output is always of string type.
out = convert_string(out)
err = convert_string(err)
if hitTimeOut:
raise ExecuteCommandTimeoutException(
msg='Reached timeout of {} seconds'.format(timeout),
out=out,
err=err,
exitCode=exitCode
)
# Detect Ctrl-C in subprocess.
if exitCode == -signal.SIGINT:
raise KeyboardInterrupt
return out, err, exitCode | [
"def",
"executeCommand",
"(",
"command",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"input",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"if",
"input",
"is",
"not",
"None",
":",
"input",
"=",
"to_bytes",
"(",
"input",
")",
"p",
"... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/libcxx/utils/libcxx/util.py#L178-L240 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PropertyGrid.GetCellTextColour | (*args, **kwargs) | return _propgrid.PropertyGrid_GetCellTextColour(*args, **kwargs) | GetCellTextColour(self) -> Colour | GetCellTextColour(self) -> Colour | [
"GetCellTextColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetCellTextColour(*args, **kwargs):
"""GetCellTextColour(self) -> Colour"""
return _propgrid.PropertyGrid_GetCellTextColour(*args, **kwargs) | [
"def",
"GetCellTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_GetCellTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2067-L2069 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py | python | CGIHTTPRequestHandler.is_cgi | (self) | return False | Test whether self.path corresponds to a CGI script.
Returns True and updates the cgi_info attribute to the tuple
(dir, rest) if self.path requires running a CGI script.
Returns False otherwise.
If any exception is raised, the caller should assume that
self.path was rejected as invalid and act accordingly.
The default implementation tests whether the normalized url
path begins with one of the strings in self.cgi_directories
(and the next character is a '/' or the end of the string). | Test whether self.path corresponds to a CGI script. | [
"Test",
"whether",
"self",
".",
"path",
"corresponds",
"to",
"a",
"CGI",
"script",
"."
] | def is_cgi(self):
"""Test whether self.path corresponds to a CGI script.
Returns True and updates the cgi_info attribute to the tuple
(dir, rest) if self.path requires running a CGI script.
Returns False otherwise.
If any exception is raised, the caller should assume that
self.path was rejected as invalid and act accordingly.
The default implementation tests whether the normalized url
path begins with one of the strings in self.cgi_directories
(and the next character is a '/' or the end of the string).
"""
collapsed_path = _url_collapse_path(self.path)
dir_sep = collapsed_path.find('/', 1)
head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
if head in self.cgi_directories:
self.cgi_info = head, tail
return True
return False | [
"def",
"is_cgi",
"(",
"self",
")",
":",
"collapsed_path",
"=",
"_url_collapse_path",
"(",
"self",
".",
"path",
")",
"dir_sep",
"=",
"collapsed_path",
".",
"find",
"(",
"'/'",
",",
"1",
")",
"head",
",",
"tail",
"=",
"collapsed_path",
"[",
":",
"dir_sep",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py#L992-L1013 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/msvs.py | python | _GetGuidOfProject | (proj_path, spec) | return guid | Get the guid for the project.
Arguments:
proj_path: Path of the vcproj or vcxproj file to generate.
spec: The target dictionary containing the properties of the target.
Returns:
the guid.
Raises:
ValueError: if the specified GUID is invalid. | Get the guid for the project. | [
"Get",
"the",
"guid",
"for",
"the",
"project",
"."
] | def _GetGuidOfProject(proj_path, spec):
"""Get the guid for the project.
Arguments:
proj_path: Path of the vcproj or vcxproj file to generate.
spec: The target dictionary containing the properties of the target.
Returns:
the guid.
Raises:
ValueError: if the specified GUID is invalid.
"""
# Pluck out the default configuration.
default_config = _GetDefaultConfiguration(spec)
# Decide the guid of the project.
guid = default_config.get('msvs_guid')
if guid:
if VALID_MSVS_GUID_CHARS.match(guid) is None:
raise ValueError('Invalid MSVS guid: "%s". Must match regex: "%s".' %
(guid, VALID_MSVS_GUID_CHARS.pattern))
guid = '{%s}' % guid
guid = guid or MSVSNew.MakeGuid(proj_path)
return guid | [
"def",
"_GetGuidOfProject",
"(",
"proj_path",
",",
"spec",
")",
":",
"# Pluck out the default configuration.",
"default_config",
"=",
"_GetDefaultConfiguration",
"(",
"spec",
")",
"# Decide the guid of the project.",
"guid",
"=",
"default_config",
".",
"get",
"(",
"'msvs_... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/msvs.py#L910-L931 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/stats.py | python | hmean | (a, axis=0, dtype=None) | Calculate the harmonic mean along the specified axis.
That is: n / (1/x1 + 1/x2 + ... + 1/xn)
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
axis : int or None, optional
Axis along which the harmonic mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults to the
dtype of `a`, unless `a` has an integer `dtype` with a precision less
than that of the default platform integer. In that case, the default
platform integer is used.
Returns
-------
hmean : ndarray
see `dtype` parameter above
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
gmean : Geometric mean
Notes
-----
The harmonic mean is computed over a single dimension of the input
array, axis=0 by default, or all values in the array if axis=None.
float64 intermediate and return values are used for integer inputs.
Use masked arrays to ignore any non-finite values in the input or that
arise in the calculations such as Not a Number and infinity.
Examples
--------
>>> from scipy.stats import hmean
>>> hmean([1, 4])
1.6000000000000001
>>> hmean([1, 2, 3, 4, 5, 6, 7])
2.6997245179063363 | Calculate the harmonic mean along the specified axis. | [
"Calculate",
"the",
"harmonic",
"mean",
"along",
"the",
"specified",
"axis",
"."
] | def hmean(a, axis=0, dtype=None):
"""
Calculate the harmonic mean along the specified axis.
That is: n / (1/x1 + 1/x2 + ... + 1/xn)
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
axis : int or None, optional
Axis along which the harmonic mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults to the
dtype of `a`, unless `a` has an integer `dtype` with a precision less
than that of the default platform integer. In that case, the default
platform integer is used.
Returns
-------
hmean : ndarray
see `dtype` parameter above
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
gmean : Geometric mean
Notes
-----
The harmonic mean is computed over a single dimension of the input
array, axis=0 by default, or all values in the array if axis=None.
float64 intermediate and return values are used for integer inputs.
Use masked arrays to ignore any non-finite values in the input or that
arise in the calculations such as Not a Number and infinity.
Examples
--------
>>> from scipy.stats import hmean
>>> hmean([1, 4])
1.6000000000000001
>>> hmean([1, 2, 3, 4, 5, 6, 7])
2.6997245179063363
"""
if not isinstance(a, np.ndarray):
a = np.array(a, dtype=dtype)
if np.all(a > 0):
# Harmonic mean only defined if greater than zero
if isinstance(a, np.ma.MaskedArray):
size = a.count(axis)
else:
if axis is None:
a = a.ravel()
size = a.shape[0]
else:
size = a.shape[axis]
return size / np.sum(1.0 / a, axis=axis, dtype=dtype)
else:
raise ValueError("Harmonic mean only defined if all elements greater "
"than zero") | [
"def",
"hmean",
"(",
"a",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"np",
".",
"ndarray",
")",
":",
"a",
"=",
"np",
".",
"array",
"(",
"a",
",",
"dtype",
"=",
"dtype",
")",
"if",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/stats.py#L320-L383 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/beautifulsoup4/bs4/dammit.py | python | EncodingDetector.encodings | (self) | Yield a number of encodings that might work for this markup. | Yield a number of encodings that might work for this markup. | [
"Yield",
"a",
"number",
"of",
"encodings",
"that",
"might",
"work",
"for",
"this",
"markup",
"."
] | def encodings(self):
"""Yield a number of encodings that might work for this markup."""
tried = set()
for e in self.override_encodings:
if self._usable(e, tried):
yield e
# Did the document originally start with a byte-order mark
# that indicated its encoding?
if self._usable(self.sniffed_encoding, tried):
yield self.sniffed_encoding
# Look within the document for an XML or HTML encoding
# declaration.
if self.declared_encoding is None:
self.declared_encoding = self.find_declared_encoding(
self.markup, self.is_html)
if self._usable(self.declared_encoding, tried):
yield self.declared_encoding
# Use third-party character set detection to guess at the
# encoding.
if self.chardet_encoding is None:
self.chardet_encoding = chardet_dammit(self.markup)
if self._usable(self.chardet_encoding, tried):
yield self.chardet_encoding
# As a last-ditch effort, try utf-8 and windows-1252.
for e in ('utf-8', 'windows-1252'):
if self._usable(e, tried):
yield e | [
"def",
"encodings",
"(",
"self",
")",
":",
"tried",
"=",
"set",
"(",
")",
"for",
"e",
"in",
"self",
".",
"override_encodings",
":",
"if",
"self",
".",
"_usable",
"(",
"e",
",",
"tried",
")",
":",
"yield",
"e",
"# Did the document originally start with a by... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/beautifulsoup4/bs4/dammit.py#L233-L263 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/driver.py | python | MemoryPointer.allow_access_to | (self, *agents) | Grant access to given *agents*.
Upon return, only the listed-agents and the owner agent have direct
access to this pointer. | Grant access to given *agents*.
Upon return, only the listed-agents and the owner agent have direct
access to this pointer. | [
"Grant",
"access",
"to",
"given",
"*",
"agents",
"*",
".",
"Upon",
"return",
"only",
"the",
"listed",
"-",
"agents",
"and",
"the",
"owner",
"agent",
"have",
"direct",
"access",
"to",
"this",
"pointer",
"."
] | def allow_access_to(self, *agents):
"""
Grant access to given *agents*.
Upon return, only the listed-agents and the owner agent have direct
access to this pointer.
"""
ct = len(agents)
if ct == 0:
return
agent_array = (ct * drvapi.hsa_agent_t)(*[a._id for a in agents])
hsa.hsa_amd_agents_allow_access(ct, agent_array, None,
self.device_pointer) | [
"def",
"allow_access_to",
"(",
"self",
",",
"*",
"agents",
")",
":",
"ct",
"=",
"len",
"(",
"agents",
")",
"if",
"ct",
"==",
"0",
":",
"return",
"agent_array",
"=",
"(",
"ct",
"*",
"drvapi",
".",
"hsa_agent_t",
")",
"(",
"*",
"[",
"a",
".",
"_id"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/driver.py#L1117-L1128 | ||
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/framework/foundation/stream.py | python | Consumer.consume | (self, value) | Accepts a value.
Args:
value: Any value accepted by this Consumer. | Accepts a value. | [
"Accepts",
"a",
"value",
"."
] | def consume(self, value):
"""Accepts a value.
Args:
value: Any value accepted by this Consumer.
"""
raise NotImplementedError() | [
"def",
"consume",
"(",
"self",
",",
"value",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/foundation/stream.py#L25-L31 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/nanfunctions.py | python | nanstd | (a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue) | return std | Compute the standard deviation along the specified axis, while
ignoring NaNs.
Returns the standard deviation, a measure of the spread of a
distribution, of the non-NaN array elements. The standard deviation is
computed for the flattened array by default, otherwise over the
specified axis.
For all-NaN slices or slices with zero degrees of freedom, NaN is
returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Calculate the standard deviation of the non-NaN values.
axis : {int, tuple of int, None}, optional
Axis or axes along which the standard deviation is computed. The default is
to compute the standard deviation of the flattened array.
dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of
integer type the default is float64, for arrays of float types it
is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type (of the
calculated values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of non-NaN
elements. By default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If this value is anything but the default it is passed through
as-is to the relevant functions of the sub-classes. If these
functions do not have a `keepdims` kwarg, a RuntimeError will
be raised.
Returns
-------
standard_deviation : ndarray, see dtype parameter above.
If `out` is None, return a new array containing the standard
deviation, otherwise return a reference to the output array. If
ddof is >= the number of non-NaN elements in a slice or the slice
contains only NaNs, then the result for that slice is NaN.
See Also
--------
var, mean, std
nanvar, nanmean
ufuncs-output-type
Notes
-----
The standard deviation is the square root of the average of the squared
deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``.
The average squared deviation is normally calculated as
``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is
specified, the divisor ``N - ddof`` is used instead. In standard
statistical practice, ``ddof=1`` provides an unbiased estimator of the
variance of the infinite population. ``ddof=0`` provides a maximum
likelihood estimate of the variance for normally distributed variables.
The standard deviation computed in this function is the square root of
the estimated variance, so even with ``ddof=1``, it will not be an
unbiased estimate of the standard deviation per se.
Note that, for complex numbers, `std` takes the absolute value before
squaring, so that the result is always real and nonnegative.
For floating-point input, the *std* is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for float32 (see example
below). Specifying a higher-accuracy accumulator using the `dtype`
keyword can alleviate this issue.
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanstd(a)
1.247219128924647
>>> np.nanstd(a, axis=0)
array([1., 0.])
>>> np.nanstd(a, axis=1)
array([0., 0.5]) # may vary | Compute the standard deviation along the specified axis, while
ignoring NaNs. | [
"Compute",
"the",
"standard",
"deviation",
"along",
"the",
"specified",
"axis",
"while",
"ignoring",
"NaNs",
"."
] | def nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):
"""
Compute the standard deviation along the specified axis, while
ignoring NaNs.
Returns the standard deviation, a measure of the spread of a
distribution, of the non-NaN array elements. The standard deviation is
computed for the flattened array by default, otherwise over the
specified axis.
For all-NaN slices or slices with zero degrees of freedom, NaN is
returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Calculate the standard deviation of the non-NaN values.
axis : {int, tuple of int, None}, optional
Axis or axes along which the standard deviation is computed. The default is
to compute the standard deviation of the flattened array.
dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of
integer type the default is float64, for arrays of float types it
is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type (of the
calculated values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of non-NaN
elements. By default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If this value is anything but the default it is passed through
as-is to the relevant functions of the sub-classes. If these
functions do not have a `keepdims` kwarg, a RuntimeError will
be raised.
Returns
-------
standard_deviation : ndarray, see dtype parameter above.
If `out` is None, return a new array containing the standard
deviation, otherwise return a reference to the output array. If
ddof is >= the number of non-NaN elements in a slice or the slice
contains only NaNs, then the result for that slice is NaN.
See Also
--------
var, mean, std
nanvar, nanmean
ufuncs-output-type
Notes
-----
The standard deviation is the square root of the average of the squared
deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``.
The average squared deviation is normally calculated as
``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is
specified, the divisor ``N - ddof`` is used instead. In standard
statistical practice, ``ddof=1`` provides an unbiased estimator of the
variance of the infinite population. ``ddof=0`` provides a maximum
likelihood estimate of the variance for normally distributed variables.
The standard deviation computed in this function is the square root of
the estimated variance, so even with ``ddof=1``, it will not be an
unbiased estimate of the standard deviation per se.
Note that, for complex numbers, `std` takes the absolute value before
squaring, so that the result is always real and nonnegative.
For floating-point input, the *std* is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for float32 (see example
below). Specifying a higher-accuracy accumulator using the `dtype`
keyword can alleviate this issue.
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanstd(a)
1.247219128924647
>>> np.nanstd(a, axis=0)
array([1., 0.])
>>> np.nanstd(a, axis=1)
array([0., 0.5]) # may vary
"""
var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
keepdims=keepdims)
if isinstance(var, np.ndarray):
std = np.sqrt(var, out=var)
else:
std = var.dtype.type(np.sqrt(var))
return std | [
"def",
"nanstd",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"ddof",
"=",
"0",
",",
"keepdims",
"=",
"np",
".",
"_NoValue",
")",
":",
"var",
"=",
"nanvar",
"(",
"a",
",",
"axis",
"=",
"axis",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/nanfunctions.py#L1572-L1672 | |
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | bindings/python/clang/cindex.py | python | Diagnostic.format | (self, options=None) | return conf.lib.clang_formatDiagnostic(self, options) | Format this diagnostic for display. The options argument takes
Diagnostic.Display* flags, which can be combined using bitwise OR. If
the options argument is not provided, the default display options will
be used. | Format this diagnostic for display. The options argument takes
Diagnostic.Display* flags, which can be combined using bitwise OR. If
the options argument is not provided, the default display options will
be used. | [
"Format",
"this",
"diagnostic",
"for",
"display",
".",
"The",
"options",
"argument",
"takes",
"Diagnostic",
".",
"Display",
"*",
"flags",
"which",
"can",
"be",
"combined",
"using",
"bitwise",
"OR",
".",
"If",
"the",
"options",
"argument",
"is",
"not",
"provi... | def format(self, options=None):
"""
Format this diagnostic for display. The options argument takes
Diagnostic.Display* flags, which can be combined using bitwise OR. If
the options argument is not provided, the default display options will
be used.
"""
if options is None:
options = conf.lib.clang_defaultDiagnosticDisplayOptions()
if options & ~Diagnostic._FormatOptionsMask:
raise ValueError('Invalid format options')
return conf.lib.clang_formatDiagnostic(self, options) | [
"def",
"format",
"(",
"self",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"conf",
".",
"lib",
".",
"clang_defaultDiagnosticDisplayOptions",
"(",
")",
"if",
"options",
"&",
"~",
"Diagnostic",
".",
"_FormatOptio... | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/bindings/python/clang/cindex.py#L467-L478 | |
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/generator/android.py | python | AndroidMkWriter.NormalizeIncludePaths | (self, include_paths) | return normalized | Normalize include_paths.
Convert absolute paths to relative to the Android top directory.
Args:
include_paths: A list of unprocessed include paths.
Returns:
A list of normalized include paths. | Normalize include_paths.
Convert absolute paths to relative to the Android top directory. | [
"Normalize",
"include_paths",
".",
"Convert",
"absolute",
"paths",
"to",
"relative",
"to",
"the",
"Android",
"top",
"directory",
"."
] | def NormalizeIncludePaths(self, include_paths):
""" Normalize include_paths.
Convert absolute paths to relative to the Android top directory.
Args:
include_paths: A list of unprocessed include paths.
Returns:
A list of normalized include paths.
"""
normalized = []
for path in include_paths:
if path[0] == '/':
path = gyp.common.RelativePath(path, self.android_top_dir)
normalized.append(path)
return normalized | [
"def",
"NormalizeIncludePaths",
"(",
"self",
",",
"include_paths",
")",
":",
"normalized",
"=",
"[",
"]",
"for",
"path",
"in",
"include_paths",
":",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"path",
"=",
"gyp",
".",
"common",
".",
"RelativePath",
... | 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/generator/android.py#L690-L704 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/perf/profile_creators/update_remote_extensions.py | python | _UpdateExtensionsInCloud | (local_extensions_dir, extensions_csv, remote_dir) | Updates set of extensions in Cloud Storage from a CSV of extension ids.
From well-formatted CSV file containing some set of extensions
(extensions_csv), download them, compress into archive, and update
the remote extension archive under REMOTE_DIR in CHROME-PARTNER-TELEMETRY
bucket. This script expects 2nd column of CSV file to contain extension ids.
Args:
local_extensions_dir: directory to download CRX files into.
extension_csv: CSV to pull extension_ids from.
remote_dir: remote directory to put extension archive in cloud storage.
Raises:
Exception if a CRX download fails. | Updates set of extensions in Cloud Storage from a CSV of extension ids. | [
"Updates",
"set",
"of",
"extensions",
"in",
"Cloud",
"Storage",
"from",
"a",
"CSV",
"of",
"extension",
"ids",
"."
] | def _UpdateExtensionsInCloud(local_extensions_dir, extensions_csv, remote_dir):
"""Updates set of extensions in Cloud Storage from a CSV of extension ids.
From well-formatted CSV file containing some set of extensions
(extensions_csv), download them, compress into archive, and update
the remote extension archive under REMOTE_DIR in CHROME-PARTNER-TELEMETRY
bucket. This script expects 2nd column of CSV file to contain extension ids.
Args:
local_extensions_dir: directory to download CRX files into.
extension_csv: CSV to pull extension_ids from.
remote_dir: remote directory to put extension archive in cloud storage.
Raises:
Exception if a CRX download fails.
"""
# Download CRX to temp files and compress into archive
zip_path = os.path.join(local_extensions_dir, ZIP_NAME)
extension_zip = zipfile.ZipFile(zip_path, 'w')
update_csv = False
extensions_info = []
with open(extensions_csv, 'rb') as csv_file:
reader = csv.reader(csv_file)
# Stores comments (in case CSV needs to be updated/rewritten)
# and skips header line.
comments = []
line = ','.join(reader.next())
while line.startswith('#'):
comments.append(line)
line = ','.join(reader.next())
# Extract info from CSV.
for row in reader:
extension_info = {
'extension_name': row[0],
'id': row[1],
'hash': row[2],
'version': row[3]
}
print 'Fetching extension %s...' % extension_info['id']
crx_path = _DownloadCrxFromCws(extension_info['id'], local_extensions_dir)
if crx_path is None:
raise exceptions.Error('\tCould not fetch %s.\n\n'
'If this extension dl consistently fails, '
'remove this entry from %s.'
% (extension_info['id'], extensions_csv))
(new_hash, new_version) = _CrxHashIfChanged(crx_path, extension_info)
if new_hash is not None:
update_csv = True
extension_info['hash'] = new_hash
extension_info['version'] = new_version
extensions_info.append(extension_info)
extension_zip.write(crx_path, arcname='%s.crx' % extension_info['id'])
extension_zip.close()
if update_csv:
print 'Updating CSV...'
_UpdateCsv(comments, extensions_csv, extensions_info)
print 'Uploading extensions to cloud...'
remote_zip_path = os.path.join(remote_dir, ZIP_NAME)
cloud_storage.Insert(cloud_storage.PARTNER_BUCKET, remote_zip_path, zip_path) | [
"def",
"_UpdateExtensionsInCloud",
"(",
"local_extensions_dir",
",",
"extensions_csv",
",",
"remote_dir",
")",
":",
"# Download CRX to temp files and compress into archive",
"zip_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"local_extensions_dir",
",",
"ZIP_NAME",
")"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/perf/profile_creators/update_remote_extensions.py#L61-L123 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/configuration.py | python | Configuration.get_environ_vars | (self) | Returns a generator with all environmental vars with prefix PIP_ | Returns a generator with all environmental vars with prefix PIP_ | [
"Returns",
"a",
"generator",
"with",
"all",
"environmental",
"vars",
"with",
"prefix",
"PIP_"
] | def get_environ_vars(self):
# type: () -> Iterable[Tuple[str, str]]
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
if key.startswith("PIP_"):
name = key[4:].lower()
if name not in ENV_NAMES_IGNORED:
yield name, val | [
"def",
"get_environ_vars",
"(",
"self",
")",
":",
"# type: () -> Iterable[Tuple[str, str]]",
"for",
"key",
",",
"val",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"\"PIP_\"",
")",
":",
"name",
"=",
"key",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/configuration.py#L337-L344 | ||
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/python_message.py | python | _AddSlots | (message_descriptor, dictionary) | Adds a __slots__ entry to dictionary, containing the names of all valid
attributes for this message type.
Args:
message_descriptor: A Descriptor instance describing this message type.
dictionary: Class dictionary to which we'll add a '__slots__' entry. | Adds a __slots__ entry to dictionary, containing the names of all valid
attributes for this message type. | [
"Adds",
"a",
"__slots__",
"entry",
"to",
"dictionary",
"containing",
"the",
"names",
"of",
"all",
"valid",
"attributes",
"for",
"this",
"message",
"type",
"."
] | def _AddSlots(message_descriptor, dictionary):
"""Adds a __slots__ entry to dictionary, containing the names of all valid
attributes for this message type.
Args:
message_descriptor: A Descriptor instance describing this message type.
dictionary: Class dictionary to which we'll add a '__slots__' entry.
"""
dictionary['__slots__'] = ['_cached_byte_size',
'_cached_byte_size_dirty',
'_fields',
'_is_present_in_parent',
'_listener',
'_listener_for_children',
'__weakref__'] | [
"def",
"_AddSlots",
"(",
"message_descriptor",
",",
"dictionary",
")",
":",
"dictionary",
"[",
"'__slots__'",
"]",
"=",
"[",
"'_cached_byte_size'",
",",
"'_cached_byte_size_dirty'",
",",
"'_fields'",
",",
"'_is_present_in_parent'",
",",
"'_listener'",
",",
"'_listener... | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/python_message.py#L156-L170 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/imperative/imperative_graph.py | python | ImperativeGraph.run_pending_inits | (self, session) | Runs the pending variable initializations using `session`. | Runs the pending variable initializations using `session`. | [
"Runs",
"the",
"pending",
"variable",
"initializations",
"using",
"session",
"."
] | def run_pending_inits(self, session):
"""Runs the pending variable initializations using `session`."""
while self._init_ops:
session.run(self._init_ops.pop(0)) | [
"def",
"run_pending_inits",
"(",
"self",
",",
"session",
")",
":",
"while",
"self",
".",
"_init_ops",
":",
"session",
".",
"run",
"(",
"self",
".",
"_init_ops",
".",
"pop",
"(",
"0",
")",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/imperative/imperative_graph.py#L184-L187 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/sysconfig.py | python | get_path_names | () | return _SCHEMES.options('posix_prefix') | Return a tuple containing the paths names. | Return a tuple containing the paths names. | [
"Return",
"a",
"tuple",
"containing",
"the",
"paths",
"names",
"."
] | def get_path_names():
"""Return a tuple containing the paths names."""
# xxx see if we want a static list
return _SCHEMES.options('posix_prefix') | [
"def",
"get_path_names",
"(",
")",
":",
"# xxx see if we want a static list",
"return",
"_SCHEMES",
".",
"options",
"(",
"'posix_prefix'",
")"
] | 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/distlib/_backport/sysconfig.py#L434-L437 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/prepare_binding_Python.py | python | SwigSettings.output_out_of_date | (self) | return False | Returns whether the output file is out of date.
Compares output file time to all the input files.
@return True if any of the input files are newer than
the output file, or if the output file doesn't exist;
False otherwise. | Returns whether the output file is out of date. | [
"Returns",
"whether",
"the",
"output",
"file",
"is",
"out",
"of",
"date",
"."
] | def output_out_of_date(self):
"""Returns whether the output file is out of date.
Compares output file time to all the input files.
@return True if any of the input files are newer than
the output file, or if the output file doesn't exist;
False otherwise.
"""
if not os.path.exists(self.output_file):
logging.info("will generate, missing binding output file")
return True
output_mtime = os.path.getmtime(self.output_file)
if self._any_files_newer(self.header_files, output_mtime):
logging.info("will generate, header files newer")
return True
if self._any_files_newer(self.interface_files, output_mtime):
logging.info("will generate, interface files newer")
return True
if self._file_newer(self.input_file, output_mtime):
logging.info("will generate, swig input file newer")
return True
if self._file_newer(self.extensions_file, output_mtime):
logging.info("will generate, swig extensions file newer")
return True
if self._file_newer(self.wrapper_file, output_mtime):
logging.info("will generate, swig wrapper file newer")
return True
if self._file_newer(self.typemaps_file, output_mtime):
logging.info("will generate, swig typemaps file newer")
return True
if self._file_newer(self.safecast_file, output_mtime):
logging.info("will generate, swig safecast file newer")
return True
# If we made it here, nothing is newer than the output file.
# Thus, the output file is not out of date.
return False | [
"def",
"output_out_of_date",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"output_file",
")",
":",
"logging",
".",
"info",
"(",
"\"will generate, missing binding output file\"",
")",
"return",
"True",
"output_mtime",
... | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/prepare_binding_Python.py#L67-L104 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/rnn_cell.py | python | GRUCell.__call__ | (self, inputs, state, scope=None) | return new_h, new_h | Gated recurrent unit (GRU) with nunits cells. | Gated recurrent unit (GRU) with nunits cells. | [
"Gated",
"recurrent",
"unit",
"(",
"GRU",
")",
"with",
"nunits",
"cells",
"."
] | def __call__(self, inputs, state, scope=None):
"""Gated recurrent unit (GRU) with nunits cells."""
with vs.variable_scope(scope or type(self).__name__): # "GRUCell"
with vs.variable_scope("Gates"): # Reset gate and update gate.
# We start with bias of 1.0 to not reset and not update.
r, u = array_ops.split(1, 2, _linear([inputs, state],
2 * self._num_units, True, 1.0))
r, u = sigmoid(r), sigmoid(u)
with vs.variable_scope("Candidate"):
c = self._activation(_linear([inputs, r * state],
self._num_units, True))
new_h = u * state + (1 - u) * c
return new_h, new_h | [
"def",
"__call__",
"(",
"self",
",",
"inputs",
",",
"state",
",",
"scope",
"=",
"None",
")",
":",
"with",
"vs",
".",
"variable_scope",
"(",
"scope",
"or",
"type",
"(",
"self",
")",
".",
"__name__",
")",
":",
"# \"GRUCell\"",
"with",
"vs",
".",
"varia... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/rnn_cell.py#L220-L232 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/random_grad.py | python | _RandomGammaGrad | (op, grad) | Returns the gradient of a Gamma sample w.r.t. alpha.
The gradient is computed using implicit differentiation, see
"Implicit Reparameterization Gradients" (https://arxiv.org/abs/1805.08498).
Args:
op: A `RandomGamma` operation. We assume that the inputs to the operation
are `shape` and `alpha` tensors, and the output is the `sample` tensor.
grad: The incoming gradient `dloss / dsample` of the same shape as
`op.outputs[0]`.
Returns:
A `Tensor` with derivatives `dloss / dalpha` | Returns the gradient of a Gamma sample w.r.t. alpha. | [
"Returns",
"the",
"gradient",
"of",
"a",
"Gamma",
"sample",
"w",
".",
"r",
".",
"t",
".",
"alpha",
"."
] | def _RandomGammaGrad(op, grad): # pylint: disable=invalid-name
"""Returns the gradient of a Gamma sample w.r.t. alpha.
The gradient is computed using implicit differentiation, see
"Implicit Reparameterization Gradients" (https://arxiv.org/abs/1805.08498).
Args:
op: A `RandomGamma` operation. We assume that the inputs to the operation
are `shape` and `alpha` tensors, and the output is the `sample` tensor.
grad: The incoming gradient `dloss / dsample` of the same shape as
`op.outputs[0]`.
Returns:
A `Tensor` with derivatives `dloss / dalpha`
"""
shape = op.inputs[0]
alpha = op.inputs[1]
sample = op.outputs[0]
with ops.control_dependencies([grad]):
# Make the parameters alpha broadcastable with samples by appending
# unit dimensions.
num_sample_dimensions = array_ops.shape(shape)[0]
alpha_broadcastable = add_leading_unit_dimensions(
alpha, num_sample_dimensions)
partial_a = gen_random_ops.random_gamma_grad(alpha_broadcastable, sample)
# The first input is shape; the second input is alpha.
return (None, math_ops.reduce_sum(
grad * partial_a, axis=math_ops.range(num_sample_dimensions))) | [
"def",
"_RandomGammaGrad",
"(",
"op",
",",
"grad",
")",
":",
"# pylint: disable=invalid-name",
"shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"alpha",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"sample",
"=",
"op",
".",
"outputs",
"[",
"0",
"]",
"wi... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/random_grad.py#L36-L65 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Utils.py | python | skip_bom | (f) | Read past a BOM at the beginning of a source file.
This could be added to the scanner, but it's *substantially* easier
to keep it at this level. | Read past a BOM at the beginning of a source file.
This could be added to the scanner, but it's *substantially* easier
to keep it at this level. | [
"Read",
"past",
"a",
"BOM",
"at",
"the",
"beginning",
"of",
"a",
"source",
"file",
".",
"This",
"could",
"be",
"added",
"to",
"the",
"scanner",
"but",
"it",
"s",
"*",
"substantially",
"*",
"easier",
"to",
"keep",
"it",
"at",
"this",
"level",
"."
] | def skip_bom(f):
"""
Read past a BOM at the beginning of a source file.
This could be added to the scanner, but it's *substantially* easier
to keep it at this level.
"""
if f.read(1) != u'\uFEFF':
f.seek(0) | [
"def",
"skip_bom",
"(",
"f",
")",
":",
"if",
"f",
".",
"read",
"(",
"1",
")",
"!=",
"u'\\uFEFF'",
":",
"f",
".",
"seek",
"(",
"0",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Utils.py#L219-L226 | ||
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/internal/enum_type_wrapper.py | python | EnumTypeWrapper.Name | (self, number) | Returns a string containing the name of an enum value. | Returns a string containing the name of an enum value. | [
"Returns",
"a",
"string",
"containing",
"the",
"name",
"of",
"an",
"enum",
"value",
"."
] | def Name(self, number):
"""Returns a string containing the name of an enum value."""
if number in self._enum_type.values_by_number:
return self._enum_type.values_by_number[number].name
raise ValueError('Enum %s has no name defined for value %d' % (
self._enum_type.name, number)) | [
"def",
"Name",
"(",
"self",
",",
"number",
")",
":",
"if",
"number",
"in",
"self",
".",
"_enum_type",
".",
"values_by_number",
":",
"return",
"self",
".",
"_enum_type",
".",
"values_by_number",
"[",
"number",
"]",
".",
"name",
"raise",
"ValueError",
"(",
... | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/enum_type_wrapper.py#L51-L56 | ||
opengauss-mirror/openGauss-server | e383f1b77720a00ddbe4c0655bc85914d9b02a2b | src/gausskernel/dbmind/tools/ai_manager/module/index_advisor/uninstall.py | python | UnInstaller._get_install_info | () | Get installed information from record file.
install time | install version | install path | Get installed information from record file.
install time | install version | install path | [
"Get",
"installed",
"information",
"from",
"record",
"file",
".",
"install",
"time",
"|",
"install",
"version",
"|",
"install",
"path"
] | def _get_install_info():
"""
Get installed information from record file.
install time | install version | install path
"""
install_time, install_version, install_path = '', '', ''
if not os.path.isfile(VERSION_RECORD_FILE_INDEX_ADVISOR):
raise Exception(
Errors.FILE_DIR_PATH['gauss_0102'] % VERSION_RECORD_FILE_INDEX_ADVISOR)
install_info = CommonTools.read_last_line_from_file(
VERSION_RECORD_FILE_INDEX_ADVISOR).strip()
if install_info:
install_time, install_version, install_path = install_info.split('|')
# check path valid
CommonTools.check_path_valid(install_path)
if not os.path.isdir(install_path):
raise Exception(Errors.FILE_DIR_PATH['gauss_0103'] % install_path)
else:
g.logger.info('Successfully got index advisor install path[%s].' % install_path)
return install_time, install_version, install_path | [
"def",
"_get_install_info",
"(",
")",
":",
"install_time",
",",
"install_version",
",",
"install_path",
"=",
"''",
",",
"''",
",",
"''",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"VERSION_RECORD_FILE_INDEX_ADVISOR",
")",
":",
"raise",
"Exception",
... | https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/ai_manager/module/index_advisor/uninstall.py#L35-L54 | ||
Evolving-AI-Lab/fooling | 66f097dd6bd2eb6794ade3e187a7adfdf1887688 | caffe/scripts/cpp_lint.py | python | FindNextMatchingAngleBracket | (clean_lines, linenum, init_suffix) | return True | Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists. | Find the corresponding > to close a template. | [
"Find",
"the",
"corresponding",
">",
"to",
"close",
"a",
"template",
"."
] | def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
"""Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists.
"""
line = init_suffix
nesting_stack = ['<']
while True:
# Find the next operator that can tell us whether < is used as an
# opening bracket or as a less-than operator. We only want to
# warn on the latter case.
#
# We could also check all other operators and terminate the search
# early, e.g. if we got something like this "a<b+c", the "<" is
# most likely a less-than operator, but then we will get false
# positives for default arguments and other template expressions.
match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(1)
line = match.group(2)
if nesting_stack[-1] == '<':
# Expecting closing angle bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator == '>':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma after a bracket, this is most likely a template
# argument. We have not seen a closing angle bracket yet, but
# it's probably a few lines later if we look for it, so just
# return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting closing parenthesis or closing bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator in (')', ']'):
# We don't bother checking for matching () or []. If we got
# something like (] or [), it would have been a syntax error.
nesting_stack.pop()
else:
# Scan the next line
linenum += 1
if linenum >= len(clean_lines.elided):
break
line = clean_lines.elided[linenum]
# Exhausted all remaining lines and still no matching angle bracket.
# Most likely the input was incomplete, otherwise we should have
# seen a semicolon and returned early.
return True | [
"def",
"FindNextMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"init_suffix",
")",
":",
"line",
"=",
"init_suffix",
"nesting_stack",
"=",
"[",
"'<'",
"]",
"while",
"True",
":",
"# Find the next operator that can tell us whether < is used as an",
"# openin... | https://github.com/Evolving-AI-Lab/fooling/blob/66f097dd6bd2eb6794ade3e187a7adfdf1887688/caffe/scripts/cpp_lint.py#L2447-L2513 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextObject.FindPosition | (*args, **kwargs) | return _richtext.RichTextObject_FindPosition(*args, **kwargs) | FindPosition(self, DC dc, RichTextDrawingContext context, long index,
Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool | FindPosition(self, DC dc, RichTextDrawingContext context, long index,
Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool | [
"FindPosition",
"(",
"self",
"DC",
"dc",
"RichTextDrawingContext",
"context",
"long",
"index",
"Point",
"OUTPUT",
"int",
"OUTPUT",
"bool",
"forceLineStart",
")",
"-",
">",
"bool"
] | def FindPosition(*args, **kwargs):
"""
FindPosition(self, DC dc, RichTextDrawingContext context, long index,
Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool
"""
return _richtext.RichTextObject_FindPosition(*args, **kwargs) | [
"def",
"FindPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextObject_FindPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1187-L1192 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/lib2to3/pgen2/tokenize.py | python | generate_tokens | (readline) | The generate_tokens() generator requires one argument, readline, which
must be a callable object which provides the same interface as the
readline() method of built-in file objects. Each call to the function
should return one line of input as a string. Alternately, readline
can be a callable function terminating with StopIteration:
readline = open(myfile).next # Example of alternate readline
The generator produces 5-tuples with these members: the token type; the
token string; a 2-tuple (srow, scol) of ints specifying the row and
column where the token begins in the source; a 2-tuple (erow, ecol) of
ints specifying the row and column where the token ends in the source;
and the line on which the token was found. The line passed is the
physical line. | The generate_tokens() generator requires one argument, readline, which
must be a callable object which provides the same interface as the
readline() method of built-in file objects. Each call to the function
should return one line of input as a string. Alternately, readline
can be a callable function terminating with StopIteration:
readline = open(myfile).next # Example of alternate readline | [
"The",
"generate_tokens",
"()",
"generator",
"requires",
"one",
"argument",
"readline",
"which",
"must",
"be",
"a",
"callable",
"object",
"which",
"provides",
"the",
"same",
"interface",
"as",
"the",
"readline",
"()",
"method",
"of",
"built",
"-",
"in",
"file"... | def generate_tokens(readline):
"""
The generate_tokens() generator requires one argument, readline, which
must be a callable object which provides the same interface as the
readline() method of built-in file objects. Each call to the function
should return one line of input as a string. Alternately, readline
can be a callable function terminating with StopIteration:
readline = open(myfile).next # Example of alternate readline
The generator produces 5-tuples with these members: the token type; the
token string; a 2-tuple (srow, scol) of ints specifying the row and
column where the token begins in the source; a 2-tuple (erow, ecol) of
ints specifying the row and column where the token ends in the source;
and the line on which the token was found. The line passed is the
physical line.
"""
lnum = parenlev = continued = 0
contstr, needcont = '', 0
contline = None
indents = [0]
# 'stashed' and 'async_*' are used for async/await parsing
stashed = None
async_def = False
async_def_indent = 0
async_def_nl = False
while 1: # loop over lines in stream
try:
line = readline()
except StopIteration:
line = ''
lnum = lnum + 1
pos, max = 0, len(line)
if contstr: # continued string
if not line:
raise TokenError("EOF in multi-line string", strstart)
endmatch = endprog.match(line)
if endmatch:
pos = end = endmatch.end(0)
yield (STRING, contstr + line[:end],
strstart, (lnum, end), contline + line)
contstr, needcont = '', 0
contline = None
elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
yield (ERRORTOKEN, contstr + line,
strstart, (lnum, len(line)), contline)
contstr = ''
contline = None
continue
else:
contstr = contstr + line
contline = contline + line
continue
elif parenlev == 0 and not continued: # new statement
if not line: break
column = 0
while pos < max: # measure leading whitespace
if line[pos] == ' ': column = column + 1
elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize
elif line[pos] == '\f': column = 0
else: break
pos = pos + 1
if pos == max: break
if stashed:
yield stashed
stashed = None
if line[pos] in '#\r\n': # skip comments or blank lines
if line[pos] == '#':
comment_token = line[pos:].rstrip('\r\n')
nl_pos = pos + len(comment_token)
yield (COMMENT, comment_token,
(lnum, pos), (lnum, pos + len(comment_token)), line)
yield (NL, line[nl_pos:],
(lnum, nl_pos), (lnum, len(line)), line)
else:
yield ((NL, COMMENT)[line[pos] == '#'], line[pos:],
(lnum, pos), (lnum, len(line)), line)
continue
if column > indents[-1]: # count indents or dedents
indents.append(column)
yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
while column < indents[-1]:
if column not in indents:
raise IndentationError(
"unindent does not match any outer indentation level",
("<tokenize>", lnum, pos, line))
indents = indents[:-1]
if async_def and async_def_indent >= indents[-1]:
async_def = False
async_def_nl = False
async_def_indent = 0
yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
if async_def and async_def_nl and async_def_indent >= indents[-1]:
async_def = False
async_def_nl = False
async_def_indent = 0
else: # continued statement
if not line:
raise TokenError("EOF in multi-line statement", (lnum, 0))
continued = 0
while pos < max:
pseudomatch = pseudoprog.match(line, pos)
if pseudomatch: # scan for tokens
start, end = pseudomatch.span(1)
spos, epos, pos = (lnum, start), (lnum, end), end
token, initial = line[start:end], line[start]
if initial in string.digits or \
(initial == '.' and token != '.'): # ordinary number
yield (NUMBER, token, spos, epos, line)
elif initial in '\r\n':
newline = NEWLINE
if parenlev > 0:
newline = NL
elif async_def:
async_def_nl = True
if stashed:
yield stashed
stashed = None
yield (newline, token, spos, epos, line)
elif initial == '#':
assert not token.endswith("\n")
if stashed:
yield stashed
stashed = None
yield (COMMENT, token, spos, epos, line)
elif token in triple_quoted:
endprog = endprogs[token]
endmatch = endprog.match(line, pos)
if endmatch: # all on one line
pos = endmatch.end(0)
token = line[start:pos]
if stashed:
yield stashed
stashed = None
yield (STRING, token, spos, (lnum, pos), line)
else:
strstart = (lnum, start) # multiple lines
contstr = line[start:]
contline = line
break
elif initial in single_quoted or \
token[:2] in single_quoted or \
token[:3] in single_quoted:
if token[-1] == '\n': # continued string
strstart = (lnum, start)
endprog = (endprogs[initial] or endprogs[token[1]] or
endprogs[token[2]])
contstr, needcont = line[start:], 1
contline = line
break
else: # ordinary string
if stashed:
yield stashed
stashed = None
yield (STRING, token, spos, epos, line)
elif initial.isidentifier(): # ordinary name
if token in ('async', 'await'):
if async_def:
yield (ASYNC if token == 'async' else AWAIT,
token, spos, epos, line)
continue
tok = (NAME, token, spos, epos, line)
if token == 'async' and not stashed:
stashed = tok
continue
if token in ('def', 'for'):
if (stashed
and stashed[0] == NAME
and stashed[1] == 'async'):
if token == 'def':
async_def = True
async_def_indent = indents[-1]
yield (ASYNC, stashed[1],
stashed[2], stashed[3],
stashed[4])
stashed = None
if stashed:
yield stashed
stashed = None
yield tok
elif initial == '\\': # continued stmt
# This yield is new; needed for better idempotency:
if stashed:
yield stashed
stashed = None
yield (NL, token, spos, (lnum, pos), line)
continued = 1
else:
if initial in '([{': parenlev = parenlev + 1
elif initial in ')]}': parenlev = parenlev - 1
if stashed:
yield stashed
stashed = None
yield (OP, token, spos, epos, line)
else:
yield (ERRORTOKEN, line[pos],
(lnum, pos), (lnum, pos+1), line)
pos = pos + 1
if stashed:
yield stashed
stashed = None
for indent in indents[1:]: # pop remaining indent levels
yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') | [
"def",
"generate_tokens",
"(",
"readline",
")",
":",
"lnum",
"=",
"parenlev",
"=",
"continued",
"=",
"0",
"contstr",
",",
"needcont",
"=",
"''",
",",
"0",
"contline",
"=",
"None",
"indents",
"=",
"[",
"0",
"]",
"# 'stashed' and 'async_*' are used for async/awa... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lib2to3/pgen2/tokenize.py#L335-L559 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py | python | ParserElement.matches | (self, testString, parseAll=True) | Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- testString - to test against this expression for a match
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
Example::
expr = Word(nums)
assert expr.matches("100") | Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- testString - to test against this expression for a match
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
Example::
expr = Word(nums)
assert expr.matches("100") | [
"Method",
"for",
"quick",
"testing",
"of",
"a",
"parser",
"against",
"a",
"test",
"string",
".",
"Good",
"for",
"simple",
"inline",
"microtests",
"of",
"sub",
"expressions",
"while",
"building",
"up",
"larger",
"parser",
".",
"Parameters",
":",
"-",
"testStr... | def matches(self, testString, parseAll=True):
"""
Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- testString - to test against this expression for a match
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
Example::
expr = Word(nums)
assert expr.matches("100")
"""
try:
self.parseString(_ustr(testString), parseAll=parseAll)
return True
except ParseBaseException:
return False | [
"def",
"matches",
"(",
"self",
",",
"testString",
",",
"parseAll",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"parseString",
"(",
"_ustr",
"(",
"testString",
")",
",",
"parseAll",
"=",
"parseAll",
")",
"return",
"True",
"except",
"ParseBaseException",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py#L2213-L2230 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/credentials.py | python | AssumeRoleCredentialFetcher._create_client | (self) | return self._client_creator(
'sts',
aws_access_key_id=frozen_credentials.access_key,
aws_secret_access_key=frozen_credentials.secret_key,
aws_session_token=frozen_credentials.token,
) | Create an STS client using the source credentials. | Create an STS client using the source credentials. | [
"Create",
"an",
"STS",
"client",
"using",
"the",
"source",
"credentials",
"."
] | def _create_client(self):
"""Create an STS client using the source credentials."""
frozen_credentials = self._source_credentials.get_frozen_credentials()
return self._client_creator(
'sts',
aws_access_key_id=frozen_credentials.access_key,
aws_secret_access_key=frozen_credentials.secret_key,
aws_session_token=frozen_credentials.token,
) | [
"def",
"_create_client",
"(",
"self",
")",
":",
"frozen_credentials",
"=",
"self",
".",
"_source_credentials",
".",
"get_frozen_credentials",
"(",
")",
"return",
"self",
".",
"_client_creator",
"(",
"'sts'",
",",
"aws_access_key_id",
"=",
"frozen_credentials",
".",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/credentials.py#L806-L814 | |
zju3dv/clean-pvnet | 5870c509e3cc205e1bb28910a7b1a9a3c8add9a8 | lib/utils/pysixd/transform.py | python | Arcball.next | (self, acceleration=0.0) | Continue rotation in direction of last drag. | Continue rotation in direction of last drag. | [
"Continue",
"rotation",
"in",
"direction",
"of",
"last",
"drag",
"."
] | def next(self, acceleration=0.0):
"""Continue rotation in direction of last drag."""
q = quaternion_slerp(self._qpre, self._qnow, 2.0+acceleration, False)
self._qpre, self._qnow = self._qnow, q | [
"def",
"next",
"(",
"self",
",",
"acceleration",
"=",
"0.0",
")",
":",
"q",
"=",
"quaternion_slerp",
"(",
"self",
".",
"_qpre",
",",
"self",
".",
"_qnow",
",",
"2.0",
"+",
"acceleration",
",",
"False",
")",
"self",
".",
"_qpre",
",",
"self",
".",
"... | https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/pysixd/transform.py#L1607-L1610 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/shutil.py | python | copyfileobj | (fsrc, fdst, length=16*1024) | copy data from file-like object fsrc to file-like object fdst | copy data from file-like object fsrc to file-like object fdst | [
"copy",
"data",
"from",
"file",
"-",
"like",
"object",
"fsrc",
"to",
"file",
"-",
"like",
"object",
"fdst"
] | def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf) | [
"def",
"copyfileobj",
"(",
"fsrc",
",",
"fdst",
",",
"length",
"=",
"16",
"*",
"1024",
")",
":",
"while",
"1",
":",
"buf",
"=",
"fsrc",
".",
"read",
"(",
"length",
")",
"if",
"not",
"buf",
":",
"break",
"fdst",
".",
"write",
"(",
"buf",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/shutil.py#L60-L66 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | command | (command_name=None, doc=None) | return callable | A decorator function that registers an LLDB command line
command that is bound to the function it is attached to. | A decorator function that registers an LLDB command line
command that is bound to the function it is attached to. | [
"A",
"decorator",
"function",
"that",
"registers",
"an",
"LLDB",
"command",
"line",
"command",
"that",
"is",
"bound",
"to",
"the",
"function",
"it",
"is",
"attached",
"to",
"."
] | def command(command_name=None, doc=None):
import lldb
"""A decorator function that registers an LLDB command line
command that is bound to the function it is attached to."""
def callable(function):
"""Registers an lldb command for the decorated function."""
command = "command script add -f %s.%s %s" % (function.__module__, function.__name__, command_name or function.__name__)
lldb.debugger.HandleCommand(command)
if doc:
function.__doc__ = doc
return function
return callable | [
"def",
"command",
"(",
"command_name",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"import",
"lldb",
"def",
"callable",
"(",
"function",
")",
":",
"\"\"\"Registers an lldb command for the decorated function.\"\"\"",
"command",
"=",
"\"command script add -f %s.%s %s\... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15389-L15401 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/sandbox.py | python | AbstractSandbox._remap_output | (self, operation, path) | return self._validate_path(path) | Called for path outputs | Called for path outputs | [
"Called",
"for",
"path",
"outputs"
] | def _remap_output(self, operation, path):
"""Called for path outputs"""
return self._validate_path(path) | [
"def",
"_remap_output",
"(",
"self",
",",
"operation",
",",
"path",
")",
":",
"return",
"self",
".",
"_validate_path",
"(",
"path",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/sandbox.py#L364-L366 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py | python | DebugAnalyzer._render_node_traceback | (self, node_name) | return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) | Render traceback of a node's creation in Python, if available.
Args:
node_name: (str) name of the node.
Returns:
A RichTextLines object containing the stack trace of the node's
construction. | Render traceback of a node's creation in Python, if available. | [
"Render",
"traceback",
"of",
"a",
"node",
"s",
"creation",
"in",
"Python",
"if",
"available",
"."
] | def _render_node_traceback(self, node_name):
"""Render traceback of a node's creation in Python, if available.
Args:
node_name: (str) name of the node.
Returns:
A RichTextLines object containing the stack trace of the node's
construction.
"""
lines = [RL(""), RL(""), RL("Traceback of node construction:", "bold")]
try:
node_stack = self._debug_dump.node_traceback(node_name)
for depth, (file_path, line, function_name, text) in enumerate(
node_stack):
lines.append("%d: %s" % (depth, file_path))
attribute = debugger_cli_common.MenuItem(
"", "ps %s -b %d" % (file_path, line)) if text else None
line_number_line = RL(" ")
line_number_line += RL("Line: %d" % line, attribute)
lines.append(line_number_line)
lines.append(" Function: %s" % function_name)
lines.append(" Text: " + (("\"%s\"" % text) if text else "None"))
lines.append("")
except KeyError:
lines.append("(Node unavailable in the loaded Python graph)")
except LookupError:
lines.append("(Unavailable because no Python graph has been loaded)")
return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) | [
"def",
"_render_node_traceback",
"(",
"self",
",",
"node_name",
")",
":",
"lines",
"=",
"[",
"RL",
"(",
"\"\"",
")",
",",
"RL",
"(",
"\"\"",
")",
",",
"RL",
"(",
"\"Traceback of node construction:\"",
",",
"\"bold\"",
")",
"]",
"try",
":",
"node_stack",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py#L839-L872 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | panreas_hnn/hed-globalweight/scripts/cpp_lint.py | python | FileInfo.Extension | (self) | return self.Split()[2] | File extension - text following the final period. | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period",
"."
] | def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2] | [
"def",
"Extension",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"2",
"]"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/scripts/cpp_lint.py#L948-L950 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/util/file_util.py | python | intra_s3_copy_model | (s3_src_path, s3_dest_path, is_dir=False, aws_credentials = {}) | copy model from a source s3 path to the target s3 path. set 'is_dir' to True if you plan
to copy the directory. set 'is_dir' to False if you only plan to copy a single file.
the default value for 'is_dir' is False. | copy model from a source s3 path to the target s3 path. set 'is_dir' to True if you plan
to copy the directory. set 'is_dir' to False if you only plan to copy a single file.
the default value for 'is_dir' is False. | [
"copy",
"model",
"from",
"a",
"source",
"s3",
"path",
"to",
"the",
"target",
"s3",
"path",
".",
"set",
"is_dir",
"to",
"True",
"if",
"you",
"plan",
"to",
"copy",
"the",
"directory",
".",
"set",
"is_dir",
"to",
"False",
"if",
"you",
"only",
"plan",
"t... | def intra_s3_copy_model(s3_src_path, s3_dest_path, is_dir=False, aws_credentials = {}):
'''
copy model from a source s3 path to the target s3 path. set 'is_dir' to True if you plan
to copy the directory. set 'is_dir' to False if you only plan to copy a single file.
the default value for 'is_dir' is False.
'''
assert(is_s3_path(s3_src_path) and is_s3_path(s3_dest_path))
# check if should use boto
if _use_boto():
_intra_s3_copy_model(s3_src_path, s3_dest_path, aws_credentials)
return
__logger__.info('Copying s3 path %s to s3 path %s' % (s3_src_path, s3_dest_path))
# Get a list of all keys to copy
num_retries = 0
while num_retries < __RETRY_TIMES:
try:
_awscli_s3_op('cp', s3_src_path, s3_dest_path, recursive=is_dir, aws_credentials=aws_credentials)
__logger__.info("Successfully copied from s3 path %s to s3 path %s" % (s3_src_path, s3_dest_path))
break
except Exception as e:
num_retries = num_retries + 1
__logger__.info("Error hit while copying model from %s to %s: %s" % (s3_src_path, s3_dest_path, e))
__logger__.info("Retrying %s out of %s" % (num_retries, __RETRY_TIMES))
if num_retries == __RETRY_TIMES:
raise e
time.sleep(__SLEEP_SECONDS_BETWEEN_RETRIES) | [
"def",
"intra_s3_copy_model",
"(",
"s3_src_path",
",",
"s3_dest_path",
",",
"is_dir",
"=",
"False",
",",
"aws_credentials",
"=",
"{",
"}",
")",
":",
"assert",
"(",
"is_s3_path",
"(",
"s3_src_path",
")",
"and",
"is_s3_path",
"(",
"s3_dest_path",
")",
")",
"# ... | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/util/file_util.py#L649-L676 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/parse/standard_method.py | python | flatten | (x, order='C') | return F.reshape(F.transpose(x, new_order), (-1,)) | r"""
Return a copy of the tensor collapsed into one dimension.
Args:
order (str, optional): Can choose between 'C' and 'F'. 'C' means to
flatten in row-major (C-style) order. 'F' means to flatten in column-major
(Fortran-style) order. Only 'C' and 'F' are supported. Default: 'C'.
Returns:
Tensor, has the same data type as input.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Raises:
TypeError: If `order` is not string type.
ValueError: If `order` is string type, but not 'C' or 'F'.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.flatten()
>>> print(output.shape)
(24,) | r"""
Return a copy of the tensor collapsed into one dimension. | [
"r",
"Return",
"a",
"copy",
"of",
"the",
"tensor",
"collapsed",
"into",
"one",
"dimension",
"."
] | def flatten(x, order='C'):
r"""
Return a copy of the tensor collapsed into one dimension.
Args:
order (str, optional): Can choose between 'C' and 'F'. 'C' means to
flatten in row-major (C-style) order. 'F' means to flatten in column-major
(Fortran-style) order. Only 'C' and 'F' are supported. Default: 'C'.
Returns:
Tensor, has the same data type as input.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Raises:
TypeError: If `order` is not string type.
ValueError: If `order` is string type, but not 'C' or 'F'.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.flatten()
>>> print(output.shape)
(24,)
"""
order = check_flatten_order_const(order)
if order == 'C':
return F.reshape(x, (-1,))
perm = F.make_range(0, F.rank(x))
new_order = F.tuple_reversed(perm)
return F.reshape(F.transpose(x, new_order), (-1,)) | [
"def",
"flatten",
"(",
"x",
",",
"order",
"=",
"'C'",
")",
":",
"order",
"=",
"check_flatten_order_const",
"(",
"order",
")",
"if",
"order",
"==",
"'C'",
":",
"return",
"F",
".",
"reshape",
"(",
"x",
",",
"(",
"-",
"1",
",",
")",
")",
"perm",
"="... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L320-L353 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ToolBarBase.AddLabelTool | (self, id, label, bitmap,
bmpDisabled = wx.NullBitmap,
kind = wx.ITEM_NORMAL,
shortHelp = '', longHelp = '',
clientData = None) | return self.DoAddTool(id, label, bitmap, bmpDisabled, kind,
shortHelp, longHelp, clientData) | The full AddTool() function.
If bmpDisabled is wx.NullBitmap, a shadowed version of the normal bitmap
is created and used as the disabled image. | The full AddTool() function. | [
"The",
"full",
"AddTool",
"()",
"function",
"."
] | def AddLabelTool(self, id, label, bitmap,
bmpDisabled = wx.NullBitmap,
kind = wx.ITEM_NORMAL,
shortHelp = '', longHelp = '',
clientData = None):
'''
The full AddTool() function.
If bmpDisabled is wx.NullBitmap, a shadowed version of the normal bitmap
is created and used as the disabled image.
'''
return self.DoAddTool(id, label, bitmap, bmpDisabled, kind,
shortHelp, longHelp, clientData) | [
"def",
"AddLabelTool",
"(",
"self",
",",
"id",
",",
"label",
",",
"bitmap",
",",
"bmpDisabled",
"=",
"wx",
".",
"NullBitmap",
",",
"kind",
"=",
"wx",
".",
"ITEM_NORMAL",
",",
"shortHelp",
"=",
"''",
",",
"longHelp",
"=",
"''",
",",
"clientData",
"=",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3674-L3686 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/examples/tutorials/mnist/fully_connected_feed.py | python | do_eval | (sess,
eval_correct,
images_placeholder,
labels_placeholder,
data_set) | Runs one evaluation against the full epoch of data.
Args:
sess: The session in which the model has been trained.
eval_correct: The Tensor that returns the number of correct predictions.
images_placeholder: The images placeholder.
labels_placeholder: The labels placeholder.
data_set: The set of images and labels to evaluate, from
input_data.read_data_sets(). | Runs one evaluation against the full epoch of data. | [
"Runs",
"one",
"evaluation",
"against",
"the",
"full",
"epoch",
"of",
"data",
"."
] | def do_eval(sess,
eval_correct,
images_placeholder,
labels_placeholder,
data_set):
"""Runs one evaluation against the full epoch of data.
Args:
sess: The session in which the model has been trained.
eval_correct: The Tensor that returns the number of correct predictions.
images_placeholder: The images placeholder.
labels_placeholder: The labels placeholder.
data_set: The set of images and labels to evaluate, from
input_data.read_data_sets().
"""
# And run one epoch of eval.
true_count = 0 # Counts the number of correct predictions.
steps_per_epoch = data_set.num_examples // FLAGS.batch_size
num_examples = steps_per_epoch * FLAGS.batch_size
for step in xrange(steps_per_epoch):
feed_dict = fill_feed_dict(data_set,
images_placeholder,
labels_placeholder)
true_count += sess.run(eval_correct, feed_dict=feed_dict)
precision = true_count / num_examples
print(' Num examples: %d Num correct: %d Precision @ 1: %0.04f' %
(num_examples, true_count, precision)) | [
"def",
"do_eval",
"(",
"sess",
",",
"eval_correct",
",",
"images_placeholder",
",",
"labels_placeholder",
",",
"data_set",
")",
":",
"# And run one epoch of eval.",
"true_count",
"=",
"0",
"# Counts the number of correct predictions.",
"steps_per_epoch",
"=",
"data_set",
... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/examples/tutorials/mnist/fully_connected_feed.py#L86-L112 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/layer/rnns.py | python | _check_is_tuple | (param_name, input_data, cls_name) | Internal function, used to check whether the input data is Tensor. | Internal function, used to check whether the input data is Tensor. | [
"Internal",
"function",
"used",
"to",
"check",
"whether",
"the",
"input",
"data",
"is",
"Tensor",
"."
] | def _check_is_tuple(param_name, input_data, cls_name):
"""Internal function, used to check whether the input data is Tensor."""
if input_data is not None and not isinstance(P.typeof(input_data), mstype.Tuple):
raise TypeError(f"For '{cls_name}', the '{param_name}' should be '{mstype.Tuple}', "
f"but got '{P.typeof(input_data)}'") | [
"def",
"_check_is_tuple",
"(",
"param_name",
",",
"input_data",
",",
"cls_name",
")",
":",
"if",
"input_data",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"P",
".",
"typeof",
"(",
"input_data",
")",
",",
"mstype",
".",
"Tuple",
")",
":",
"raise... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/rnns.py#L69-L73 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/webapp2/webapp2.py | python | Response._get_status_message | (self) | return self.status.split(' ', 1)[1] | The response status message, as a string. | The response status message, as a string. | [
"The",
"response",
"status",
"message",
"as",
"a",
"string",
"."
] | def _get_status_message(self):
"""The response status message, as a string."""
return self.status.split(' ', 1)[1] | [
"def",
"_get_status_message",
"(",
"self",
")",
":",
"return",
"self",
".",
"status",
".",
"split",
"(",
"' '",
",",
"1",
")",
"[",
"1",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2.py#L427-L429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.