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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/ragweed.py | python | download | (ctx, config) | Download the s3 tests from the git builder.
Remove downloaded s3 file upon exit.
The context passed in should be identical to the context
passed in to the main task. | Download the s3 tests from the git builder.
Remove downloaded s3 file upon exit. | [
"Download",
"the",
"s3",
"tests",
"from",
"the",
"git",
"builder",
".",
"Remove",
"downloaded",
"s3",
"file",
"upon",
"exit",
"."
] | def download(ctx, config):
"""
Download the s3 tests from the git builder.
Remove downloaded s3 file upon exit.
The context passed in should be identical to the context
passed in to the main task.
"""
assert isinstance(config, dict)
log.info('Downloading ragweed...')
testdir = teuthology.get_testdir(ctx)
for (client, cconf) in config.items():
ragweed_repo = ctx.config.get('ragweed_repo',
teuth_config.ceph_git_base_url + 'ragweed.git')
for branch in get_ragweed_branches(ctx.config, cconf):
log.info("Using branch '%s' for ragweed", branch)
try:
ctx.cluster.only(client).sh(
script=f'git clone -b {branch} {ragweed_repo} {testdir}/ragweed')
break
except Exception as e:
exc = e
else:
raise exc
sha1 = cconf.get('sha1')
if sha1 is not None:
ctx.cluster.only(client).run(
args=[
'cd', '{tdir}/ragweed'.format(tdir=testdir),
run.Raw('&&'),
'git', 'reset', '--hard', sha1,
],
)
try:
yield
finally:
log.info('Removing ragweed...')
testdir = teuthology.get_testdir(ctx)
for client in config:
ctx.cluster.only(client).run(
args=[
'rm',
'-rf',
'{tdir}/ragweed'.format(tdir=testdir),
],
) | [
"def",
"download",
"(",
"ctx",
",",
"config",
")",
":",
"assert",
"isinstance",
"(",
"config",
",",
"dict",
")",
"log",
".",
"info",
"(",
"'Downloading ragweed...'",
")",
"testdir",
"=",
"teuthology",
".",
"get_testdir",
"(",
"ctx",
")",
"for",
"(",
"cli... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ragweed.py#L48-L94 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.getboolean | (self, s) | return self.tk.getboolean(s) | Return a boolean value for Tcl boolean values true and false given as parameter. | Return a boolean value for Tcl boolean values true and false given as parameter. | [
"Return",
"a",
"boolean",
"value",
"for",
"Tcl",
"boolean",
"values",
"true",
"and",
"false",
"given",
"as",
"parameter",
"."
] | def getboolean(self, s):
"""Return a boolean value for Tcl boolean values true and false given as parameter."""
return self.tk.getboolean(s) | [
"def",
"getboolean",
"(",
"self",
",",
"s",
")",
":",
"return",
"self",
".",
"tk",
".",
"getboolean",
"(",
"s",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L457-L459 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | PreHtmlHelpDialog | (*args, **kwargs) | return val | PreHtmlHelpDialog(HtmlHelpData data=None) -> HtmlHelpDialog | PreHtmlHelpDialog(HtmlHelpData data=None) -> HtmlHelpDialog | [
"PreHtmlHelpDialog",
"(",
"HtmlHelpData",
"data",
"=",
"None",
")",
"-",
">",
"HtmlHelpDialog"
] | def PreHtmlHelpDialog(*args, **kwargs):
"""PreHtmlHelpDialog(HtmlHelpData data=None) -> HtmlHelpDialog"""
val = _html.new_PreHtmlHelpDialog(*args, **kwargs)
self._setOORInfo(self)
return val | [
"def",
"PreHtmlHelpDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_html",
".",
"new_PreHtmlHelpDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1850-L1854 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/zip.py | python | generate | (env) | Add Builders and construction variables for zip to an Environment. | Add Builders and construction variables for zip to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"zip",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for zip to an Environment."""
try:
bld = env['BUILDERS']['Zip']
except KeyError:
bld = ZipBuilder
env['BUILDERS']['Zip'] = bld
env['ZIP'] = 'zip'
env['ZIPFLAGS'] = SCons.Util.CLVar('')
env['ZIPCOM'] = zipAction
env['ZIPCOMPRESSION'] = zipcompression
env['ZIPSUFFIX'] = '.zip'
env['ZIPROOT'] = SCons.Util.CLVar('') | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"bld",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Zip'",
"]",
"except",
"KeyError",
":",
"bld",
"=",
"ZipBuilder",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Zip'",
"]",
"=",
"bld",
"env",
"[",
"'ZIP'... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/zip.py#L78-L91 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/clang/tools/scan-build-py/libscanbuild/runner.py | python | classify_parameters | (command) | return result | Prepare compiler flags (filters some and add others) and take out
language (-x) and architecture (-arch) flags for future processing. | Prepare compiler flags (filters some and add others) and take out
language (-x) and architecture (-arch) flags for future processing. | [
"Prepare",
"compiler",
"flags",
"(",
"filters",
"some",
"and",
"add",
"others",
")",
"and",
"take",
"out",
"language",
"(",
"-",
"x",
")",
"and",
"architecture",
"(",
"-",
"arch",
")",
"flags",
"for",
"future",
"processing",
"."
] | def classify_parameters(command):
""" Prepare compiler flags (filters some and add others) and take out
language (-x) and architecture (-arch) flags for future processing. """
result = {
'flags': [], # the filtered compiler flags
'arch_list': [], # list of architecture flags
'language': None, # compilation language, None, if not specified
'compiler': compiler_language(command) # 'c' or 'c++'
}
# iterate on the compile options
args = iter(command[1:])
for arg in args:
# take arch flags into a separate basket
if arg == '-arch':
result['arch_list'].append(next(args))
# take language
elif arg == '-x':
result['language'] = next(args)
# parameters which looks source file are not flags
elif re.match(r'^[^-].+', arg) and classify_source(arg):
pass
# ignore some flags
elif arg in IGNORED_FLAGS:
count = IGNORED_FLAGS[arg]
for _ in range(count):
next(args)
# we don't care about extra warnings, but we should suppress ones
# that we don't want to see.
elif re.match(r'^-W.+', arg) and not re.match(r'^-Wno-.+', arg):
pass
# and consider everything else as compilation flag.
else:
result['flags'].append(arg)
return result | [
"def",
"classify_parameters",
"(",
"command",
")",
":",
"result",
"=",
"{",
"'flags'",
":",
"[",
"]",
",",
"# the filtered compiler flags",
"'arch_list'",
":",
"[",
"]",
",",
"# list of architecture flags",
"'language'",
":",
"None",
",",
"# compilation language, No... | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/tools/scan-build-py/libscanbuild/runner.py#L266-L302 | |
rampageX/firmware-mod-kit | c94cd6aeee50d92ec5280a6dba6d74828fd3606b | src/binwalk-2.1.1/src/binwalk/core/magic.py | python | Magic.match | (self, data) | return self.scan(data, 1) | Match the beginning of a data buffer to a signature.
@data - The data buffer to match against the loaded signature list.
Returns a list of SignatureResult objects. | Match the beginning of a data buffer to a signature. | [
"Match",
"the",
"beginning",
"of",
"a",
"data",
"buffer",
"to",
"a",
"signature",
"."
] | def match(self, data):
'''
Match the beginning of a data buffer to a signature.
@data - The data buffer to match against the loaded signature list.
Returns a list of SignatureResult objects.
'''
return self.scan(data, 1) | [
"def",
"match",
"(",
"self",
",",
"data",
")",
":",
"return",
"self",
".",
"scan",
"(",
"data",
",",
"1",
")"
] | https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/core/magic.py#L716-L724 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/multiprocessing/util.py | python | Finalize.cancel | (self) | Cancel finalization of the object | Cancel finalization of the object | [
"Cancel",
"finalization",
"of",
"the",
"object"
] | def cancel(self):
'''
Cancel finalization of the object
'''
try:
del _finalizer_registry[self._key]
except KeyError:
pass
else:
self._weakref = self._callback = self._args = \
self._kwargs = self._key = None | [
"def",
"cancel",
"(",
"self",
")",
":",
"try",
":",
"del",
"_finalizer_registry",
"[",
"self",
".",
"_key",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"self",
".",
"_weakref",
"=",
"self",
".",
"_callback",
"=",
"self",
".",
"_args",
"=",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/multiprocessing/util.py#L206-L216 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/generator/xcodeproj_file.py | python | XCConfigurationList.HasBuildSetting | (self, key) | return 1 | Determines the state of a build setting in all XCBuildConfiguration
child objects.
If all child objects have key in their build settings, and the value is the
same in all child objects, returns 1.
If no child objects have the key in their build settings, returns 0.
If some, but not all, child objects have the key in their build settings,
or if any children have different values for the key, returns -1. | Determines the state of a build setting in all XCBuildConfiguration
child objects. | [
"Determines",
"the",
"state",
"of",
"a",
"build",
"setting",
"in",
"all",
"XCBuildConfiguration",
"child",
"objects",
"."
] | def HasBuildSetting(self, key):
"""Determines the state of a build setting in all XCBuildConfiguration
child objects.
If all child objects have key in their build settings, and the value is the
same in all child objects, returns 1.
If no child objects have the key in their build settings, returns 0.
If some, but not all, child objects have the key in their build settings,
or if any children have different values for the key, returns -1.
"""
has = None
value = None
for configuration in self._properties['buildConfigurations']:
configuration_has = configuration.HasBuildSetting(key)
if has is None:
has = configuration_has
elif has != configuration_has:
return -1
if configuration_has:
configuration_value = configuration.GetBuildSetting(key)
if value is None:
value = configuration_value
elif value != configuration_value:
return -1
if not has:
return 0
return 1 | [
"def",
"HasBuildSetting",
"(",
"self",
",",
"key",
")",
":",
"has",
"=",
"None",
"value",
"=",
"None",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"configuration_has",
"=",
"configuration",
".",
"HasBuildSe... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/xcodeproj_file.py#L1626-L1658 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/symsrc/pdb_fingerprint_from_img.py | python | GetPDBInfoFromImg | (filename) | Returns the PDB fingerprint and the pdb filename given an image file | Returns the PDB fingerprint and the pdb filename given an image file | [
"Returns",
"the",
"PDB",
"fingerprint",
"and",
"the",
"pdb",
"filename",
"given",
"an",
"image",
"file"
] | def GetPDBInfoFromImg(filename):
"""Returns the PDB fingerprint and the pdb filename given an image file"""
pe = pefile.PE(filename)
for dbg in pe.DIRECTORY_ENTRY_DEBUG:
if dbg.struct.Type == 2: # IMAGE_DEBUG_TYPE_CODEVIEW
off = dbg.struct.AddressOfRawData
size = dbg.struct.SizeOfData
data = pe.get_memory_mapped_image()[off:off+size]
cv = pefile.Structure(__CV_INFO_PDB70_format__)
cv.__unpack__(data)
cv.PdbFileName = data[cv.sizeof():]
guid = pefile.Structure(__GUID_format__)
guid.__unpack__(cv.Signature)
guid.Data4_0 = ''.join("%02X" % ord(x) for x in guid.Data4[0:2])
guid.Data4_1 = ''.join("%02X" % ord(x) for x in guid.Data4[2:])
return ("%08X%04X%04X%s%s%d" % (
guid.Data1, guid.Data2, guid.Data3,
guid.Data4_0, guid.Data4_1, cv.Age),
cv.PdbFileName.split('\x00', 1)[0])
break | [
"def",
"GetPDBInfoFromImg",
"(",
"filename",
")",
":",
"pe",
"=",
"pefile",
".",
"PE",
"(",
"filename",
")",
"for",
"dbg",
"in",
"pe",
".",
"DIRECTORY_ENTRY_DEBUG",
":",
"if",
"dbg",
".",
"struct",
".",
"Type",
"==",
"2",
":",
"# IMAGE_DEBUG_TYPE_CODEVIEW"... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/symsrc/pdb_fingerprint_from_img.py#L26-L50 | ||
GXYM/DRRG | 9e074fa9052de8d131f55ca1f6ae6673c1bfeca4 | dataset/total_text/Evaluation_Protocol/Python_scripts/Deteval.py | python | tau_calculation | (det_x, det_y, gt_x, gt_y) | return np.round((area_of_intersection(det_x, det_y, gt_x, gt_y) / area(det_x, det_y)), 2) | tau = inter_area / det_area | tau = inter_area / det_area | [
"tau",
"=",
"inter_area",
"/",
"det_area"
] | def tau_calculation(det_x, det_y, gt_x, gt_y):
"""
tau = inter_area / det_area
"""
return np.round((area_of_intersection(det_x, det_y, gt_x, gt_y) / area(det_x, det_y)), 2) | [
"def",
"tau_calculation",
"(",
"det_x",
",",
"det_y",
",",
"gt_x",
",",
"gt_y",
")",
":",
"return",
"np",
".",
"round",
"(",
"(",
"area_of_intersection",
"(",
"det_x",
",",
"det_y",
",",
"gt_x",
",",
"gt_y",
")",
"/",
"area",
"(",
"det_x",
",",
"det_... | https://github.com/GXYM/DRRG/blob/9e074fa9052de8d131f55ca1f6ae6673c1bfeca4/dataset/total_text/Evaluation_Protocol/Python_scripts/Deteval.py#L78-L82 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/resolvelib/providers.py | python | AbstractProvider.is_satisfied_by | (self, requirement, candidate) | Whether the given requirement can be satisfied by a candidate.
The candidate is guarenteed to have been generated from the
requirement.
A boolean should be returned to indicate whether `candidate` is a
viable solution to the requirement. | Whether the given requirement can be satisfied by a candidate. | [
"Whether",
"the",
"given",
"requirement",
"can",
"be",
"satisfied",
"by",
"a",
"candidate",
"."
] | def is_satisfied_by(self, requirement, candidate):
"""Whether the given requirement can be satisfied by a candidate.
The candidate is guarenteed to have been generated from the
requirement.
A boolean should be returned to indicate whether `candidate` is a
viable solution to the requirement.
"""
raise NotImplementedError | [
"def",
"is_satisfied_by",
"(",
"self",
",",
"requirement",
",",
"candidate",
")",
":",
"raise",
"NotImplementedError"
] | 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/resolvelib/providers.py#L78-L87 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/asyncio/tasks.py | python | run_coroutine_threadsafe | (coro, loop) | return future | Submit a coroutine object to a given event loop.
Return a concurrent.futures.Future to access the result. | Submit a coroutine object to a given event loop. | [
"Submit",
"a",
"coroutine",
"object",
"to",
"a",
"given",
"event",
"loop",
"."
] | def run_coroutine_threadsafe(coro, loop):
"""Submit a coroutine object to a given event loop.
Return a concurrent.futures.Future to access the result.
"""
if not coroutines.iscoroutine(coro):
raise TypeError('A coroutine object is required')
future = concurrent.futures.Future()
def callback():
try:
futures._chain_future(ensure_future(coro, loop=loop), future)
except (SystemExit, KeyboardInterrupt):
raise
except BaseException as exc:
if future.set_running_or_notify_cancel():
future.set_exception(exc)
raise
loop.call_soon_threadsafe(callback)
return future | [
"def",
"run_coroutine_threadsafe",
"(",
"coro",
",",
"loop",
")",
":",
"if",
"not",
"coroutines",
".",
"iscoroutine",
"(",
"coro",
")",
":",
"raise",
"TypeError",
"(",
"'A coroutine object is required'",
")",
"future",
"=",
"concurrent",
".",
"futures",
".",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/tasks.py#L915-L935 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | Choicebook.Create | (*args, **kwargs) | return _controls_.Choicebook_Create(*args, **kwargs) | Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=EmptyString) -> bool | Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=EmptyString) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
"String",
"name",
"=",
"EmptyString",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=EmptyString) -> bool
"""
return _controls_.Choicebook_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Choicebook_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3271-L3276 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/rfcn/lib/datasets/ds_utils.py | python | validate_boxes | (boxes, width=0, height=0) | Check that a set of boxes are valid. | Check that a set of boxes are valid. | [
"Check",
"that",
"a",
"set",
"of",
"boxes",
"are",
"valid",
"."
] | def validate_boxes(boxes, width=0, height=0):
"""Check that a set of boxes are valid."""
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
assert (x1 >= 0).all()
assert (y1 >= 0).all()
assert (x2 >= x1).all()
assert (y2 >= y1).all()
assert (x2 < width).all()
assert (y2 < height).all() | [
"def",
"validate_boxes",
"(",
"boxes",
",",
"width",
"=",
"0",
",",
"height",
"=",
"0",
")",
":",
"x1",
"=",
"boxes",
"[",
":",
",",
"0",
"]",
"y1",
"=",
"boxes",
"[",
":",
",",
"1",
"]",
"x2",
"=",
"boxes",
"[",
":",
",",
"2",
"]",
"y2",
... | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/lib/datasets/ds_utils.py#L24-L35 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/msvc.py | python | msvc9_find_vcvarsall | (version) | return get_unpatched(msvc9_find_vcvarsall)(version) | Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone
compiler build for Python (VCForPython). Fall back to original behavior
when the standalone compiler is not available.
Redirect the path of "vcvarsall.bat".
Known supported compilers
-------------------------
Microsoft Visual C++ 9.0:
Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64)
Parameters
----------
version: float
Required Microsoft Visual C++ version.
Return
------
vcvarsall.bat path: str | Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone
compiler build for Python (VCForPython). Fall back to original behavior
when the standalone compiler is not available. | [
"Patched",
"distutils",
".",
"msvc9compiler",
".",
"find_vcvarsall",
"to",
"use",
"the",
"standalone",
"compiler",
"build",
"for",
"Python",
"(",
"VCForPython",
")",
".",
"Fall",
"back",
"to",
"original",
"behavior",
"when",
"the",
"standalone",
"compiler",
"is"... | def msvc9_find_vcvarsall(version):
"""
Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone
compiler build for Python (VCForPython). Fall back to original behavior
when the standalone compiler is not available.
Redirect the path of "vcvarsall.bat".
Known supported compilers
-------------------------
Microsoft Visual C++ 9.0:
Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64)
Parameters
----------
version: float
Required Microsoft Visual C++ version.
Return
------
vcvarsall.bat path: str
"""
VC_BASE = r'Software\%sMicrosoft\DevDiv\VCForPython\%0.1f'
key = VC_BASE % ('', version)
try:
# Per-user installs register the compiler path here
productdir = Reg.get_value(key, "installdir")
except KeyError:
try:
# All-user installs on a 64-bit system register here
key = VC_BASE % ('Wow6432Node\\', version)
productdir = Reg.get_value(key, "installdir")
except KeyError:
productdir = None
if productdir:
vcvarsall = os.path.os.path.join(productdir, "vcvarsall.bat")
if os.path.isfile(vcvarsall):
return vcvarsall
return get_unpatched(msvc9_find_vcvarsall)(version) | [
"def",
"msvc9_find_vcvarsall",
"(",
"version",
")",
":",
"VC_BASE",
"=",
"r'Software\\%sMicrosoft\\DevDiv\\VCForPython\\%0.1f'",
"key",
"=",
"VC_BASE",
"%",
"(",
"''",
",",
"version",
")",
"try",
":",
"# Per-user installs register the compiler path here",
"productdir",
"=... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/msvc.py#L63-L103 | |
rootm0s/Protectors | 5b3f4d11687a5955caf9c3af30666c4bfc2c19ab | OWASP-ZSC/module/readline_windows/pyreadline/lineeditor/history.py | python | LineHistory.get_history_item | (self, index) | return item.get_line_text() | Return the current contents of history item at index (starts with index 1). | Return the current contents of history item at index (starts with index 1). | [
"Return",
"the",
"current",
"contents",
"of",
"history",
"item",
"at",
"index",
"(",
"starts",
"with",
"index",
"1",
")",
"."
] | def get_history_item(self, index):
'''Return the current contents of history item at index (starts with index 1).'''
item = self.history[index - 1]
log("get_history_item: index:%d item:%r" % (index, item))
return item.get_line_text() | [
"def",
"get_history_item",
"(",
"self",
",",
"index",
")",
":",
"item",
"=",
"self",
".",
"history",
"[",
"index",
"-",
"1",
"]",
"log",
"(",
"\"get_history_item: index:%d item:%r\"",
"%",
"(",
"index",
",",
"item",
")",
")",
"return",
"item",
".",
"get_... | https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/lineeditor/history.py#L53-L57 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/pickle.py | python | Pickler.memoize | (self, obj) | Store an object in the memo. | Store an object in the memo. | [
"Store",
"an",
"object",
"in",
"the",
"memo",
"."
] | def memoize(self, obj):
"""Store an object in the memo."""
# The Pickler memo is a dictionary mapping object ids to 2-tuples
# that contain the Unpickler memo key and the object being memoized.
# The memo key is written to the pickle and will become
# the key in the Unpickler's memo. The object is stored in the
# Pickler memo so that transient objects are kept alive during
# pickling.
# The use of the Unpickler memo length as the memo key is just a
# convention. The only requirement is that the memo values be unique.
# But there appears no advantage to any other scheme, and this
# scheme allows the Unpickler memo to be implemented as a plain (but
# growable) array, indexed by memo key.
if self.fast:
return
assert id(obj) not in self.memo
memo_len = len(self.memo)
self.write(self.put(memo_len))
self.memo[id(obj)] = memo_len, obj | [
"def",
"memoize",
"(",
"self",
",",
"obj",
")",
":",
"# The Pickler memo is a dictionary mapping object ids to 2-tuples",
"# that contain the Unpickler memo key and the object being memoized.",
"# The memo key is written to the pickle and will become",
"# the key in the Unpickler's memo. The ... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pickle.py#L227-L247 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/framework/ops.py | python | RegisterShape.__call__ | (self, f) | return f | Registers "f" as the shape function for "op_type". | Registers "f" as the shape function for "op_type". | [
"Registers",
"f",
"as",
"the",
"shape",
"function",
"for",
"op_type",
"."
] | def __call__(self, f):
"""Registers "f" as the shape function for "op_type"."""
if f is None:
# None is a special "weak" value that provides a default shape function,
# and can be overridden by a non-None registration.
try:
_default_shape_function_registry.register(_no_shape_function,
self._op_type)
except KeyError:
# Ignore duplicate registrations of the weak value. This can
# occur if the op library input to wrapper generation
# inadvertently links in one or more of the standard op
# libraries.
pass
else:
_shape_registry.register(f, self._op_type)
return f | [
"def",
"__call__",
"(",
"self",
",",
"f",
")",
":",
"if",
"f",
"is",
"None",
":",
"# None is a special \"weak\" value that provides a default shape function,",
"# and can be overridden by a non-None registration.",
"try",
":",
"_default_shape_function_registry",
".",
"register"... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L1752-L1768 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py | python | IMAP4.subscribe | (self, mailbox) | return self._simple_command('SUBSCRIBE', mailbox) | Subscribe to new mailbox.
(typ, [data]) = <instance>.subscribe(mailbox) | Subscribe to new mailbox. | [
"Subscribe",
"to",
"new",
"mailbox",
"."
] | def subscribe(self, mailbox):
"""Subscribe to new mailbox.
(typ, [data]) = <instance>.subscribe(mailbox)
"""
return self._simple_command('SUBSCRIBE', mailbox) | [
"def",
"subscribe",
"(",
"self",
",",
"mailbox",
")",
":",
"return",
"self",
".",
"_simple_command",
"(",
"'SUBSCRIBE'",
",",
"mailbox",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py#L725-L730 | |
manutdzou/KITTI_SSD | 5b620c2f291d36a0fe14489214f22a992f173f44 | scripts/cpp_lint.py | python | GetPreviousNonBlankLine | (clean_lines, linenum) | return ('', -1) | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line. | Return the most recent non-blank line and its line number. | [
"Return",
"the",
"most",
"recent",
"non",
"-",
"blank",
"line",
"and",
"its",
"line",
"number",
"."
] | def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | [
"def",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"prevlinenum",
"=",
"linenum",
"-",
"1",
"while",
"prevlinenum",
">=",
"0",
":",
"prevline",
"=",
"clean_lines",
".",
"elided",
"[",
"prevlinenum",
"]",
"if",
"not",
"IsBlankLine",... | https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/scripts/cpp_lint.py#L3050-L3070 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/install_egg_info.py | python | safe_name | (name) | return re.sub('[^A-Za-z0-9.]+', '-', name) | Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'. | Convert an arbitrary string to a standard distribution name | [
"Convert",
"an",
"arbitrary",
"string",
"to",
"a",
"standard",
"distribution",
"name"
] | def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
"""
return re.sub('[^A-Za-z0-9.]+', '-', name) | [
"def",
"safe_name",
"(",
"name",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"name",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/install_egg_info.py#L55-L60 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/tpu/python/tpu/tpu_estimator.py | python | _wrap_computation_in_while_loop | (device, op_fn) | Wraps the ops generated by `op_fn` in tf.while_loop. | Wraps the ops generated by `op_fn` in tf.while_loop. | [
"Wraps",
"the",
"ops",
"generated",
"by",
"op_fn",
"in",
"tf",
".",
"while_loop",
"."
] | def _wrap_computation_in_while_loop(device, op_fn):
"""Wraps the ops generated by `op_fn` in tf.while_loop."""
def computation(i):
with ops.control_dependencies(op_fn()):
return i + 1
iterations_per_loop_var = _create_or_get_iterations_per_loop()
# By setting parallel_iterations=1, the parallel execution in while_loop is
# basically turned off.
with ops.device(device):
iterations = array_ops.identity(iterations_per_loop_var)
return control_flow_ops.while_loop(
lambda i: i < iterations,
computation, [constant_op.constant(0)], parallel_iterations=1) | [
"def",
"_wrap_computation_in_while_loop",
"(",
"device",
",",
"op_fn",
")",
":",
"def",
"computation",
"(",
"i",
")",
":",
"with",
"ops",
".",
"control_dependencies",
"(",
"op_fn",
"(",
")",
")",
":",
"return",
"i",
"+",
"1",
"iterations_per_loop_var",
"=",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tpu/python/tpu/tpu_estimator.py#L1654-L1667 | ||
tensorflow/io | 92b44e180674a8af0e12e405530f7343e3e693e4 | tensorflow_io/python/ops/io_dataset.py | python | IODataset.from_audio | (cls, filename, **kwargs) | Creates an `IODataset` from an audio file.
The following audio file formats are supported:
- WAV
- Flac
- Vorbis
- MP3
Args:
filename: A string, the filename of an audio file.
name: A name prefix for the IOTensor (optional).
Returns:
A `IODataset`. | Creates an `IODataset` from an audio file. | [
"Creates",
"an",
"IODataset",
"from",
"an",
"audio",
"file",
"."
] | def from_audio(cls, filename, **kwargs):
"""Creates an `IODataset` from an audio file.
The following audio file formats are supported:
- WAV
- Flac
- Vorbis
- MP3
Args:
filename: A string, the filename of an audio file.
name: A name prefix for the IOTensor (optional).
Returns:
A `IODataset`.
"""
with tf.name_scope(kwargs.get("name", "IOFromAudio")):
return audio_ops.AudioIODataset(filename) | [
"def",
"from_audio",
"(",
"cls",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"kwargs",
".",
"get",
"(",
"\"name\"",
",",
"\"IOFromAudio\"",
")",
")",
":",
"return",
"audio_ops",
".",
"AudioIODataset",
"(",
... | https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/ops/io_dataset.py#L100-L118 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/training/summary_io.py | python | SummaryWriter.add_summary | (self, summary, global_step=None) | Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer
and adds it to the event file.
You can pass the result of evaluating any summary op, using
[`Session.run()`](client.md#Session.run) or
[`Tensor.eval()`](framework.md#Tensor.eval), to this
function. Alternatively, you can pass a `tf.Summary` protocol
buffer that you populate with your own data. The latter is
commonly done to report evaluation results in event files.
Args:
summary: A `Summary` protocol buffer, optionally serialized as a string.
global_step: Number. Optional global step value to record with the
summary. | Adds a `Summary` protocol buffer to the event file. | [
"Adds",
"a",
"Summary",
"protocol",
"buffer",
"to",
"the",
"event",
"file",
"."
] | def add_summary(self, summary, global_step=None):
"""Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer
and adds it to the event file.
You can pass the result of evaluating any summary op, using
[`Session.run()`](client.md#Session.run) or
[`Tensor.eval()`](framework.md#Tensor.eval), to this
function. Alternatively, you can pass a `tf.Summary` protocol
buffer that you populate with your own data. The latter is
commonly done to report evaluation results in event files.
Args:
summary: A `Summary` protocol buffer, optionally serialized as a string.
global_step: Number. Optional global step value to record with the
summary.
"""
if isinstance(summary, bytes):
summ = summary_pb2.Summary()
summ.ParseFromString(summary)
summary = summ
event = event_pb2.Event(wall_time=time.time(), summary=summary)
if global_step is not None:
event.step = int(global_step)
self.add_event(event) | [
"def",
"add_summary",
"(",
"self",
",",
"summary",
",",
"global_step",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"summary",
",",
"bytes",
")",
":",
"summ",
"=",
"summary_pb2",
".",
"Summary",
"(",
")",
"summ",
".",
"ParseFromString",
"(",
"summary"... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/summary_io.py#L127-L152 | ||
borglab/gtsam | a5bee157efce6a0563704bce6a5d188c29817f39 | python/gtsam/utils/logging_optimizer.py | python | optimize | (optimizer, check_convergence, hook) | Given an optimizer and a convergence check, iterate until convergence.
After each iteration, hook(optimizer, error) is called.
After the function, use values and errors to get the result.
Arguments:
optimizer (T): needs an iterate and an error function.
check_convergence: T * float * float -> bool
hook -- hook function to record the error | Given an optimizer and a convergence check, iterate until convergence.
After each iteration, hook(optimizer, error) is called.
After the function, use values and errors to get the result.
Arguments:
optimizer (T): needs an iterate and an error function.
check_convergence: T * float * float -> bool
hook -- hook function to record the error | [
"Given",
"an",
"optimizer",
"and",
"a",
"convergence",
"check",
"iterate",
"until",
"convergence",
".",
"After",
"each",
"iteration",
"hook",
"(",
"optimizer",
"error",
")",
"is",
"called",
".",
"After",
"the",
"function",
"use",
"values",
"and",
"errors",
"... | def optimize(optimizer, check_convergence, hook):
""" Given an optimizer and a convergence check, iterate until convergence.
After each iteration, hook(optimizer, error) is called.
After the function, use values and errors to get the result.
Arguments:
optimizer (T): needs an iterate and an error function.
check_convergence: T * float * float -> bool
hook -- hook function to record the error
"""
# the optimizer is created with default values which incur the error below
current_error = optimizer.error()
hook(optimizer, current_error)
# Iterative loop
while True:
# Do next iteration
optimizer.iterate()
new_error = optimizer.error()
hook(optimizer, new_error)
if check_convergence(optimizer, current_error, new_error):
return
current_error = new_error | [
"def",
"optimize",
"(",
"optimizer",
",",
"check_convergence",
",",
"hook",
")",
":",
"# the optimizer is created with default values which incur the error below",
"current_error",
"=",
"optimizer",
".",
"error",
"(",
")",
"hook",
"(",
"optimizer",
",",
"current_error",
... | https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/python/gtsam/utils/logging_optimizer.py#L11-L32 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/tools/stats-viewer.py | python | StatsViewer.Run | (self) | The main entry-point to running the stats viewer. | The main entry-point to running the stats viewer. | [
"The",
"main",
"entry",
"-",
"point",
"to",
"running",
"the",
"stats",
"viewer",
"."
] | def Run(self):
"""The main entry-point to running the stats viewer."""
try:
self.data = self.MountSharedData()
# OpenWindow blocks until the main window is closed
self.OpenWindow()
finally:
self.CleanUp() | [
"def",
"Run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"data",
"=",
"self",
".",
"MountSharedData",
"(",
")",
"# OpenWindow blocks until the main window is closed",
"self",
".",
"OpenWindow",
"(",
")",
"finally",
":",
"self",
".",
"CleanUp",
"(",
")"
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/stats-viewer.py#L90-L97 | ||
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | tools/extra/extract_seconds.py | python | get_log_created_year | (input_file) | return log_created_year | Get year from log file system timestamp | Get year from log file system timestamp | [
"Get",
"year",
"from",
"log",
"file",
"system",
"timestamp"
] | def get_log_created_year(input_file):
"""Get year from log file system timestamp
"""
log_created_time = os.path.getctime(input_file)
log_created_year = datetime.datetime.fromtimestamp(log_created_time).year
return log_created_year | [
"def",
"get_log_created_year",
"(",
"input_file",
")",
":",
"log_created_time",
"=",
"os",
".",
"path",
".",
"getctime",
"(",
"input_file",
")",
"log_created_year",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"log_created_time",
")",
".",
"year"... | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/tools/extra/extract_seconds.py#L22-L28 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/rolling.py | python | _Window._wrap_result | (self, result, block=None, obj=None) | return result | Wrap a single result. | Wrap a single result. | [
"Wrap",
"a",
"single",
"result",
"."
] | def _wrap_result(self, result, block=None, obj=None):
"""
Wrap a single result.
"""
if obj is None:
obj = self._selected_obj
index = obj.index
if isinstance(result, np.ndarray):
if result.ndim == 1:
from pandas import Series
return Series(result, index, name=obj.name)
return type(obj)(result, index=index, columns=block.columns)
return result | [
"def",
"_wrap_result",
"(",
"self",
",",
"result",
",",
"block",
"=",
"None",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"self",
".",
"_selected_obj",
"index",
"=",
"obj",
".",
"index",
"if",
"isinstance",
"(",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/rolling.py#L283-L300 | |
olliw42/storm32bgc | 99d62a6130ae2950514022f50eb669c45a8cc1ba | old/betacopter/old/betacopter36dev-v003/modules/uavcan/libuavcan/dsdl_compiler/libuavcan_dsdl_compiler/pyratemp.py | python | LoaderString.load | (self, s) | return u | Return template-string as unicode. | Return template-string as unicode. | [
"Return",
"template",
"-",
"string",
"as",
"unicode",
"."
] | def load(self, s):
"""Return template-string as unicode.
"""
if isinstance(s, unicode):
u = s
else:
u = s.decode(self.encoding)
return u | [
"def",
"load",
"(",
"self",
",",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"u",
"=",
"s",
"else",
":",
"u",
"=",
"s",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"return",
"u"
] | https://github.com/olliw42/storm32bgc/blob/99d62a6130ae2950514022f50eb669c45a8cc1ba/old/betacopter/old/betacopter36dev-v003/modules/uavcan/libuavcan/dsdl_compiler/libuavcan_dsdl_compiler/pyratemp.py#L376-L383 | |
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/linalg/sparse_matrix.py | python | SparseMatrixBuilder.print_triplets | (self) | Print the triplets stored in the builder | Print the triplets stored in the builder | [
"Print",
"the",
"triplets",
"stored",
"in",
"the",
"builder"
] | def print_triplets(self):
"""Print the triplets stored in the builder"""
self.ptr.print_triplets() | [
"def",
"print_triplets",
"(",
"self",
")",
":",
"self",
".",
"ptr",
".",
"print_triplets",
"(",
")"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/linalg/sparse_matrix.py#L153-L155 | ||
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/rfcn/tools/train_rfcn_alt_opt_5stage.py | python | rpn_compute_stats | (queue=None, imdb_name=None, cfg=None, rpn_test_prototxt=None) | Compute mean stds for anchors | Compute mean stds for anchors | [
"Compute",
"mean",
"stds",
"for",
"anchors"
] | def rpn_compute_stats(queue=None, imdb_name=None, cfg=None, rpn_test_prototxt=None):
"""Compute mean stds for anchors
"""
cfg.TRAIN.HAS_RPN = True
cfg.TRAIN.BBOX_REG = False # applies only to R-FCN bbox regression
cfg.TRAIN.PROPOSAL_METHOD = 'gt'
cfg.TRAIN.IMS_PER_BATCH = 1
import caffe
_init_caffe(cfg)
# NOTE: the matlab implementation computes proposals on flipped images, too.
# We compute them on the image once and then flip the already computed
# proposals. This might cause a minor loss in mAP (less proposal jittering).
roidb, imdb = get_roidb(imdb_name)
print 'Loaded dataset `{:s}` for proposal generation'.format(imdb.name)
mean_file = os.path.join(imdb.cache_path, imdb.name + '_means.npy')
std_file = os.path.join(imdb.cache_path, imdb.name + '_stds.npy')
if os.path.exists(mean_file) and os.path.exists(std_file):
means = np.load(mean_file)
stds = np.load(std_file)
else:
# Load RPN and configure output directory
rpn_net = caffe.Net(rpn_test_prototxt, caffe.TEST)
# Generate proposals on the imdb
print 'start computing means/stds, it may take several minutes...'
if imdb_name.startswith('coco'):
means, stds = imdb_rpn_compute_stats(rpn_net, imdb, anchor_scales=(4, 8, 16, 32))
else:
means, stds = imdb_rpn_compute_stats(rpn_net, imdb, anchor_scales=(8, 16, 32))
np.save(mean_file, means)
np.save(std_file, stds)
queue.put({'means': means, 'stds': stds}) | [
"def",
"rpn_compute_stats",
"(",
"queue",
"=",
"None",
",",
"imdb_name",
"=",
"None",
",",
"cfg",
"=",
"None",
",",
"rpn_test_prototxt",
"=",
"None",
")",
":",
"cfg",
".",
"TRAIN",
".",
"HAS_RPN",
"=",
"True",
"cfg",
".",
"TRAIN",
".",
"BBOX_REG",
"=",... | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/tools/train_rfcn_alt_opt_5stage.py#L237-L269 | ||
Xilinx/Vitis_Libraries | 4bd100518d93a8842d1678046ad7457f94eb355c | hpc/L3/src/sw/mlp/python_api/xfhpc_L3.py | python | XFHPCManager.sendMat | (self, A, idxKernel, idxDevice) | return self._lib.xfhpcSend(
A, c_ulonglong(
A.size), c_uint(
A.itemsize), idxKernel, idxDevice) | send mat from host to device
Parameters
A: ndarray
matrix in host memory
idxKernel: int
index of kernel to be used
idxDeivce: int
index of local device to be used | send mat from host to device | [
"send",
"mat",
"from",
"host",
"to",
"device"
] | def sendMat(self, A, idxKernel, idxDevice):
'''
send mat from host to device
Parameters
A: ndarray
matrix in host memory
idxKernel: int
index of kernel to be used
idxDeivce: int
index of local device to be used
'''
return self._lib.xfhpcSend(
A, c_ulonglong(
A.size), c_uint(
A.itemsize), idxKernel, idxDevice) | [
"def",
"sendMat",
"(",
"self",
",",
"A",
",",
"idxKernel",
",",
"idxDevice",
")",
":",
"return",
"self",
".",
"_lib",
".",
"xfhpcSend",
"(",
"A",
",",
"c_ulonglong",
"(",
"A",
".",
"size",
")",
",",
"c_uint",
"(",
"A",
".",
"itemsize",
")",
",",
... | https://github.com/Xilinx/Vitis_Libraries/blob/4bd100518d93a8842d1678046ad7457f94eb355c/hpc/L3/src/sw/mlp/python_api/xfhpc_L3.py#L95-L111 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | official-ws/python/bitmex_websocket.py | python | BitMEXWebsocket.__init__ | (self, endpoint, symbol, api_key=None, api_secret=None, subscriptions=DEFAULT_SUBS) | Connect to the websocket and initialize data stores. | Connect to the websocket and initialize data stores. | [
"Connect",
"to",
"the",
"websocket",
"and",
"initialize",
"data",
"stores",
"."
] | def __init__(self, endpoint, symbol, api_key=None, api_secret=None, subscriptions=DEFAULT_SUBS):
'''Connect to the websocket and initialize data stores.'''
self.logger = logging.getLogger(__name__)
self.logger.debug("Initializing WebSocket.")
self.endpoint = endpoint
self.symbol = symbol
if api_key is not None and api_secret is None:
raise ValueError('api_secret is required if api_key is provided')
if api_key is None and api_secret is not None:
raise ValueError('api_key is required if api_secret is provided')
self.api_key = api_key
self.api_secret = api_secret
self.data = {}
self.keys = {}
self.exited = False
# We can subscribe right in the connection querystring, so let's build that.
# Subscribe to all pertinent endpoints
wsURL = self.__get_url(subscriptions)
self.logger.info("Connecting to %s" % wsURL)
self.__connect(wsURL, symbol)
self.logger.info('Connected to WS.')
# Connected. Wait for partials
self.__wait_for_symbol(symbol)
if api_key:
self.__wait_for_account()
self.logger.info('Got all market data. Starting.') | [
"def",
"__init__",
"(",
"self",
",",
"endpoint",
",",
"symbol",
",",
"api_key",
"=",
"None",
",",
"api_secret",
"=",
"None",
",",
"subscriptions",
"=",
"DEFAULT_SUBS",
")",
":",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")... | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/official-ws/python/bitmex_websocket.py#L25-L56 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/html5lib/html5parser.py | python | parse | (doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs) | return p.parse(doc, **kwargs) | Parse an HTML document as a string or file-like object into a tree
:arg doc: the document to parse as a string or file-like object
:arg treebuilder: the treebuilder to use when parsing
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:returns: parsed tree
Example:
>>> from html5lib.html5parser import parse
>>> parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> | Parse an HTML document as a string or file-like object into a tree | [
"Parse",
"an",
"HTML",
"document",
"as",
"a",
"string",
"or",
"file",
"-",
"like",
"object",
"into",
"a",
"tree"
] | def parse(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs):
"""Parse an HTML document as a string or file-like object into a tree
:arg doc: the document to parse as a string or file-like object
:arg treebuilder: the treebuilder to use when parsing
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:returns: parsed tree
Example:
>>> from html5lib.html5parser import parse
>>> parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
"""
tb = treebuilders.getTreeBuilder(treebuilder)
p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)
return p.parse(doc, **kwargs) | [
"def",
"parse",
"(",
"doc",
",",
"treebuilder",
"=",
"\"etree\"",
",",
"namespaceHTMLElements",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"tb",
"=",
"treebuilders",
".",
"getTreeBuilder",
"(",
"treebuilder",
")",
"p",
"=",
"HTMLParser",
"(",
"tb",
... | 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/html5lib/html5parser.py#L26-L46 | |
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | logdevice/ops/ldops/admin_api.py | python | check_impact | (
client: AdminAPI, req: Optional[CheckImpactRequest] = None
) | return await client.checkImpact(req or CheckImpactRequest()) | Wrapper for checkImpact() Thrift method | Wrapper for checkImpact() Thrift method | [
"Wrapper",
"for",
"checkImpact",
"()",
"Thrift",
"method"
] | async def check_impact(
client: AdminAPI, req: Optional[CheckImpactRequest] = None
) -> CheckImpactResponse:
"""
Wrapper for checkImpact() Thrift method
"""
return await client.checkImpact(req or CheckImpactRequest()) | [
"async",
"def",
"check_impact",
"(",
"client",
":",
"AdminAPI",
",",
"req",
":",
"Optional",
"[",
"CheckImpactRequest",
"]",
"=",
"None",
")",
"->",
"CheckImpactResponse",
":",
"return",
"await",
"client",
".",
"checkImpact",
"(",
"req",
"or",
"CheckImpactRequ... | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/logdevice/ops/ldops/admin_api.py#L184-L190 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/release/check_clusterfuzz.py | python | APIRequest | (key, **params) | return None | Send a request to the clusterfuzz api.
Returns a json dict of the response. | Send a request to the clusterfuzz api. | [
"Send",
"a",
"request",
"to",
"the",
"clusterfuzz",
"api",
"."
] | def APIRequest(key, **params):
"""Send a request to the clusterfuzz api.
Returns a json dict of the response.
"""
params["api_key"] = key
params = urllib.urlencode(params)
headers = {"Content-type": "application/x-www-form-urlencoded"}
try:
conn = httplib.HTTPSConnection(HOSTNAME)
conn.request("POST", "/_api/", params, headers)
response = conn.getresponse()
# Never leak "data" into public logs.
data = response.read()
except:
raise Exception("ERROR: Connection problem.")
try:
return json.loads(data)
except:
raise Exception("ERROR: Could not read response. Is your key valid?")
return None | [
"def",
"APIRequest",
"(",
"key",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"\"api_key\"",
"]",
"=",
"key",
"params",
"=",
"urllib",
".",
"urlencode",
"(",
"params",
")",
"headers",
"=",
"{",
"\"Content-type\"",
":",
"\"application/x-www-form-urlencod... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/release/check_clusterfuzz.py#L150-L177 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/compiler.py | python | UndeclaredNameVisitor.visit_Block | (self, node) | Stop visiting a blocks. | Stop visiting a blocks. | [
"Stop",
"visiting",
"a",
"blocks",
"."
] | def visit_Block(self, node):
"""Stop visiting a blocks.""" | [
"def",
"visit_Block",
"(",
"self",
",",
"node",
")",
":"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/compiler.py#L233-L234 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.winfo_screenwidth | (self) | return getint(
self.tk.call('winfo', 'screenwidth', self._w)) | Return the number of pixels of the width of the screen of
this widget in pixel. | Return the number of pixels of the width of the screen of
this widget in pixel. | [
"Return",
"the",
"number",
"of",
"pixels",
"of",
"the",
"width",
"of",
"the",
"screen",
"of",
"this",
"widget",
"in",
"pixel",
"."
] | def winfo_screenwidth(self):
"""Return the number of pixels of the width of the screen of
this widget in pixel."""
return getint(
self.tk.call('winfo', 'screenwidth', self._w)) | [
"def",
"winfo_screenwidth",
"(",
"self",
")",
":",
"return",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'screenwidth'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L881-L885 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/fields.py | python | BaseSchemaField.definition | (self) | return {
'AttributeName': self.name,
'AttributeType': self.data_type,
} | Returns the attribute definition structure DynamoDB expects.
Example::
>>> field.definition()
{
'AttributeName': 'username',
'AttributeType': 'S',
} | Returns the attribute definition structure DynamoDB expects. | [
"Returns",
"the",
"attribute",
"definition",
"structure",
"DynamoDB",
"expects",
"."
] | def definition(self):
"""
Returns the attribute definition structure DynamoDB expects.
Example::
>>> field.definition()
{
'AttributeName': 'username',
'AttributeType': 'S',
}
"""
return {
'AttributeName': self.name,
'AttributeType': self.data_type,
} | [
"def",
"definition",
"(",
"self",
")",
":",
"return",
"{",
"'AttributeName'",
":",
"self",
".",
"name",
",",
"'AttributeType'",
":",
"self",
".",
"data_type",
",",
"}"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/fields.py#L27-L43 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/wrap/grad_reducer.py | python | _tensors_allreduce_with_sparse | (degree, mean, allgather, allreduce, allreduce_filter, grad) | return grad | Apply allgather on gradient instead of allreduce for sparse feature.
Allgather is a communication operation used for distributed deep learning.
Args:
degree (int): The mean coefficient.
mean (bool): When mean is true, the mean coefficient (degree) would apply on gradients.
allgather (Primitive): The communication operator for sparse gradients.
allreduce (Primitive): The communication operator for gradients.
allreduce_filter (bool): When it is true, allgather would apply.
grad (tuple): The indices, gradient tensor and tensor_shape before operation.
Returns:
RowTensor, the gradient after operation. | Apply allgather on gradient instead of allreduce for sparse feature.
Allgather is a communication operation used for distributed deep learning. | [
"Apply",
"allgather",
"on",
"gradient",
"instead",
"of",
"allreduce",
"for",
"sparse",
"feature",
".",
"Allgather",
"is",
"a",
"communication",
"operation",
"used",
"for",
"distributed",
"deep",
"learning",
"."
] | def _tensors_allreduce_with_sparse(degree, mean, allgather, allreduce, allreduce_filter, grad):
"""
Apply allgather on gradient instead of allreduce for sparse feature.
Allgather is a communication operation used for distributed deep learning.
Args:
degree (int): The mean coefficient.
mean (bool): When mean is true, the mean coefficient (degree) would apply on gradients.
allgather (Primitive): The communication operator for sparse gradients.
allreduce (Primitive): The communication operator for gradients.
allreduce_filter (bool): When it is true, allgather would apply.
grad (tuple): The indices, gradient tensor and tensor_shape before operation.
Returns:
RowTensor, the gradient after operation.
"""
if allreduce_filter:
indices = allgather(grad.indices)
dout = allgather(grad.values)
if mean:
dout = F.tensor_mul(dout, F.cast(degree, F.dtype(dout)))
grad = RowTensor(indices, dout, grad.dense_shape)
return grad | [
"def",
"_tensors_allreduce_with_sparse",
"(",
"degree",
",",
"mean",
",",
"allgather",
",",
"allreduce",
",",
"allreduce_filter",
",",
"grad",
")",
":",
"if",
"allreduce_filter",
":",
"indices",
"=",
"allgather",
"(",
"grad",
".",
"indices",
")",
"dout",
"=",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/wrap/grad_reducer.py#L158-L180 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | Target.FinalOutput | (self) | return self.bundle or self.binary or self.actions_stamp | Return the last output of the target, which depends on all prior
steps. | Return the last output of the target, which depends on all prior
steps. | [
"Return",
"the",
"last",
"output",
"of",
"the",
"target",
"which",
"depends",
"on",
"all",
"prior",
"steps",
"."
] | def FinalOutput(self):
"""Return the last output of the target, which depends on all prior
steps."""
return self.bundle or self.binary or self.actions_stamp | [
"def",
"FinalOutput",
"(",
"self",
")",
":",
"return",
"self",
".",
"bundle",
"or",
"self",
".",
"binary",
"or",
"self",
".",
"actions_stamp"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L182-L185 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGridManager.GetIterator | (*args) | return _propgrid.PropertyGridManager_GetIterator(*args) | GetIterator(self, int flags=PG_ITERATE_DEFAULT, PGProperty firstProp=None) -> PropertyGridIterator
GetIterator(self, int flags=PG_ITERATE_DEFAULT, PGProperty firstProp=None) -> PropertyGridConstIterator
GetIterator(self, int flags, int startPos) -> PropertyGridIterator
GetIterator(self, int flags, int startPos) -> PropertyGridConstIterator | GetIterator(self, int flags=PG_ITERATE_DEFAULT, PGProperty firstProp=None) -> PropertyGridIterator
GetIterator(self, int flags=PG_ITERATE_DEFAULT, PGProperty firstProp=None) -> PropertyGridConstIterator
GetIterator(self, int flags, int startPos) -> PropertyGridIterator
GetIterator(self, int flags, int startPos) -> PropertyGridConstIterator | [
"GetIterator",
"(",
"self",
"int",
"flags",
"=",
"PG_ITERATE_DEFAULT",
"PGProperty",
"firstProp",
"=",
"None",
")",
"-",
">",
"PropertyGridIterator",
"GetIterator",
"(",
"self",
"int",
"flags",
"=",
"PG_ITERATE_DEFAULT",
"PGProperty",
"firstProp",
"=",
"None",
")"... | def GetIterator(*args):
"""
GetIterator(self, int flags=PG_ITERATE_DEFAULT, PGProperty firstProp=None) -> PropertyGridIterator
GetIterator(self, int flags=PG_ITERATE_DEFAULT, PGProperty firstProp=None) -> PropertyGridConstIterator
GetIterator(self, int flags, int startPos) -> PropertyGridIterator
GetIterator(self, int flags, int startPos) -> PropertyGridConstIterator
"""
return _propgrid.PropertyGridManager_GetIterator(*args) | [
"def",
"GetIterator",
"(",
"*",
"args",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_GetIterator",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3468-L3475 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | base/android/jni_generator/jni_generator.py | python | InlHeaderFileGenerator.GetJNINativeMethodsString | (self) | return self.SubstituteNativeMethods(template) | Returns the implementation of the array of native methods. | Returns the implementation of the array of native methods. | [
"Returns",
"the",
"implementation",
"of",
"the",
"array",
"of",
"native",
"methods",
"."
] | def GetJNINativeMethodsString(self):
"""Returns the implementation of the array of native methods."""
template = Template("""\
static const JNINativeMethod kMethods${JAVA_CLASS}[] = {
${KMETHODS}
};
""")
return self.SubstituteNativeMethods(template) | [
"def",
"GetJNINativeMethodsString",
"(",
"self",
")",
":",
"template",
"=",
"Template",
"(",
"\"\"\"\\\nstatic const JNINativeMethod kMethods${JAVA_CLASS}[] = {\n${KMETHODS}\n};\n\"\"\"",
")",
"return",
"self",
".",
"SubstituteNativeMethods",
"(",
"template",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/base/android/jni_generator/jni_generator.py#L749-L756 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Geometry.Segmentize | (self, *args) | return _ogr.Geometry_Segmentize(self, *args) | r"""
Segmentize(Geometry self, double dfMaxLength)
void OGR_G_Segmentize(OGRGeometryH
hGeom, double dfMaxLength)
Modify the geometry such it has no segment longer then the given
distance.
Interpolated points will have Z and M values (if needed) set to 0.
Distance computation is performed in 2d only.
This function is the same as the CPP method OGRGeometry::segmentize().
Parameters:
-----------
hGeom: handle on the geometry to segmentize
dfMaxLength: the maximum distance between 2 points after
segmentization | r"""
Segmentize(Geometry self, double dfMaxLength)
void OGR_G_Segmentize(OGRGeometryH
hGeom, double dfMaxLength) | [
"r",
"Segmentize",
"(",
"Geometry",
"self",
"double",
"dfMaxLength",
")",
"void",
"OGR_G_Segmentize",
"(",
"OGRGeometryH",
"hGeom",
"double",
"dfMaxLength",
")"
] | def Segmentize(self, *args):
r"""
Segmentize(Geometry self, double dfMaxLength)
void OGR_G_Segmentize(OGRGeometryH
hGeom, double dfMaxLength)
Modify the geometry such it has no segment longer then the given
distance.
Interpolated points will have Z and M values (if needed) set to 0.
Distance computation is performed in 2d only.
This function is the same as the CPP method OGRGeometry::segmentize().
Parameters:
-----------
hGeom: handle on the geometry to segmentize
dfMaxLength: the maximum distance between 2 points after
segmentization
"""
return _ogr.Geometry_Segmentize(self, *args) | [
"def",
"Segmentize",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Geometry_Segmentize",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L7084-L7106 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py | python | Leaf.prefix | (self) | return self._prefix | The whitespace and comments preceding this token in the input. | The whitespace and comments preceding this token in the input. | [
"The",
"whitespace",
"and",
"comments",
"preceding",
"this",
"token",
"in",
"the",
"input",
"."
] | def prefix(self):
"""
The whitespace and comments preceding this token in the input.
"""
return self._prefix | [
"def",
"prefix",
"(",
"self",
")",
":",
"return",
"self",
".",
"_prefix"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py#L384-L388 | |
nasa/astrobee | 9241e67e6692810d6e275abb3165b6d02f4ca5ef | scripts/git/cpplint.py | python | CheckRedundantOverrideOrFinal | (filename, clean_lines, linenum, error) | Check if line contains a redundant "override" or "final" virt-specifier.
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 if line contains a redundant "override" or "final" virt-specifier. | [
"Check",
"if",
"line",
"contains",
"a",
"redundant",
"override",
"or",
"final",
"virt",
"-",
"specifier",
"."
] | def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
"""Check if line contains a redundant "override" or "final" virt-specifier.
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 at most one of "override" or "final" is present, not both
line = clean_lines.elided[linenum]
if Search(r"\boverride\b", line) and Search(r"\bfinal\b", line):
error(
filename,
linenum,
"readability/inheritance",
4,
(
'"override" is redundant since function is '
'already declared as "final"'
),
) | [
"def",
"CheckRedundantOverrideOrFinal",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Check that at most one of \"override\" or \"final\" is present, not both",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search... | https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L6499-L6520 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py | python | ispackage | (path) | return False | Guess whether a path refers to a package directory. | Guess whether a path refers to a package directory. | [
"Guess",
"whether",
"a",
"path",
"refers",
"to",
"a",
"package",
"directory",
"."
] | def ispackage(path):
"""Guess whether a path refers to a package directory."""
if os.path.isdir(path):
for ext in ('.py', '.pyc', '.pyo'):
if os.path.isfile(os.path.join(path, '__init__' + ext)):
return True
return False | [
"def",
"ispackage",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"for",
"ext",
"in",
"(",
"'.py'",
",",
"'.pyc'",
",",
"'.pyo'",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py#L187-L193 | |
cmu-db/noisepage | 79276e68fe83322f1249e8a8be96bd63c583ae56 | build-support/cpplint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
"."... | https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L1379-L1391 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/linesearch.py | python | scalar_search_wolfe1 | (phi, derphi, phi0=None, old_phi0=None, derphi0=None,
c1=1e-4, c2=0.9,
amax=50, amin=1e-8, xtol=1e-14) | return stp, phi1, phi0 | Scalar function search for alpha that satisfies strong Wolfe conditions
alpha > 0 is assumed to be a descent direction.
Parameters
----------
phi : callable phi(alpha)
Function at point `alpha`
derphi : callable dphi(alpha)
Derivative `d phi(alpha)/ds`. Returns a scalar.
phi0 : float, optional
Value of `f` at 0
old_phi0 : float, optional
Value of `f` at the previous point
derphi0 : float, optional
Value `derphi` at 0
c1, c2 : float, optional
Wolfe parameters
amax, amin : float, optional
Maximum and minimum step size
xtol : float, optional
Relative tolerance for an acceptable step.
Returns
-------
alpha : float
Step size, or None if no suitable step was found
phi : float
Value of `phi` at the new point `alpha`
phi0 : float
Value of `phi` at `alpha=0`
Notes
-----
Uses routine DCSRCH from MINPACK. | Scalar function search for alpha that satisfies strong Wolfe conditions | [
"Scalar",
"function",
"search",
"for",
"alpha",
"that",
"satisfies",
"strong",
"Wolfe",
"conditions"
] | def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None,
c1=1e-4, c2=0.9,
amax=50, amin=1e-8, xtol=1e-14):
"""
Scalar function search for alpha that satisfies strong Wolfe conditions
alpha > 0 is assumed to be a descent direction.
Parameters
----------
phi : callable phi(alpha)
Function at point `alpha`
derphi : callable dphi(alpha)
Derivative `d phi(alpha)/ds`. Returns a scalar.
phi0 : float, optional
Value of `f` at 0
old_phi0 : float, optional
Value of `f` at the previous point
derphi0 : float, optional
Value `derphi` at 0
c1, c2 : float, optional
Wolfe parameters
amax, amin : float, optional
Maximum and minimum step size
xtol : float, optional
Relative tolerance for an acceptable step.
Returns
-------
alpha : float
Step size, or None if no suitable step was found
phi : float
Value of `phi` at the new point `alpha`
phi0 : float
Value of `phi` at `alpha=0`
Notes
-----
Uses routine DCSRCH from MINPACK.
"""
if phi0 is None:
phi0 = phi(0.)
if derphi0 is None:
derphi0 = derphi(0.)
if old_phi0 is not None and derphi0 != 0:
alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0)
if alpha1 < 0:
alpha1 = 1.0
else:
alpha1 = 1.0
phi1 = phi0
derphi1 = derphi0
isave = np.zeros((2,), np.intc)
dsave = np.zeros((13,), float)
task = b'START'
maxiter = 100
for i in xrange(maxiter):
stp, phi1, derphi1, task = minpack2.dcsrch(alpha1, phi1, derphi1,
c1, c2, xtol, task,
amin, amax, isave, dsave)
if task[:2] == b'FG':
alpha1 = stp
phi1 = phi(stp)
derphi1 = derphi(stp)
else:
break
else:
# maxiter reached, the line search did not converge
stp = None
if task[:5] == b'ERROR' or task[:4] == b'WARN':
stp = None # failed
return stp, phi1, phi0 | [
"def",
"scalar_search_wolfe1",
"(",
"phi",
",",
"derphi",
",",
"phi0",
"=",
"None",
",",
"old_phi0",
"=",
"None",
",",
"derphi0",
"=",
"None",
",",
"c1",
"=",
"1e-4",
",",
"c2",
"=",
"0.9",
",",
"amax",
"=",
"50",
",",
"amin",
"=",
"1e-8",
",",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/linesearch.py#L106-L185 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/converters/onnx/_operators_nd.py | python | _convert_conv | (builder, node, graph, err) | convert to CoreML Convolution Layer:
https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L1418 | convert to CoreML Convolution Layer:
https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L1418 | [
"convert",
"to",
"CoreML",
"Convolution",
"Layer",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"apple",
"/",
"coremltools",
"/",
"blob",
"/",
"655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492",
"/",
"mlmodel",
"/",
"format",
"/",
"NeuralNetwork",
".",
"proto#L14... | def _convert_conv(builder, node, graph, err):
"""
convert to CoreML Convolution Layer:
https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L1418
"""
params_dict = dict()
params_dict["is_deconv"] = False
if node.op_type.endswith("Transpose"):
params_dict["is_deconv"] = True
# get weights for convolution
weight_name = node.inputs[1]
W = None
if weight_name in node.input_tensors:
W = node.input_tensors[weight_name]
params_dict["w_shape"] = W.shape
else:
# W is provided as a input
# Make W compatible for CoreML Conv Layer
# W ONNX format: OC x KC x H x W
# Expected CoreML Format: H x W x KC x OC
W_name = node.inputs[1]
W_shape = graph.shape_dict[W_name]
W_rank = len(W_shape)
params_dict["w_shape"] = W_shape
if W_rank == 3:
expanded_node_name = node.name + "_" + W_name + "_expanded"
builder.add_expand_dims(
name=node.name + "_w_expand",
input_name=W_name,
output_name=expanded_node_name,
axes=[-2],
)
W_name = expanded_node_name
# Now Permute the W tensor
W_transpose_axes = [2, 3, 1, 0]
# If ConvTranpose then, Kernel and Output channels are shuffled
if params_dict["is_deconv"]:
W_transpose_axes = [2, 3, 0, 1]
builder.add_transpose(
name=node.name + "_w_transpose",
axes=W_transpose_axes,
input_name=W_name,
output_name=W_name + "_transposed",
)
W_name = W_name + "_transposed"
node.inputs[1] = W_name
params_dict["W"] = W
bias = None
if len(node.inputs) > 2:
bias = node.input_tensors[node.inputs[2]]
params_dict["bias"] = bias
params_dict["groups"] = node.attrs.get("group", 1)
_add_conv_like_op(
_add_conv, _get_conv_params, params_dict, builder, node, graph, err
) | [
"def",
"_convert_conv",
"(",
"builder",
",",
"node",
",",
"graph",
",",
"err",
")",
":",
"params_dict",
"=",
"dict",
"(",
")",
"params_dict",
"[",
"\"is_deconv\"",
"]",
"=",
"False",
"if",
"node",
".",
"op_type",
".",
"endswith",
"(",
"\"Transpose\"",
")... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/onnx/_operators_nd.py#L594-L653 | ||
unitusdev/unitus | 4cd523cb5b46cf224bbed7a653618d2b9e832455 | contrib/devtools/security-check.py | python | check_PE_NX | (executable) | return (bits & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) == IMAGE_DLL_CHARACTERISTICS_NX_COMPAT | NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP) | NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP) | [
"NX",
":",
"DllCharacteristics",
"bit",
"0x100",
"signifies",
"nxcompat",
"(",
"DEP",
")"
] | def check_PE_NX(executable):
'''NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)'''
(arch,bits) = get_PE_dll_characteristics(executable)
return (bits & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) == IMAGE_DLL_CHARACTERISTICS_NX_COMPAT | [
"def",
"check_PE_NX",
"(",
"executable",
")",
":",
"(",
"arch",
",",
"bits",
")",
"=",
"get_PE_dll_characteristics",
"(",
"executable",
")",
"return",
"(",
"bits",
"&",
"IMAGE_DLL_CHARACTERISTICS_NX_COMPAT",
")",
"==",
"IMAGE_DLL_CHARACTERISTICS_NX_COMPAT"
] | https://github.com/unitusdev/unitus/blob/4cd523cb5b46cf224bbed7a653618d2b9e832455/contrib/devtools/security-check.py#L161-L164 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/layer1.py | python | Layer1.validate_configuration_settings | (self, application_name,
option_settings, template_name=None,
environment_name=None) | return self._get_response('ValidateConfigurationSettings', params) | Takes a set of configuration settings and either a
configuration template or environment, and determines whether
those values are valid. This action returns a list of messages
indicating any errors or warnings associated with the selection
of option values.
:type application_name: string
:param application_name: The name of the application that the
configuration template or environment belongs to.
:type template_name: string
:param template_name: The name of the configuration template to
validate the settings against. Condition: You cannot specify both
this and an environment name.
:type environment_name: string
:param environment_name: The name of the environment to validate the
settings against. Condition: You cannot specify both this and a
configuration template name.
:type option_settings: list
:param option_settings: A list of the options and desired values to
evaluate.
:raises: InsufficientPrivilegesException | Takes a set of configuration settings and either a
configuration template or environment, and determines whether
those values are valid. This action returns a list of messages
indicating any errors or warnings associated with the selection
of option values. | [
"Takes",
"a",
"set",
"of",
"configuration",
"settings",
"and",
"either",
"a",
"configuration",
"template",
"or",
"environment",
"and",
"determines",
"whether",
"those",
"values",
"are",
"valid",
".",
"This",
"action",
"returns",
"a",
"list",
"of",
"messages",
... | def validate_configuration_settings(self, application_name,
option_settings, template_name=None,
environment_name=None):
"""
Takes a set of configuration settings and either a
configuration template or environment, and determines whether
those values are valid. This action returns a list of messages
indicating any errors or warnings associated with the selection
of option values.
:type application_name: string
:param application_name: The name of the application that the
configuration template or environment belongs to.
:type template_name: string
:param template_name: The name of the configuration template to
validate the settings against. Condition: You cannot specify both
this and an environment name.
:type environment_name: string
:param environment_name: The name of the environment to validate the
settings against. Condition: You cannot specify both this and a
configuration template name.
:type option_settings: list
:param option_settings: A list of the options and desired values to
evaluate.
:raises: InsufficientPrivilegesException
"""
params = {'ApplicationName': application_name}
self._build_list_params(params, option_settings,
'OptionSettings.member',
('Namespace', 'OptionName', 'Value'))
if template_name:
params['TemplateName'] = template_name
if environment_name:
params['EnvironmentName'] = environment_name
return self._get_response('ValidateConfigurationSettings', params) | [
"def",
"validate_configuration_settings",
"(",
"self",
",",
"application_name",
",",
"option_settings",
",",
"template_name",
"=",
"None",
",",
"environment_name",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'ApplicationName'",
":",
"application_name",
"}",
"self",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/layer1.py#L1146-L1184 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/gluon/parameter.py | python | Parameter.grad | (self, ctx=None) | return self._check_and_get(self._grad, ctx) | Returns a gradient buffer for this parameter on one context.
Parameters
----------
ctx : Context
Desired context. | Returns a gradient buffer for this parameter on one context. | [
"Returns",
"a",
"gradient",
"buffer",
"for",
"this",
"parameter",
"on",
"one",
"context",
"."
] | def grad(self, ctx=None):
"""Returns a gradient buffer for this parameter on one context.
Parameters
----------
ctx : Context
Desired context.
"""
if self._data is not None and self._grad is None:
raise RuntimeError(
"Cannot get gradient array for Parameter '%s' " \
"because grad_req='null'"%(self.name))
return self._check_and_get(self._grad, ctx) | [
"def",
"grad",
"(",
"self",
",",
"ctx",
"=",
"None",
")",
":",
"if",
"self",
".",
"_data",
"is",
"not",
"None",
"and",
"self",
".",
"_grad",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot get gradient array for Parameter '%s' \"",
"\"because grad_r... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/parameter.py#L560-L572 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/pyshell.py | python | fix_x11_paste | (root) | Make paste replace selection on x11. See issue #5124. | Make paste replace selection on x11. See issue #5124. | [
"Make",
"paste",
"replace",
"selection",
"on",
"x11",
".",
"See",
"issue",
"#5124",
"."
] | def fix_x11_paste(root):
"Make paste replace selection on x11. See issue #5124."
if root._windowingsystem == 'x11':
for cls in 'Text', 'Entry', 'Spinbox':
root.bind_class(
cls,
'<<Paste>>',
'catch {%W delete sel.first sel.last}\n' +
root.bind_class(cls, '<<Paste>>')) | [
"def",
"fix_x11_paste",
"(",
"root",
")",
":",
"if",
"root",
".",
"_windowingsystem",
"==",
"'x11'",
":",
"for",
"cls",
"in",
"'Text'",
",",
"'Entry'",
",",
"'Spinbox'",
":",
"root",
".",
"bind_class",
"(",
"cls",
",",
"'<<Paste>>'",
",",
"'catch {%W delet... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/pyshell.py#L1324-L1332 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Parser/asdl.py | python | ASDLParser.p_field_4 | (self, (type, _)) | return Field(type, seq=True) | field ::= Id * | field ::= Id * | [
"field",
"::",
"=",
"Id",
"*"
] | def p_field_4(self, (type, _)):
" field ::= Id * "
return Field(type, seq=True) | [
"def",
"p_field_4",
"(",
"self",
",",
"(",
"type",
",",
"_",
")",
")",
":",
"return",
"Field",
"(",
"type",
",",
"seq",
"=",
"True",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Parser/asdl.py#L213-L215 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/candidate_sampling_ops.py | python | learned_unigram_candidate_sampler | (true_classes, num_true, num_sampled,
unique, range_max, seed=None, name=None) | return gen_candidate_sampling_ops._learned_unigram_candidate_sampler(
true_classes, num_true, num_sampled, unique, range_max, seed=seed1,
seed2=seed2, name=name) | Samples a set of classes from a distribution learned during training.
This operation randomly samples a tensor of sampled classes
(`sampled_candidates`) from the range of integers `[0, range_max)`.
The elements of `sampled_candidates` are drawn without replacement
(if `unique=True`) or with replacement (if `unique=False`) from
the base distribution.
The base distribution for this operation is constructed on the fly
during training. It is a unigram distribution over the target
classes seen so far during training. Every integer in `[0, range_max)`
begins with a weight of 1, and is incremented by 1 each time it is
seen as a target class. The base distribution is not saved to checkpoints,
so it is reset when the model is reloaded.
In addition, this operation returns tensors `true_expected_count`
and `sampled_expected_count` representing the number of times each
of the target classes (`true_classes`) and the sampled
classes (`sampled_candidates`) is expected to occur in an average
tensor of sampled classes. These values correspond to `Q(y|x)`
defined in [this
document](http://www.tensorflow.org/extras/candidate_sampling.pdf).
If `unique=True`, then these are post-rejection probabilities and we
compute them approximately.
Args:
true_classes: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes.
num_true: An `int`. The number of target classes per training example.
num_sampled: An `int`. The number of classes to randomly sample per batch.
unique: A `bool`. Determines whether all sampled classes in a batch are
unique.
range_max: An `int`. The number of possible classes.
seed: An `int`. An operation-specific seed. Default is 0.
name: A name for the operation (optional).
Returns:
sampled_candidates: A tensor of type `int64` and shape `[num_sampled]`.
The sampled classes.
true_expected_count: A tensor of type `float`. Same shape as
`true_classes`. The expected counts under the sampling distribution
of each of `true_classes`.
sampled_expected_count: A tensor of type `float`. Same shape as
`sampled_candidates`. The expected counts under the sampling distribution
of each of `sampled_candidates`. | Samples a set of classes from a distribution learned during training. | [
"Samples",
"a",
"set",
"of",
"classes",
"from",
"a",
"distribution",
"learned",
"during",
"training",
"."
] | def learned_unigram_candidate_sampler(true_classes, num_true, num_sampled,
unique, range_max, seed=None, name=None):
"""Samples a set of classes from a distribution learned during training.
This operation randomly samples a tensor of sampled classes
(`sampled_candidates`) from the range of integers `[0, range_max)`.
The elements of `sampled_candidates` are drawn without replacement
(if `unique=True`) or with replacement (if `unique=False`) from
the base distribution.
The base distribution for this operation is constructed on the fly
during training. It is a unigram distribution over the target
classes seen so far during training. Every integer in `[0, range_max)`
begins with a weight of 1, and is incremented by 1 each time it is
seen as a target class. The base distribution is not saved to checkpoints,
so it is reset when the model is reloaded.
In addition, this operation returns tensors `true_expected_count`
and `sampled_expected_count` representing the number of times each
of the target classes (`true_classes`) and the sampled
classes (`sampled_candidates`) is expected to occur in an average
tensor of sampled classes. These values correspond to `Q(y|x)`
defined in [this
document](http://www.tensorflow.org/extras/candidate_sampling.pdf).
If `unique=True`, then these are post-rejection probabilities and we
compute them approximately.
Args:
true_classes: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes.
num_true: An `int`. The number of target classes per training example.
num_sampled: An `int`. The number of classes to randomly sample per batch.
unique: A `bool`. Determines whether all sampled classes in a batch are
unique.
range_max: An `int`. The number of possible classes.
seed: An `int`. An operation-specific seed. Default is 0.
name: A name for the operation (optional).
Returns:
sampled_candidates: A tensor of type `int64` and shape `[num_sampled]`.
The sampled classes.
true_expected_count: A tensor of type `float`. Same shape as
`true_classes`. The expected counts under the sampling distribution
of each of `true_classes`.
sampled_expected_count: A tensor of type `float`. Same shape as
`sampled_candidates`. The expected counts under the sampling distribution
of each of `sampled_candidates`.
"""
seed1, seed2 = random_seed.get_seed(seed)
return gen_candidate_sampling_ops._learned_unigram_candidate_sampler(
true_classes, num_true, num_sampled, unique, range_max, seed=seed1,
seed2=seed2, name=name) | [
"def",
"learned_unigram_candidate_sampler",
"(",
"true_classes",
",",
"num_true",
",",
"num_sampled",
",",
"unique",
",",
"range_max",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"seed1",
",",
"seed2",
"=",
"random_seed",
".",
"get_seed",
"... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/candidate_sampling_ops.py#L139-L192 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/generator/analyzer.py | python | CalculateVariables | (default_variables, params) | Calculate additional variables for use in the build (called by gyp). | Calculate additional variables for use in the build (called by gyp). | [
"Calculate",
"additional",
"variables",
"for",
"use",
"in",
"the",
"build",
"(",
"called",
"by",
"gyp",
")",
"."
] | def CalculateVariables(default_variables, params):
"""Calculate additional variables for use in the build (called by gyp)."""
flavor = gyp.common.GetFlavor(params)
if flavor == "mac":
default_variables.setdefault("OS", "mac")
elif flavor == "win":
default_variables.setdefault("OS", "win")
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
else:
operating_system = flavor
if flavor == "android":
operating_system = "linux" # Keep this legacy behavior for now.
default_variables.setdefault("OS", operating_system) | [
"def",
"CalculateVariables",
"(",
"default_variables",
",",
"params",
")",
":",
"flavor",
"=",
"gyp",
".",
"common",
".",
"GetFlavor",
"(",
"params",
")",
"if",
"flavor",
"==",
"\"mac\"",
":",
"default_variables",
".",
"setdefault",
"(",
"\"OS\"",
",",
"\"ma... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/analyzer.py#L614-L626 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/input.py | python | ParallelState.LoadTargetBuildFileCallback | (self, result) | Handle the results of running LoadTargetBuildFile in another process. | Handle the results of running LoadTargetBuildFile in another process. | [
"Handle",
"the",
"results",
"of",
"running",
"LoadTargetBuildFile",
"in",
"another",
"process",
"."
] | def LoadTargetBuildFileCallback(self, result):
"""Handle the results of running LoadTargetBuildFile in another process.
"""
self.condition.acquire()
if not result:
self.error = True
self.condition.notify()
self.condition.release()
return
(build_file_path0, build_file_data0, dependencies0) = result
self.data[build_file_path0] = build_file_data0
self.data['target_build_files'].add(build_file_path0)
for new_dependency in dependencies0:
if new_dependency not in self.scheduled:
self.scheduled.add(new_dependency)
self.dependencies.append(new_dependency)
self.pending -= 1
self.condition.notify()
self.condition.release() | [
"def",
"LoadTargetBuildFileCallback",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"condition",
".",
"acquire",
"(",
")",
"if",
"not",
"result",
":",
"self",
".",
"error",
"=",
"True",
"self",
".",
"condition",
".",
"notify",
"(",
")",
"self",
".... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/input.py#L553-L571 | ||
GeometryCollective/boundary-first-flattening | 8250e5a0e85980ec50b5e8aa8f49dd6519f915cd | deps/nanogui/ext/pybind11/tools/clang/cindex.py | python | File.from_name | (translation_unit, file_name) | return File(conf.lib.clang_getFile(translation_unit, file_name)) | Retrieve a file handle within the given translation unit. | Retrieve a file handle within the given translation unit. | [
"Retrieve",
"a",
"file",
"handle",
"within",
"the",
"given",
"translation",
"unit",
"."
] | def from_name(translation_unit, file_name):
"""Retrieve a file handle within the given translation unit."""
return File(conf.lib.clang_getFile(translation_unit, file_name)) | [
"def",
"from_name",
"(",
"translation_unit",
",",
"file_name",
")",
":",
"return",
"File",
"(",
"conf",
".",
"lib",
".",
"clang_getFile",
"(",
"translation_unit",
",",
"file_name",
")",
")"
] | https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/ext/pybind11/tools/clang/cindex.py#L2677-L2679 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/state_ops.py | python | batch_scatter_update | (ref, indices, updates, use_locking=True, name=None) | Generalization of `tf.compat.v1.scatter_update` to axis different than 0.
Analogous to `batch_gather`. This assumes that `ref`, `indices` and `updates`
have a series of leading dimensions that are the same for all of them, and the
updates are performed on the last dimension of indices. In other words, the
dimensions should be the following:
`num_prefix_dims = indices.ndims - 1`
`batch_dim = num_prefix_dims + 1`
`updates.shape = indices.shape + var.shape[batch_dim:]`
where
`updates.shape[:num_prefix_dims]`
`== indices.shape[:num_prefix_dims]`
`== var.shape[:num_prefix_dims]`
And the operation performed can be expressed as:
`var[i_1, ..., i_n, indices[i_1, ..., i_n, j]] = updates[i_1, ..., i_n, j]`
When indices is a 1D tensor, this operation is equivalent to
`tf.compat.v1.scatter_update`.
To avoid this operation there would be 2 alternatives:
1) Reshaping the variable by merging the first `ndims` dimensions. However,
this is not possible because `tf.reshape` returns a Tensor, which we
cannot use `tf.compat.v1.scatter_update` on.
2) Looping over the first `ndims` of the variable and using
`tf.compat.v1.scatter_update` on the subtensors that result of slicing the
first
dimension. This is a valid option for `ndims = 1`, but less efficient than
this implementation.
See also `tf.compat.v1.scatter_update` and `tf.compat.v1.scatter_nd_update`.
Args:
ref: `Variable` to scatter onto.
indices: Tensor containing indices as described above.
updates: Tensor of updates to apply to `ref`.
use_locking: Boolean indicating whether to lock the writing operation.
name: Optional scope name string.
Returns:
Ref to `variable` after it has been modified.
Raises:
ValueError: If the initial `ndims` of `ref`, `indices`, and `updates` are
not the same. | Generalization of `tf.compat.v1.scatter_update` to axis different than 0. | [
"Generalization",
"of",
"tf",
".",
"compat",
".",
"v1",
".",
"scatter_update",
"to",
"axis",
"different",
"than",
"0",
"."
] | def batch_scatter_update(ref, indices, updates, use_locking=True, name=None):
"""Generalization of `tf.compat.v1.scatter_update` to axis different than 0.
Analogous to `batch_gather`. This assumes that `ref`, `indices` and `updates`
have a series of leading dimensions that are the same for all of them, and the
updates are performed on the last dimension of indices. In other words, the
dimensions should be the following:
`num_prefix_dims = indices.ndims - 1`
`batch_dim = num_prefix_dims + 1`
`updates.shape = indices.shape + var.shape[batch_dim:]`
where
`updates.shape[:num_prefix_dims]`
`== indices.shape[:num_prefix_dims]`
`== var.shape[:num_prefix_dims]`
And the operation performed can be expressed as:
`var[i_1, ..., i_n, indices[i_1, ..., i_n, j]] = updates[i_1, ..., i_n, j]`
When indices is a 1D tensor, this operation is equivalent to
`tf.compat.v1.scatter_update`.
To avoid this operation there would be 2 alternatives:
1) Reshaping the variable by merging the first `ndims` dimensions. However,
this is not possible because `tf.reshape` returns a Tensor, which we
cannot use `tf.compat.v1.scatter_update` on.
2) Looping over the first `ndims` of the variable and using
`tf.compat.v1.scatter_update` on the subtensors that result of slicing the
first
dimension. This is a valid option for `ndims = 1`, but less efficient than
this implementation.
See also `tf.compat.v1.scatter_update` and `tf.compat.v1.scatter_nd_update`.
Args:
ref: `Variable` to scatter onto.
indices: Tensor containing indices as described above.
updates: Tensor of updates to apply to `ref`.
use_locking: Boolean indicating whether to lock the writing operation.
name: Optional scope name string.
Returns:
Ref to `variable` after it has been modified.
Raises:
ValueError: If the initial `ndims` of `ref`, `indices`, and `updates` are
not the same.
"""
with ops.name_scope(name):
indices = ops.convert_to_tensor(indices, name="indices")
indices_shape = array_ops.shape(indices)
indices_dimensions = indices.get_shape().ndims
if indices_dimensions is None:
raise ValueError("batch_gather does not allow indices with unknown "
"shape.")
nd_indices = array_ops.expand_dims(indices, axis=-1)
nd_indices_list = []
# Scatter ND requires indices to have an additional dimension, in which the
# coordinates of the updated things are specified. For this to be adapted to
# the scatter_update with several leading dimensions, we simply make use of
# a tf.range for all the leading dimensions followed by concat of all the
# coordinates we created with the original indices.
# For example if indices.shape = [2, 3, 4], we should generate the following
# indices for tf.compat.v1.scatter_nd_update:
# nd_indices[:, :, 0] = [[0, 0, 0], [1, 1, 1]]
# nd_indices[:, :, 1] = [[0, 1, 2], [0, 1, 2]]
# nd_indices[:, :, 2] = indices
for dimension in range(indices_dimensions - 1):
# In this loop we generate the following for the example (one for each
# iteration).
# nd_indices[:, :, 0] = [[0, 0, 0], [1, 1, 1]]
# nd_indices[:, :, 1] = [[0, 1, 2], [0, 1, 2]]
# This is done at every iteration with a tf.range over the size of the
# i-th dimension and using broadcasting over the desired shape.
dimension_size = indices_shape[dimension]
shape_to_broadcast = [1] * (indices_dimensions + 1)
shape_to_broadcast[dimension] = dimension_size
dimension_range = array_ops.reshape(
gen_math_ops._range(0, dimension_size, 1), shape_to_broadcast)
if dimension_range.dtype.base_dtype != nd_indices.dtype:
dimension_range = gen_math_ops.cast(dimension_range, nd_indices.dtype)
nd_indices_list.append(
dimension_range * array_ops.ones_like(nd_indices))
# Add the original indices at the end, as described above, and concat.
nd_indices_list.append(nd_indices)
final_indices = array_ops.concat(nd_indices_list, axis=-1)
return scatter_nd_update(
ref, final_indices, updates, use_locking=use_locking) | [
"def",
"batch_scatter_update",
"(",
"ref",
",",
"indices",
",",
"updates",
",",
"use_locking",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
")",
":",
"indices",
"=",
"ops",
".",
"convert_to_tensor",
"(",... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/state_ops.py#L821-L915 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/util/retry.py | python | Retry.is_exhausted | (self) | return min(retry_counts) < 0 | Are we out of retries? | Are we out of retries? | [
"Are",
"we",
"out",
"of",
"retries?"
] | def is_exhausted(self):
""" Are we out of retries? """
retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)
retry_counts = list(filter(None, retry_counts))
if not retry_counts:
return False
return min(retry_counts) < 0 | [
"def",
"is_exhausted",
"(",
"self",
")",
":",
"retry_counts",
"=",
"(",
"self",
".",
"total",
",",
"self",
".",
"connect",
",",
"self",
".",
"read",
",",
"self",
".",
"redirect",
",",
"self",
".",
"status",
")",
"retry_counts",
"=",
"list",
"(",
"fil... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/util/retry.py#L346-L353 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-thci/OpenThread.py | python | OpenThreadTHCI.__skipSeqNoIncrease | (self) | return self.__executeCommand(cmd)[-1] == 'Done' | skip sequence number increase when recovering BBR Dataset from Network Data
Returns:
True: successful to set the behavior.
False: fail to set the behavior. | skip sequence number increase when recovering BBR Dataset from Network Data | [
"skip",
"sequence",
"number",
"increase",
"when",
"recovering",
"BBR",
"Dataset",
"from",
"Network",
"Data"
] | def __skipSeqNoIncrease(self):
"""skip sequence number increase when recovering BBR Dataset from Network Data
Returns:
True: successful to set the behavior.
False: fail to set the behavior.
"""
print('call __skipSeqNoIncrease()')
cmd = 'bbr skipseqnuminc'
return self.__executeCommand(cmd)[-1] == 'Done' | [
"def",
"__skipSeqNoIncrease",
"(",
"self",
")",
":",
"print",
"(",
"'call __skipSeqNoIncrease()'",
")",
"cmd",
"=",
"'bbr skipseqnuminc'",
"return",
"self",
".",
"__executeCommand",
"(",
"cmd",
")",
"[",
"-",
"1",
"]",
"==",
"'Done'"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread.py#L542-L551 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | RadioButton.GetClassDefaultAttributes | (*args, **kwargs) | return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs) | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this. | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes | [
"GetClassDefaultAttributes",
"(",
"int",
"variant",
"=",
"WINDOW_VARIANT_NORMAL",
")",
"-",
">",
"VisualAttributes"
] | def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs) | [
"def",
"GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"RadioButton_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L2755-L2770 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.eightbitize_bias_add_node | (self, original_node) | Replaces a BiasAdd node with the eight bit equivalent sub-graph. | Replaces a BiasAdd node with the eight bit equivalent sub-graph. | [
"Replaces",
"a",
"BiasAdd",
"node",
"with",
"the",
"eight",
"bit",
"equivalent",
"sub",
"-",
"graph",
"."
] | def eightbitize_bias_add_node(self, original_node):
"""Replaces a BiasAdd node with the eight bit equivalent sub-graph."""
quantized_bias_add_name = (original_node.name +
"_eightbit_quantized_bias_add")
all_input_names = self.add_eightbit_prologue_nodes(original_node)
quantized_bias_add_node = create_node(
"QuantizedBiasAdd", quantized_bias_add_name,
all_input_names)
set_attr_dtype(quantized_bias_add_node, "T1", tf.quint8)
set_attr_dtype(quantized_bias_add_node, "T2", tf.quint8)
set_attr_dtype(quantized_bias_add_node, "out_type", tf.qint32)
self.add_output_graph_node(quantized_bias_add_node)
quantize_down_name = self.add_quantize_down_node(original_node,
quantized_bias_add_name)
self.add_dequantize_result_node(quantize_down_name, original_node.name) | [
"def",
"eightbitize_bias_add_node",
"(",
"self",
",",
"original_node",
")",
":",
"quantized_bias_add_name",
"=",
"(",
"original_node",
".",
"name",
"+",
"\"_eightbit_quantized_bias_add\"",
")",
"all_input_names",
"=",
"self",
".",
"add_eightbit_prologue_nodes",
"(",
"or... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L602-L616 | ||
CaoWGG/TensorRT-CenterNet | f949252e37b51e60f873808f46d3683f15735e79 | onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py | python | Type.get_named_type | (self) | return conf.lib.clang_Type_getNamedType(self) | Retrieve the type named by the qualified-id. | Retrieve the type named by the qualified-id. | [
"Retrieve",
"the",
"type",
"named",
"by",
"the",
"qualified",
"-",
"id",
"."
] | def get_named_type(self):
"""
Retrieve the type named by the qualified-id.
"""
return conf.lib.clang_Type_getNamedType(self) | [
"def",
"get_named_type",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Type_getNamedType",
"(",
"self",
")"
] | https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L2078-L2082 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGridManager.GetGrid | (*args) | return _propgrid.PropertyGridManager_GetGrid(*args) | GetGrid(self) -> PropertyGrid
GetGrid(self) -> PropertyGrid | GetGrid(self) -> PropertyGrid
GetGrid(self) -> PropertyGrid | [
"GetGrid",
"(",
"self",
")",
"-",
">",
"PropertyGrid",
"GetGrid",
"(",
"self",
")",
"-",
">",
"PropertyGrid"
] | def GetGrid(*args):
"""
GetGrid(self) -> PropertyGrid
GetGrid(self) -> PropertyGrid
"""
return _propgrid.PropertyGridManager_GetGrid(*args) | [
"def",
"GetGrid",
"(",
"*",
"args",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_GetGrid",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3461-L3466 | |
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py | python | generic_pin.get_ODR_F1_value | (self) | return v | return one of LOW, HIGH | return one of LOW, HIGH | [
"return",
"one",
"of",
"LOW",
"HIGH"
] | def get_ODR_F1_value(self):
'''return one of LOW, HIGH'''
values = ['LOW', 'HIGH']
v = 'HIGH'
if self.type == 'OUTPUT':
v = 'LOW'
elif self.label is not None and self.label.startswith('I2C'):
v = 'LOW'
for e in self.extra:
if e in values:
v = e
# for some controllers input pull up down is selected by ODR
if self.type == "INPUT":
v = 'LOW'
if 'PULLUP' in self.extra:
v = "HIGH"
return v | [
"def",
"get_ODR_F1_value",
"(",
"self",
")",
":",
"values",
"=",
"[",
"'LOW'",
",",
"'HIGH'",
"]",
"v",
"=",
"'HIGH'",
"if",
"self",
".",
"type",
"==",
"'OUTPUT'",
":",
"v",
"=",
"'LOW'",
"elif",
"self",
".",
"label",
"is",
"not",
"None",
"and",
"s... | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py#L401-L417 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/MeshingApplication/python_scripts/mmg_process.py | python | MmgProcess._CreateGradientProcess | (self) | This method is responsible of create the gradients for the level-set process
Keyword arguments:
self -- It signifies an instance of a class. | This method is responsible of create the gradients for the level-set process | [
"This",
"method",
"is",
"responsible",
"of",
"create",
"the",
"gradients",
"for",
"the",
"level",
"-",
"set",
"process"
] | def _CreateGradientProcess(self):
""" This method is responsible of create the gradients for the level-set process
Keyword arguments:
self -- It signifies an instance of a class.
"""
# We compute the scalar value gradient
if self.domain_size == 2:
self.local_gradient = KratosMultiphysics.ComputeNodalGradientProcess2D(self.main_model_part, self.scalar_variable, self.gradient_variable, KratosMultiphysics.NODAL_AREA)
else:
self.local_gradient = KratosMultiphysics.ComputeNodalGradientProcess3D(self.main_model_part, self.scalar_variable, self.gradient_variable, KratosMultiphysics.NODAL_AREA) | [
"def",
"_CreateGradientProcess",
"(",
"self",
")",
":",
"# We compute the scalar value gradient",
"if",
"self",
".",
"domain_size",
"==",
"2",
":",
"self",
".",
"local_gradient",
"=",
"KratosMultiphysics",
".",
"ComputeNodalGradientProcess2D",
"(",
"self",
".",
"main_... | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/MeshingApplication/python_scripts/mmg_process.py#L552-L562 | ||
HackWebRTC/webrtc | 7abfc990c00ab35090fff285fcf635d1d7892433 | tools_webrtc/gn_check_autofix.py | python | FirstNonEmpty | (iterable) | return next((x for x in iterable if x), None) | Return first item which evaluates to True, or fallback to None. | Return first item which evaluates to True, or fallback to None. | [
"Return",
"first",
"item",
"which",
"evaluates",
"to",
"True",
"or",
"fallback",
"to",
"None",
"."
] | def FirstNonEmpty(iterable):
"""Return first item which evaluates to True, or fallback to None."""
return next((x for x in iterable if x), None) | [
"def",
"FirstNonEmpty",
"(",
"iterable",
")",
":",
"return",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"iterable",
"if",
"x",
")",
",",
"None",
")"
] | https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/tools_webrtc/gn_check_autofix.py#L94-L96 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/MetaSearch/dialogs/maindialog.py | python | MetaSearchDialog.manageGui | (self) | open window | open window | [
"open",
"window"
] | def manageGui(self):
"""open window"""
def _on_timeout_change(value):
self.settings.setValue('/MetaSearch/timeout', value)
self.timeout = value
def _on_records_change(value):
self.settings.setValue('/MetaSearch/returnRecords', value)
self.maxrecords = value
def _on_ssl_state_change(state):
self.settings.setValue('/MetaSearch/disableSSL', bool(state))
self.disable_ssl_verification = bool(state)
self.tabWidget.setCurrentIndex(0)
self.populate_connection_list()
self.btnRawAPIResponse.setEnabled(False)
# load settings
self.spnRecords.setValue(self.maxrecords)
self.spnRecords.valueChanged.connect(_on_records_change)
self.spnTimeout.setValue(self.timeout)
self.spnTimeout.valueChanged.connect(_on_timeout_change)
self.disableSSLVerification.setChecked(self.disable_ssl_verification)
self.disableSSLVerification.stateChanged.connect(_on_ssl_state_change)
key = '/MetaSearch/%s' % self.cmbConnectionsSearch.currentText()
self.catalog_url = self.settings.value('%s/url' % key)
self.catalog_username = self.settings.value('%s/username' % key)
self.catalog_password = self.settings.value('%s/password' % key)
self.catalog_type = self.settings.value('%s/catalog-type' % key)
self.set_bbox_global()
self.reset_buttons()
# install proxy handler if specified in QGIS settings
self.install_proxy() | [
"def",
"manageGui",
"(",
"self",
")",
":",
"def",
"_on_timeout_change",
"(",
"value",
")",
":",
"self",
".",
"settings",
".",
"setValue",
"(",
"'/MetaSearch/timeout'",
",",
"value",
")",
"self",
".",
"timeout",
"=",
"value",
"def",
"_on_records_change",
"(",... | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/MetaSearch/dialogs/maindialog.py#L141-L178 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cefbuilds/cef_json_builder.py | python | cef_json_builder.clear | (self) | Clear the contents of this object. | Clear the contents of this object. | [
"Clear",
"the",
"contents",
"of",
"this",
"object",
"."
] | def clear(self):
""" Clear the contents of this object. """
self._data = {}
for platform in self.get_platforms():
self._data[platform] = {'versions': []}
self._versions = {}
self._queryct = 0 | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"{",
"}",
"for",
"platform",
"in",
"self",
".",
"get_platforms",
"(",
")",
":",
"self",
".",
"_data",
"[",
"platform",
"]",
"=",
"{",
"'versions'",
":",
"[",
"]",
"}",
"self",
".",... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cefbuilds/cef_json_builder.py#L108-L114 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/importlib/resources.py | python | contents | (package: Package) | return list(item.name for item in _common.from_package(package).iterdir()) | Return an iterable of entries in 'package'.
Note that not all entries are resources. Specifically, directories are
not considered resources. Use `is_resource()` on each entry returned here
to check if it is a resource or not. | Return an iterable of entries in 'package'. | [
"Return",
"an",
"iterable",
"of",
"entries",
"in",
"package",
"."
] | def contents(package: Package) -> Iterable[str]:
"""Return an iterable of entries in 'package'.
Note that not all entries are resources. Specifically, directories are
not considered resources. Use `is_resource()` on each entry returned here
to check if it is a resource or not.
"""
package = _get_package(package)
reader = _get_resource_reader(package)
if reader is not None:
return reader.contents()
# Is the package a namespace package? By definition, namespace packages
# cannot have resources.
namespace = (
package.__spec__.origin is None or
package.__spec__.origin == 'namespace'
)
if namespace or not package.__spec__.has_location:
return ()
return list(item.name for item in _common.from_package(package).iterdir()) | [
"def",
"contents",
"(",
"package",
":",
"Package",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"package",
"=",
"_get_package",
"(",
"package",
")",
"reader",
"=",
"_get_resource_reader",
"(",
"package",
")",
"if",
"reader",
"is",
"not",
"None",
":",
"re... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/resources.py#L196-L215 | |
tensorflow/deepmath | b5b721f54de1d5d6a02d78f5da5995237f9995f9 | deepmath/deephol/train/data.py | python | generic_parser | (serialized_example, feature_list, label_list) | return features, labels | Parses a HOL example, keeping requested features and labels.
Args:
serialized_example: A tf.Example for a parameterized tactic application.
feature_list: List of string feature names to parse (subset of features).
label_list: List of string label names to parse (subset of labels).
Returns:
features, labels: dicts with keys of feature_list, label_list respectively. | Parses a HOL example, keeping requested features and labels. | [
"Parses",
"a",
"HOL",
"example",
"keeping",
"requested",
"features",
"and",
"labels",
"."
] | def generic_parser(serialized_example, feature_list, label_list):
"""Parses a HOL example, keeping requested features and labels.
Args:
serialized_example: A tf.Example for a parameterized tactic application.
feature_list: List of string feature names to parse (subset of features).
label_list: List of string label names to parse (subset of labels).
Returns:
features, labels: dicts with keys of feature_list, label_list respectively.
"""
example = tf.parse_single_example(
serialized_example,
features={
# Subgoal features
# goal: the consequent term of the subgoal as a string.
'goal': tf.FixedLenFeature((), tf.string, default_value=''),
# goal_asl: list of hypotheses of the subgoal.
'goal_asl': tf.VarLenFeature(dtype=tf.string),
# Parameterized tactic applied to the subgoal
# tactic: string name of tactic that is applied to this subgoal.
'tactic': tf.FixedLenFeature((), tf.string, default_value=''),
# tac_id: integer id of tactic.
'tac_id': tf.FixedLenFeature((), tf.int64, default_value=-1),
# thms: list of tactic arguments of type thm.
'thms': tf.VarLenFeature(dtype=tf.string),
# thms_hard_negatives: list of hard negative theorem parameter
# arguments
'thms_hard_negatives': tf.VarLenFeature(dtype=tf.string),
})
for key in ('goal_asl', 'thms', 'thms_hard_negatives'):
if key in example:
example[key] = tf.sparse_tensor_to_dense(example[key], default_value='')
features = {key: example[key] for key in feature_list}
labels = {key: example[key] for key in label_list}
return features, labels | [
"def",
"generic_parser",
"(",
"serialized_example",
",",
"feature_list",
",",
"label_list",
")",
":",
"example",
"=",
"tf",
".",
"parse_single_example",
"(",
"serialized_example",
",",
"features",
"=",
"{",
"# Subgoal features",
"# goal: the consequent term of the subgoal... | https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/train/data.py#L77-L114 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/base/tf/__init__.py | python | PreparePythonModule | (moduleName=None) | Prepare an extension module at import time. This will import the
Python module associated with the caller's module (e.g. '_tf' for 'pxr.Tf')
or the module with the specified moduleName and copy its contents into
the caller's local namespace.
Generally, this should only be called by the __init__.py script for a module
upon loading a boost python module (generally '_libName.so'). | Prepare an extension module at import time. This will import the
Python module associated with the caller's module (e.g. '_tf' for 'pxr.Tf')
or the module with the specified moduleName and copy its contents into
the caller's local namespace. | [
"Prepare",
"an",
"extension",
"module",
"at",
"import",
"time",
".",
"This",
"will",
"import",
"the",
"Python",
"module",
"associated",
"with",
"the",
"caller",
"s",
"module",
"(",
"e",
".",
"g",
".",
"_tf",
"for",
"pxr",
".",
"Tf",
")",
"or",
"the",
... | def PreparePythonModule(moduleName=None):
"""Prepare an extension module at import time. This will import the
Python module associated with the caller's module (e.g. '_tf' for 'pxr.Tf')
or the module with the specified moduleName and copy its contents into
the caller's local namespace.
Generally, this should only be called by the __init__.py script for a module
upon loading a boost python module (generally '_libName.so')."""
import importlib
import inspect
frame = inspect.currentframe().f_back
try:
f_locals = frame.f_locals
# If an explicit moduleName is not supplied, construct it from the
# caller's module name, like "pxr.Tf", and our naming conventions,
# which results in "_tf".
if moduleName is None:
moduleName = f_locals["__name__"].split(".")[-1]
moduleName = "_" + moduleName[0].lower() + moduleName[1:]
with WindowsImportWrapper():
module = importlib.import_module(
"." + moduleName, f_locals["__name__"])
PrepareModule(module, f_locals)
try:
del f_locals[moduleName]
except KeyError:
pass
try:
module = importlib.import_module(".__DOC", f_locals["__name__"])
module.Execute(f_locals)
try:
del f_locals["__DOC"]
except KeyError:
pass
except Exception:
pass
finally:
del frame | [
"def",
"PreparePythonModule",
"(",
"moduleName",
"=",
"None",
")",
":",
"import",
"importlib",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"try",
":",
"f_locals",
"=",
"frame",
".",
"f_locals",
"# If an explicit ... | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/base/tf/__init__.py#L66-L108 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Sizer.SetVirtualSizeHints | (*args, **kwargs) | return _core_.Sizer_SetVirtualSizeHints(*args, **kwargs) | SetVirtualSizeHints(self, Window window)
Tell the sizer to set the minimal size of the window virtual area to
match the sizer's minimal size. For windows with managed scrollbars
this will set them appropriately.
:see: `wx.ScrolledWindow.SetScrollbars` | SetVirtualSizeHints(self, Window window) | [
"SetVirtualSizeHints",
"(",
"self",
"Window",
"window",
")"
] | def SetVirtualSizeHints(*args, **kwargs):
"""
SetVirtualSizeHints(self, Window window)
Tell the sizer to set the minimal size of the window virtual area to
match the sizer's minimal size. For windows with managed scrollbars
this will set them appropriately.
:see: `wx.ScrolledWindow.SetScrollbars`
"""
return _core_.Sizer_SetVirtualSizeHints(*args, **kwargs) | [
"def",
"SetVirtualSizeHints",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Sizer_SetVirtualSizeHints",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14912-L14923 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/fx/experimental/graph_gradual_typechecker.py | python | get_parameter | (traced, target: str) | return param | Returns the parameter given by ``target`` if it exists,
otherwise throws an error.
See the docstring for ``get_submodule`` for a more detailed
explanation of this method's functionality as well as how to
correctly specify ``target``.
Args:
target: The fully-qualified string name of the Parameter
to look for. (See ``get_submodule`` for how to specify a
fully-qualified string.)
Returns:
torch.nn.Parameter: The Parameter referenced by ``target``
Raises:
AttributeError: If the target string references an invalid
path or resolves to something that is not an
``nn.Parameter`` | Returns the parameter given by ``target`` if it exists,
otherwise throws an error. | [
"Returns",
"the",
"parameter",
"given",
"by",
"target",
"if",
"it",
"exists",
"otherwise",
"throws",
"an",
"error",
"."
] | def get_parameter(traced, target: str):
"""
Returns the parameter given by ``target`` if it exists,
otherwise throws an error.
See the docstring for ``get_submodule`` for a more detailed
explanation of this method's functionality as well as how to
correctly specify ``target``.
Args:
target: The fully-qualified string name of the Parameter
to look for. (See ``get_submodule`` for how to specify a
fully-qualified string.)
Returns:
torch.nn.Parameter: The Parameter referenced by ``target``
Raises:
AttributeError: If the target string references an invalid
path or resolves to something that is not an
``nn.Parameter``
"""
module_path, _, param_name = target.rpartition(".")
mod: torch.nn.Module = traced.get_submodule(module_path)
if not hasattr(mod, param_name):
raise AttributeError(mod._get_name() + " has no attribute `" + param_name + "`")
param: torch.nn.Parameter = getattr(mod, param_name)
return param | [
"def",
"get_parameter",
"(",
"traced",
",",
"target",
":",
"str",
")",
":",
"module_path",
",",
"_",
",",
"param_name",
"=",
"target",
".",
"rpartition",
"(",
"\".\"",
")",
"mod",
":",
"torch",
".",
"nn",
".",
"Module",
"=",
"traced",
".",
"get_submodu... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/graph_gradual_typechecker.py#L894-L925 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/driver/abstract_variational_driver.py | python | AbstractVariationalDriver.info | (self, depth=0) | Returns an info string used to print information to screen about this driver. | Returns an info string used to print information to screen about this driver. | [
"Returns",
"an",
"info",
"string",
"used",
"to",
"print",
"information",
"to",
"screen",
"about",
"this",
"driver",
"."
] | def info(self, depth=0):
"""
Returns an info string used to print information to screen about this driver.
"""
pass | [
"def",
"info",
"(",
"self",
",",
"depth",
"=",
"0",
")",
":",
"pass"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/driver/abstract_variational_driver.py#L119-L123 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/common.py | python | _is_binary_mode | (handle: FilePathOrBuffer, mode: str) | return isinstance(handle, binary_classes) or "b" in getattr(handle, "mode", mode) | Whether the handle is opened in binary mode | Whether the handle is opened in binary mode | [
"Whether",
"the",
"handle",
"is",
"opened",
"in",
"binary",
"mode"
] | def _is_binary_mode(handle: FilePathOrBuffer, mode: str) -> bool:
"""Whether the handle is opened in binary mode"""
# specified by user
if "t" in mode or "b" in mode:
return "b" in mode
# exceptions
text_classes = (
# classes that expect string but have 'b' in mode
codecs.StreamWriter,
codecs.StreamReader,
codecs.StreamReaderWriter,
# cannot be wrapped in TextIOWrapper GH43439
tempfile.SpooledTemporaryFile,
)
if issubclass(type(handle), text_classes):
return False
# classes that expect bytes
binary_classes = (BufferedIOBase, RawIOBase)
return isinstance(handle, binary_classes) or "b" in getattr(handle, "mode", mode) | [
"def",
"_is_binary_mode",
"(",
"handle",
":",
"FilePathOrBuffer",
",",
"mode",
":",
"str",
")",
"->",
"bool",
":",
"# specified by user",
"if",
"\"t\"",
"in",
"mode",
"or",
"\"b\"",
"in",
"mode",
":",
"return",
"\"b\"",
"in",
"mode",
"# exceptions",
"text_cl... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/common.py#L942-L962 | |
avast/retdec | b9879088a5f0278508185ec645494e6c5c57a455 | scripts/type_extractor/type_extractor/parse_includes.py | python | is_wanted | (func_info) | return True | Do we want to include the given function in our extracted files? | Do we want to include the given function in our extracted files? | [
"Do",
"we",
"want",
"to",
"include",
"the",
"given",
"function",
"in",
"our",
"extracted",
"files?"
] | def is_wanted(func_info):
"""Do we want to include the given function in our extracted files?"""
# We do not want to include generic Windows functions whose arguments or
# return types are "T" types (e.g. LPCTSTR). They are never present in
# binary files. Instead, their A/W variants are used, depending on whether
# UNICODE was defined during compilation or not.
def is_t_type(type):
t_types_re = r'\b({})\b'.format('|'.join([
'LPCTSTR',
'PCTSTR',
'LPTSTR',
'PTSTR',
'TBYTE',
'PTBYTE',
'TCHAR',
]))
return re.search(t_types_re, type) is not None
if is_t_type(func_info.ret_type):
return False
for param in func_info.params:
if is_t_type(param.type_text):
return False
# Some functions look like declarations but are, in fact, just ordinary
# sentences. We detect this heuristically by searching for declarations
# that start with an uppercase letter and contain "the".
if re.fullmatch(r'[A-Z].*\bthe\b.*', func_info.decl):
return False
return True | [
"def",
"is_wanted",
"(",
"func_info",
")",
":",
"# We do not want to include generic Windows functions whose arguments or",
"# return types are \"T\" types (e.g. LPCTSTR). They are never present in",
"# binary files. Instead, their A/W variants are used, depending on whether",
"# UNICODE was defin... | https://github.com/avast/retdec/blob/b9879088a5f0278508185ec645494e6c5c57a455/scripts/type_extractor/type_extractor/parse_includes.py#L138-L167 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/distutils/ccompiler_opt.py | python | _Parse._parse_policy_not_keepsort | (self, has_baseline, final_targets, extra_flags) | return has_baseline, final_targets, extra_flags | sorted depend on the highest interest | sorted depend on the highest interest | [
"sorted",
"depend",
"on",
"the",
"highest",
"interest"
] | def _parse_policy_not_keepsort(self, has_baseline, final_targets, extra_flags):
"""sorted depend on the highest interest"""
final_targets = self.feature_sorted(final_targets, reverse=True)
return has_baseline, final_targets, extra_flags | [
"def",
"_parse_policy_not_keepsort",
"(",
"self",
",",
"has_baseline",
",",
"final_targets",
",",
"extra_flags",
")",
":",
"final_targets",
"=",
"self",
".",
"feature_sorted",
"(",
"final_targets",
",",
"reverse",
"=",
"True",
")",
"return",
"has_baseline",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/ccompiler_opt.py#L2064-L2067 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | GetConfigOption | (*args) | return _gdal.GetConfigOption(*args) | r"""GetConfigOption(char const * pszKey, char const * pszDefault=None) -> char const * | r"""GetConfigOption(char const * pszKey, char const * pszDefault=None) -> char const * | [
"r",
"GetConfigOption",
"(",
"char",
"const",
"*",
"pszKey",
"char",
"const",
"*",
"pszDefault",
"=",
"None",
")",
"-",
">",
"char",
"const",
"*"
] | def GetConfigOption(*args):
r"""GetConfigOption(char const * pszKey, char const * pszDefault=None) -> char const *"""
return _gdal.GetConfigOption(*args) | [
"def",
"GetConfigOption",
"(",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"GetConfigOption",
"(",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L1648-L1650 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_PCR_Allocate_REQUEST.fromTpm | (buf) | return buf.createObj(TPM2_PCR_Allocate_REQUEST) | Returns new TPM2_PCR_Allocate_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPM2_PCR_Allocate_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPM2_PCR_Allocate_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPM2_PCR_Allocate_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPM2_PCR_Allocate_REQUEST) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPM2_PCR_Allocate_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L13914-L13918 | |
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/message.py | python | Message.SerializeToString | (self) | Serializes the protocol message to a binary string.
Returns:
A binary string representation of the message if all of the required
fields in the message are set (i.e. the message is initialized).
Raises:
message.EncodeError if the message isn't initialized. | Serializes the protocol message to a binary string. | [
"Serializes",
"the",
"protocol",
"message",
"to",
"a",
"binary",
"string",
"."
] | def SerializeToString(self):
"""Serializes the protocol message to a binary string.
Returns:
A binary string representation of the message if all of the required
fields in the message are set (i.e. the message is initialized).
Raises:
message.EncodeError if the message isn't initialized.
"""
raise NotImplementedError | [
"def",
"SerializeToString",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/message.py#L184-L194 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py | python | LoggerAdapter.__init__ | (self, logger, extra) | Initialize the adapter with a logger and a dict-like object which
provides contextual information. This constructor signature allows
easy stacking of LoggerAdapters, if so desired.
You can effectively pass keyword arguments as shown in the
following example:
adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) | Initialize the adapter with a logger and a dict-like object which
provides contextual information. This constructor signature allows
easy stacking of LoggerAdapters, if so desired. | [
"Initialize",
"the",
"adapter",
"with",
"a",
"logger",
"and",
"a",
"dict",
"-",
"like",
"object",
"which",
"provides",
"contextual",
"information",
".",
"This",
"constructor",
"signature",
"allows",
"easy",
"stacking",
"of",
"LoggerAdapters",
"if",
"so",
"desire... | def __init__(self, logger, extra):
"""
Initialize the adapter with a logger and a dict-like object which
provides contextual information. This constructor signature allows
easy stacking of LoggerAdapters, if so desired.
You can effectively pass keyword arguments as shown in the
following example:
adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
"""
self.logger = logger
self.extra = extra | [
"def",
"__init__",
"(",
"self",
",",
"logger",
",",
"extra",
")",
":",
"self",
".",
"logger",
"=",
"logger",
"self",
".",
"extra",
"=",
"extra"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L1389-L1401 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | Palette.GetColoursCount | (*args, **kwargs) | return _gdi_.Palette_GetColoursCount(*args, **kwargs) | GetColoursCount(self) -> int | GetColoursCount(self) -> int | [
"GetColoursCount",
"(",
"self",
")",
"-",
">",
"int"
] | def GetColoursCount(*args, **kwargs):
"""GetColoursCount(self) -> int"""
return _gdi_.Palette_GetColoursCount(*args, **kwargs) | [
"def",
"GetColoursCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Palette_GetColoursCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L349-L351 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.IsLinkIncremental | (self, config) | return link_inc != '1' | Returns whether the target should be linked incrementally. | Returns whether the target should be linked incrementally. | [
"Returns",
"whether",
"the",
"target",
"should",
"be",
"linked",
"incrementally",
"."
] | def IsLinkIncremental(self, config):
"""Returns whether the target should be linked incrementally."""
config = self._TargetConfig(config)
link_inc = self._Setting(('VCLinkerTool', 'LinkIncremental'), config)
return link_inc != '1' | [
"def",
"IsLinkIncremental",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"link_inc",
"=",
"self",
".",
"_Setting",
"(",
"(",
"'VCLinkerTool'",
",",
"'LinkIncremental'",
")",
",",
"config",
")",
"ret... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/msvs_emulation.py#L794-L798 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/package/package_importer.py | python | PackageImporter.load_pickle | (self, package: str, resource: str, map_location=None) | return result | Unpickles the resource from the package, loading any modules that are needed to construct the objects
using :meth:`import_module`.
Args:
package (str): The name of module package (e.g. ``"my_package.my_subpackage"``).
resource (str): The unique name for the resource.
map_location: Passed to `torch.load` to determine how tensors are mapped to devices. Defaults to ``None``.
Returns:
Any: The unpickled object. | Unpickles the resource from the package, loading any modules that are needed to construct the objects
using :meth:`import_module`. | [
"Unpickles",
"the",
"resource",
"from",
"the",
"package",
"loading",
"any",
"modules",
"that",
"are",
"needed",
"to",
"construct",
"the",
"objects",
"using",
":",
"meth",
":",
"import_module",
"."
] | def load_pickle(self, package: str, resource: str, map_location=None) -> Any:
"""Unpickles the resource from the package, loading any modules that are needed to construct the objects
using :meth:`import_module`.
Args:
package (str): The name of module package (e.g. ``"my_package.my_subpackage"``).
resource (str): The unique name for the resource.
map_location: Passed to `torch.load` to determine how tensors are mapped to devices. Defaults to ``None``.
Returns:
Any: The unpickled object.
"""
pickle_file = self._zipfile_path(package, resource)
restore_location = _get_restore_location(map_location)
loaded_storages = {}
loaded_reduces = {}
storage_context = torch._C.DeserializationStorageContext()
def load_tensor(dtype, size, key, location, restore_location):
name = f"{key}.storage"
if storage_context.has_storage(name):
storage = storage_context.get_storage(name, dtype).storage()
else:
tensor = self.zip_reader.get_storage_from_record(
".data/" + name, size, dtype
)
if isinstance(self.zip_reader, torch._C.PyTorchFileReader):
storage_context.add_storage(name, tensor)
storage = tensor.storage()
loaded_storages[key] = restore_location(storage, location)
def persistent_load(saved_id):
assert isinstance(saved_id, tuple)
typename = _maybe_decode_ascii(saved_id[0])
data = saved_id[1:]
if typename == "storage":
storage_type, key, location, size = data
dtype = storage_type.dtype
if key not in loaded_storages:
load_tensor(
dtype,
size,
key,
_maybe_decode_ascii(location),
restore_location,
)
storage = loaded_storages[key]
# TODO: Once we decide to break serialization FC, we can
# stop wrapping with TypedStorage
return torch.storage.TypedStorage(
wrap_storage=storage._untyped(), dtype=dtype
)
elif typename == "reduce_package":
# to fix BC breaking change, objects on this load path
# will be loaded multiple times erroneously
if len(data) == 2:
func, args = data
return func(self, *args)
reduce_id, func, args = data
if reduce_id not in loaded_reduces:
loaded_reduces[reduce_id] = func(self, *args)
return loaded_reduces[reduce_id]
else:
f"Unknown typename for persistent_load, expected 'storage' or 'reduce_package' but got '{typename}'"
# Load the data (which may in turn use `persistent_load` to load tensors)
data_file = io.BytesIO(self.zip_reader.get_record(pickle_file))
unpickler = self.Unpickler(data_file)
unpickler.persistent_load = persistent_load
@contextmanager
def set_deserialization_context():
# to let reduce_package access deserializaiton context
self.storage_context = storage_context
self.last_map_location = map_location
try:
yield
finally:
self.storage_context = None
self.last_map_location = None
with set_deserialization_context():
result = unpickler.load()
# TODO from zdevito:
# This stateful weird function will need to be removed in our efforts
# to unify the format. It has a race condition if multiple python
# threads try to read independent files
torch._utils._validate_loaded_sparse_tensors()
return result | [
"def",
"load_pickle",
"(",
"self",
",",
"package",
":",
"str",
",",
"resource",
":",
"str",
",",
"map_location",
"=",
"None",
")",
"->",
"Any",
":",
"pickle_file",
"=",
"self",
".",
"_zipfile_path",
"(",
"package",
",",
"resource",
")",
"restore_location",... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/package/package_importer.py#L169-L262 | |
google/nucleus | 68d3947fafba1337f294c0668a6e1c7f3f1273e3 | nucleus/util/vis.py | python | array_to_png | (arr,
path=None,
show=True,
vmin=None,
vmax=None,
scale=None,
labels=None) | Save an array as a PNG image with PIL and show it.
Args:
arr: numpy array. Should be 2-dimensional or 3-dimensional where the third
dimension has 3 channels.
path: str. Path for the image output. Default is /tmp/tmp.png for quickly
showing the image in a notebook.
show: bool. Whether to show the image using IPython utilities, only works in
notebooks.
vmin: number. Minimum data value, which will correspond to black in
greyscale or lack of each color in RGB images. Default None takes the
minimum of the data from arr.
vmax: number. Maximum data value, which will correspond to white in
greyscale or full presence of each color in RGB images. Default None takes
the max of the data from arr.
scale: integer. Number of pixels wide and tall to show each cell in the
array. This sizes up the image while keeping exactly the same number of
pixels for every cell in the array, preserving resolution and preventing
any interpolation or overlapping of pixels. Default None adapts to the
size of the image to multiply it up until a limit of 500 pixels, a
convenient size for use in notebooks. If saving to a file for automated
processing, scale=1 is recommended to keep output files small and simple
while still retaining all the information content.
labels: list of str. Labels to show across the top of the image.
Returns:
None. Saves an image at path and optionally shows it with IPython.display. | Save an array as a PNG image with PIL and show it. | [
"Save",
"an",
"array",
"as",
"a",
"PNG",
"image",
"with",
"PIL",
"and",
"show",
"it",
"."
] | def array_to_png(arr,
path=None,
show=True,
vmin=None,
vmax=None,
scale=None,
labels=None):
"""Save an array as a PNG image with PIL and show it.
Args:
arr: numpy array. Should be 2-dimensional or 3-dimensional where the third
dimension has 3 channels.
path: str. Path for the image output. Default is /tmp/tmp.png for quickly
showing the image in a notebook.
show: bool. Whether to show the image using IPython utilities, only works in
notebooks.
vmin: number. Minimum data value, which will correspond to black in
greyscale or lack of each color in RGB images. Default None takes the
minimum of the data from arr.
vmax: number. Maximum data value, which will correspond to white in
greyscale or full presence of each color in RGB images. Default None takes
the max of the data from arr.
scale: integer. Number of pixels wide and tall to show each cell in the
array. This sizes up the image while keeping exactly the same number of
pixels for every cell in the array, preserving resolution and preventing
any interpolation or overlapping of pixels. Default None adapts to the
size of the image to multiply it up until a limit of 500 pixels, a
convenient size for use in notebooks. If saving to a file for automated
processing, scale=1 is recommended to keep output files small and simple
while still retaining all the information content.
labels: list of str. Labels to show across the top of the image.
Returns:
None. Saves an image at path and optionally shows it with IPython.display.
"""
scaled, image_mode = autoscale_colors_for_png(arr, vmin=vmin, vmax=vmax)
save_to_png(
scaled,
path=path,
show=show,
image_mode=image_mode,
labels=labels,
scale=scale) | [
"def",
"array_to_png",
"(",
"arr",
",",
"path",
"=",
"None",
",",
"show",
"=",
"True",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"labels",
"=",
"None",
")",
":",
"scaled",
",",
"image_mode",
"=",
"autoscale... | https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/util/vis.py#L354-L396 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Text.image_names | (self) | return self.tk.call(self._w, "image", "names") | Return all names of embedded images in this widget. | Return all names of embedded images in this widget. | [
"Return",
"all",
"names",
"of",
"embedded",
"images",
"in",
"this",
"widget",
"."
] | def image_names(self):
"""Return all names of embedded images in this widget."""
return self.tk.call(self._w, "image", "names") | [
"def",
"image_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"image\"",
",",
"\"names\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L3106-L3108 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/data.py | python | BatchFeed.add_update | (self, entry, batch_id_string=None) | Add an update request to the list of batch operations in this feed.
Sets the operation type of the entry to insert if it is not already set
and assigns the desired batch id to the entry so that it can be
referenced in the server's response.
Args:
entry: BatchEntry The entry which will be sent to the server as an
update (HTTP PUT) request. The item must have a valid atom id
so that the server knows which entry to replace.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. See also comments for AddInsert. | Add an update request to the list of batch operations in this feed. | [
"Add",
"an",
"update",
"request",
"to",
"the",
"list",
"of",
"batch",
"operations",
"in",
"this",
"feed",
"."
] | def add_update(self, entry, batch_id_string=None):
"""Add an update request to the list of batch operations in this feed.
Sets the operation type of the entry to insert if it is not already set
and assigns the desired batch id to the entry so that it can be
referenced in the server's response.
Args:
entry: BatchEntry The entry which will be sent to the server as an
update (HTTP PUT) request. The item must have a valid atom id
so that the server knows which entry to replace.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. See also comments for AddInsert.
"""
self.add_batch_entry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_UPDATE) | [
"def",
"add_update",
"(",
"self",
",",
"entry",
",",
"batch_id_string",
"=",
"None",
")",
":",
"self",
".",
"add_batch_entry",
"(",
"entry",
"=",
"entry",
",",
"batch_id_string",
"=",
"batch_id_string",
",",
"operation_string",
"=",
"BATCH_UPDATE",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/data.py#L478-L495 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/socketserver.py | python | BaseServer.server_activate | (self) | Called by constructor to activate the server.
May be overridden. | Called by constructor to activate the server. | [
"Called",
"by",
"constructor",
"to",
"activate",
"the",
"server",
"."
] | def server_activate(self):
"""Called by constructor to activate the server.
May be overridden.
"""
pass | [
"def",
"server_activate",
"(",
"self",
")",
":",
"pass"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/socketserver.py#L207-L213 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/framework/python/framework/tensor_util.py | python | _is_shape | (expected_shape, actual_tensor, actual_shape=None) | Returns whether actual_tensor's shape is expected_shape.
Args:
expected_shape: Integer list defining the expected shape, or tensor of same.
actual_tensor: Tensor to test.
actual_shape: Shape of actual_tensor, if we already have it.
Returns:
New tensor. | Returns whether actual_tensor's shape is expected_shape. | [
"Returns",
"whether",
"actual_tensor",
"s",
"shape",
"is",
"expected_shape",
"."
] | def _is_shape(expected_shape, actual_tensor, actual_shape=None):
"""Returns whether actual_tensor's shape is expected_shape.
Args:
expected_shape: Integer list defining the expected shape, or tensor of same.
actual_tensor: Tensor to test.
actual_shape: Shape of actual_tensor, if we already have it.
Returns:
New tensor.
"""
with ops.op_scope([actual_tensor], 'is_shape') as scope:
is_rank = _is_rank(array_ops.size(expected_shape), actual_tensor)
if actual_shape is None:
actual_shape = array_ops.shape(actual_tensor, name='actual')
shape_equal = _all_equal(
ops.convert_to_tensor(expected_shape, name='expected'),
actual_shape)
return math_ops.logical_and(is_rank, shape_equal, name=scope) | [
"def",
"_is_shape",
"(",
"expected_shape",
",",
"actual_tensor",
",",
"actual_shape",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"actual_tensor",
"]",
",",
"'is_shape'",
")",
"as",
"scope",
":",
"is_rank",
"=",
"_is_rank",
"(",
"array... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/framework/python/framework/tensor_util.py#L161-L178 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | samples/python/efficientdet/build_engine.py | python | EngineBuilder.create_network | (self, onnx_path) | Parse the ONNX graph and create the corresponding TensorRT network definition.
:param onnx_path: The path to the ONNX graph to load. | Parse the ONNX graph and create the corresponding TensorRT network definition.
:param onnx_path: The path to the ONNX graph to load. | [
"Parse",
"the",
"ONNX",
"graph",
"and",
"create",
"the",
"corresponding",
"TensorRT",
"network",
"definition",
".",
":",
"param",
"onnx_path",
":",
"The",
"path",
"to",
"the",
"ONNX",
"graph",
"to",
"load",
"."
] | def create_network(self, onnx_path):
"""
Parse the ONNX graph and create the corresponding TensorRT network definition.
:param onnx_path: The path to the ONNX graph to load.
"""
network_flags = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
self.network = self.builder.create_network(network_flags)
self.parser = trt.OnnxParser(self.network, self.trt_logger)
onnx_path = os.path.realpath(onnx_path)
with open(onnx_path, "rb") as f:
if not self.parser.parse(f.read()):
log.error("Failed to load ONNX file: {}".format(onnx_path))
for error in range(self.parser.num_errors):
log.error(self.parser.get_error(error))
sys.exit(1)
inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]
outputs = [self.network.get_output(i) for i in range(self.network.num_outputs)]
log.info("Network Description")
for input in inputs:
self.batch_size = input.shape[0]
log.info("Input '{}' with shape {} and dtype {}".format(input.name, input.shape, input.dtype))
for output in outputs:
log.info("Output '{}' with shape {} and dtype {}".format(output.name, output.shape, output.dtype))
assert self.batch_size > 0
self.builder.max_batch_size = self.batch_size | [
"def",
"create_network",
"(",
"self",
",",
"onnx_path",
")",
":",
"network_flags",
"=",
"(",
"1",
"<<",
"int",
"(",
"trt",
".",
"NetworkDefinitionCreationFlag",
".",
"EXPLICIT_BATCH",
")",
")",
"self",
".",
"network",
"=",
"self",
".",
"builder",
".",
"cre... | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/efficientdet/build_engine.py#L134-L162 | ||
sonyxperiadev/WebGL | 0299b38196f78c6d5f74bcf6fa312a3daee6de60 | Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | Tag.__init__ | (self, parser, name, attrs=None, parent=None,
previous=None) | Basic constructor. | Basic constructor. | [
"Basic",
"constructor",
"."
] | def __init__(self, parser, name, attrs=None, parent=None,
previous=None):
"Basic constructor."
# We don't actually store the parser object: that lets extracted
# chunks be garbage-collected
self.parserClass = parser.__class__
self.isSelfClosing = parser.isSelfClosingTag(name)
self.name = name
if attrs == None:
attrs = []
self.attrs = attrs
self.contents = []
self.setup(parent, previous)
self.hidden = False
self.containsSubstitutions = False
self.convertHTMLEntities = parser.convertHTMLEntities
self.convertXMLEntities = parser.convertXMLEntities
self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
def convert(kval):
"Converts HTML, XML and numeric entities in the attribute value."
k, val = kval
if val is None:
return kval
return (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
self._convertEntities, val))
self.attrs = map(convert, self.attrs) | [
"def",
"__init__",
"(",
"self",
",",
"parser",
",",
"name",
",",
"attrs",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"previous",
"=",
"None",
")",
":",
"# We don't actually store the parser object: that lets extracted",
"# chunks be garbage-collected",
"self",
".... | https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L500-L527 | ||
vusec/vuzzer64 | 2b1b0ed757a3dca114db0192fa4ab1add92348bc | fuzzer-code/bb-weight-new.py | python | get_backedges | (root) | return backedge | tries to retrieve back edges. this analysis may produce FP/FN. the algorith is based on assumption that if we
traverse a graph width first, the whenever we hit a node that has been traversed before, we get a backedge. | tries to retrieve back edges. this analysis may produce FP/FN. the algorith is based on assumption that if we
traverse a graph width first, the whenever we hit a node that has been traversed before, we get a backedge. | [
"tries",
"to",
"retrieve",
"back",
"edges",
".",
"this",
"analysis",
"may",
"produce",
"FP",
"/",
"FN",
".",
"the",
"algorith",
"is",
"based",
"on",
"assumption",
"that",
"if",
"we",
"traverse",
"a",
"graph",
"width",
"first",
"the",
"whenever",
"we",
"h... | def get_backedges(root):
''' tries to retrieve back edges. this analysis may produce FP/FN. the algorith is based on assumption that if we
traverse a graph width first, the whenever we hit a node that has been traversed before, we get a backedge.
'''
tmp=deque([])
visited=set()
backedge=[]# a list of tuple of the form (startEA,endEA), denoting an edge.
#for cr in root.succs():
# tmp.append(cr)
# visited.append(cr.startEA)
#print "init visited: %x"%cr.startEA
#if len(tmp) == 0:
# return backedge
tmp.append(root)
#print "visited: %x"%root.startEA
while len(tmp)>0:
cur=tmp.popleft()
visited.add(cur.startEA)
for ccur in cur.succs():
if ccur.startEA in visited and get_path(ccur,cur,backedge) == True:
backedge.append((cur.startEA,ccur.startEA))
elif ccur.startEA not in visited:
visited.add(ccur.startEA)
tmp.append(ccur)
#print "visited: %x"%ccur.startEA
else:
pass
# now we repeat the above step to prune backedges that we got so far.
tmp.clear()
visited=set()
backedgeF=[]
tmp.append(root)
#print "visited: %x"%root.startEA
while len(tmp)>0:
cur=tmp.popleft()
visited.add(cur.startEA)
for ccur in cur.succs():
if ccur.startEA in visited and get_path(ccur,cur,backedge) == True:
backedgeF.append((cur.startEA,ccur.startEA))
elif ccur.startEA not in visited:
visited.add(ccur.startEA)
tmp.append(ccur)
#print "visited: %x"% ccur.startEA
else:
pass
print "Done Back Edge..."
#if len(backedgeF)>8:
# for be in backedgeF:
# print "%x - %x"%(be[0],be[1])
# sys.exit(0)
return backedge | [
"def",
"get_backedges",
"(",
"root",
")",
":",
"tmp",
"=",
"deque",
"(",
"[",
"]",
")",
"visited",
"=",
"set",
"(",
")",
"backedge",
"=",
"[",
"]",
"# a list of tuple of the form (startEA,endEA), denoting an edge.",
"#for cr in root.succs():",
"# tmp.append(cr)",
... | https://github.com/vusec/vuzzer64/blob/2b1b0ed757a3dca114db0192fa4ab1add92348bc/fuzzer-code/bb-weight-new.py#L123-L176 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _GenerateMSBuildRulePropsFile | (props_path, msbuild_rules) | Generate the .props file. | Generate the .props file. | [
"Generate",
"the",
".",
"props",
"file",
"."
] | def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
"""Generate the .props file."""
content = [
"Project",
{"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"},
]
for rule in msbuild_rules:
content.extend(
[
[
"PropertyGroup",
{
"Condition": "'$(%s)' == '' and '$(%s)' == '' and "
"'$(ConfigurationType)' != 'Makefile'"
% (rule.before_targets, rule.after_targets)
},
[rule.before_targets, "Midl"],
[rule.after_targets, "CustomBuild"],
],
[
"PropertyGroup",
[
rule.depends_on,
{"Condition": "'$(ConfigurationType)' != 'Makefile'"},
"_SelectedFiles;$(%s)" % rule.depends_on,
],
],
[
"ItemDefinitionGroup",
[
rule.rule_name,
["CommandLineTemplate", rule.command],
["Outputs", rule.outputs],
["ExecutionDescription", rule.description],
["AdditionalDependencies", rule.additional_dependencies],
],
],
]
)
easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True) | [
"def",
"_GenerateMSBuildRulePropsFile",
"(",
"props_path",
",",
"msbuild_rules",
")",
":",
"content",
"=",
"[",
"\"Project\"",
",",
"{",
"\"xmlns\"",
":",
"\"http://schemas.microsoft.com/developer/msbuild/2003\"",
"}",
",",
"]",
"for",
"rule",
"in",
"msbuild_rules",
"... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L2438-L2477 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextCtrl.PromoteList | (*args, **kwargs) | return _richtext.RichTextCtrl_PromoteList(*args, **kwargs) | PromoteList(self, int promoteBy, RichTextRange range, String defName,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel=-1) -> bool | PromoteList(self, int promoteBy, RichTextRange range, String defName,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel=-1) -> bool | [
"PromoteList",
"(",
"self",
"int",
"promoteBy",
"RichTextRange",
"range",
"String",
"defName",
"int",
"flags",
"=",
"RICHTEXT_SETSTYLE_WITH_UNDO",
"int",
"specifiedLevel",
"=",
"-",
"1",
")",
"-",
">",
"bool"
] | def PromoteList(*args, **kwargs):
"""
PromoteList(self, int promoteBy, RichTextRange range, String defName,
int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel=-1) -> bool
"""
return _richtext.RichTextCtrl_PromoteList(*args, **kwargs) | [
"def",
"PromoteList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_PromoteList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L3199-L3204 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/cli/cli_shared.py | python | get_run_short_description | (run_call_count,
fetches,
feed_dict,
is_callable_runner=False) | return description | Get a short description of the run() call.
Args:
run_call_count: (int) Run call counter.
fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
for more details.
feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
for more details.
is_callable_runner: (bool) whether a runner returned by
Session.make_callable is being run.
Returns:
(str) A short description of the run() call, including information about
the fetche(s) and feed(s). | Get a short description of the run() call. | [
"Get",
"a",
"short",
"description",
"of",
"the",
"run",
"()",
"call",
"."
] | def get_run_short_description(run_call_count,
fetches,
feed_dict,
is_callable_runner=False):
"""Get a short description of the run() call.
Args:
run_call_count: (int) Run call counter.
fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
for more details.
feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
for more details.
is_callable_runner: (bool) whether a runner returned by
Session.make_callable is being run.
Returns:
(str) A short description of the run() call, including information about
the fetche(s) and feed(s).
"""
if is_callable_runner:
return "runner from make_callable()"
description = "run #%d: " % run_call_count
if isinstance(fetches, (ops.Tensor, ops.Operation, variables.Variable)):
description += "1 fetch (%s); " % _get_fetch_name(fetches)
else:
# Could be (nested) list, tuple, dict or namedtuple.
num_fetches = len(_get_fetch_names(fetches))
if num_fetches > 1:
description += "%d fetches; " % num_fetches
else:
description += "%d fetch; " % num_fetches
if not feed_dict:
description += "0 feeds"
else:
if len(feed_dict) == 1:
for key in feed_dict:
description += "1 feed (%s)" % (
key if isinstance(key, six.string_types) else key.name)
else:
description += "%d feeds" % len(feed_dict)
return description | [
"def",
"get_run_short_description",
"(",
"run_call_count",
",",
"fetches",
",",
"feed_dict",
",",
"is_callable_runner",
"=",
"False",
")",
":",
"if",
"is_callable_runner",
":",
"return",
"\"runner from make_callable()\"",
"description",
"=",
"\"run #%d: \"",
"%",
"run_c... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/cli_shared.py#L418-L462 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py | python | TFAsymmetryFittingModel._toggle_fix_normalisation_in_tf_asymmetry_single_fit_mode | (self, dataset_index: int, is_fixed: bool) | Fixes the current normalisation to its current value in single fit mode, or unfixes it. | Fixes the current normalisation to its current value in single fit mode, or unfixes it. | [
"Fixes",
"the",
"current",
"normalisation",
"to",
"its",
"current",
"value",
"in",
"single",
"fit",
"mode",
"or",
"unfixes",
"it",
"."
] | def _toggle_fix_normalisation_in_tf_asymmetry_single_fit_mode(self, dataset_index: int, is_fixed: bool) -> None:
"""Fixes the current normalisation to its current value in single fit mode, or unfixes it."""
current_tf_single_fit_function = self.fitting_context.tf_asymmetry_single_functions[dataset_index]
if current_tf_single_fit_function is not None:
if is_fixed:
current_tf_single_fit_function.fixParameter(NORMALISATION_PARAMETER)
else:
current_tf_single_fit_function.freeParameter(NORMALISATION_PARAMETER) | [
"def",
"_toggle_fix_normalisation_in_tf_asymmetry_single_fit_mode",
"(",
"self",
",",
"dataset_index",
":",
"int",
",",
"is_fixed",
":",
"bool",
")",
"->",
"None",
":",
"current_tf_single_fit_function",
"=",
"self",
".",
"fitting_context",
".",
"tf_asymmetry_single_functi... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py#L461-L468 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests_toolbelt/_compat.py | python | HTTPHeaderDict.pop | (self, key, default=__marker) | D.pop(k[,d]) -> v, remove specified key and return its value.
If key is not found, d is returned if given, otherwise KeyError is
raised. | D.pop(k[,d]) -> v, remove specified key and return its value. | [
"D",
".",
"pop",
"(",
"k",
"[",
"d",
"]",
")",
"-",
">",
"v",
"remove",
"specified",
"key",
"and",
"return",
"its",
"value",
"."
] | def pop(self, key, default=__marker):
"""D.pop(k[,d]) -> v, remove specified key and return its value.
If key is not found, d is returned if given, otherwise KeyError is
raised.
"""
# Using the MutableMapping function directly fails due to the private
# marker.
# Using ordinary dict.pop would expose the internal structures.
# So let's reinvent the wheel.
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"__marker",
")",
":",
"# Using the MutableMapping function directly fails due to the private",
"# marker.",
"# Using ordinary dict.pop would expose the internal structures.",
"# So let's reinvent the wheel.",
"try",
":",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests_toolbelt/_compat.py#L153-L171 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.