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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/wheel.py | python | WheelBuilder.build | (self) | Build wheels. | Build wheels. | [
"Build",
"wheels",
"."
] | def build(self):
"""Build wheels."""
#unpack and constructs req set
self.requirement_set.prepare_files(self.finder)
reqset = self.requirement_set.requirements.values()
#make the wheelhouse
if not os.path.exists(self.wheel_dir):
os.makedirs(self.wheel_dir)
#build the wheels
logger.notify('Building wheels for collected packages: %s' % ', '.join([req.name for req in reqset]))
logger.indent += 2
build_success, build_failure = [], []
for req in reqset:
if req.is_wheel:
logger.notify("Skipping building wheel: %s", req.url)
continue
if self._build_one(req):
build_success.append(req)
else:
build_failure.append(req)
logger.indent -= 2
#notify sucess/failure
if build_success:
logger.notify('Successfully built %s' % ' '.join([req.name for req in build_success]))
if build_failure:
logger.notify('Failed to build %s' % ' '.join([req.name for req in build_failure])) | [
"def",
"build",
"(",
"self",
")",
":",
"#unpack and constructs req set",
"self",
".",
"requirement_set",
".",
"prepare_files",
"(",
"self",
".",
"finder",
")",
"reqset",
"=",
"self",
".",
"requirement_set",
".",
"requirements",
".",
"values",
"(",
")",
"#make the wheelhouse",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"wheel_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"wheel_dir",
")",
"#build the wheels",
"logger",
".",
"notify",
"(",
"'Building wheels for collected packages: %s'",
"%",
"', '",
".",
"join",
"(",
"[",
"req",
".",
"name",
"for",
"req",
"in",
"reqset",
"]",
")",
")",
"logger",
".",
"indent",
"+=",
"2",
"build_success",
",",
"build_failure",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"req",
"in",
"reqset",
":",
"if",
"req",
".",
"is_wheel",
":",
"logger",
".",
"notify",
"(",
"\"Skipping building wheel: %s\"",
",",
"req",
".",
"url",
")",
"continue",
"if",
"self",
".",
"_build_one",
"(",
"req",
")",
":",
"build_success",
".",
"append",
"(",
"req",
")",
"else",
":",
"build_failure",
".",
"append",
"(",
"req",
")",
"logger",
".",
"indent",
"-=",
"2",
"#notify sucess/failure",
"if",
"build_success",
":",
"logger",
".",
"notify",
"(",
"'Successfully built %s'",
"%",
"' '",
".",
"join",
"(",
"[",
"req",
".",
"name",
"for",
"req",
"in",
"build_success",
"]",
")",
")",
"if",
"build_failure",
":",
"logger",
".",
"notify",
"(",
"'Failed to build %s'",
"%",
"' '",
".",
"join",
"(",
"[",
"req",
".",
"name",
"for",
"req",
"in",
"build_failure",
"]",
")",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/wheel.py#L305-L335 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pexpect/pexpect/popen_spawn.py | python | PopenSpawn.send | (self, s) | Send data to the subprocess' stdin.
Returns the number of bytes written. | Send data to the subprocess' stdin. | [
"Send",
"data",
"to",
"the",
"subprocess",
"stdin",
"."
] | def send(self, s):
'''Send data to the subprocess' stdin.
Returns the number of bytes written.
'''
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=False)
if PY3:
return self.proc.stdin.write(b)
else:
# On Python 2, .write() returns None, so we return the length of
# bytes written ourselves. This assumes they all got written.
self.proc.stdin.write(b)
return len(b) | [
"def",
"send",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"self",
".",
"_coerce_send_string",
"(",
"s",
")",
"self",
".",
"_log",
"(",
"s",
",",
"'send'",
")",
"b",
"=",
"self",
".",
"_encoder",
".",
"encode",
"(",
"s",
",",
"final",
"=",
"False",
")",
"if",
"PY3",
":",
"return",
"self",
".",
"proc",
".",
"stdin",
".",
"write",
"(",
"b",
")",
"else",
":",
"# On Python 2, .write() returns None, so we return the length of",
"# bytes written ourselves. This assumes they all got written.",
"self",
".",
"proc",
".",
"stdin",
".",
"write",
"(",
"b",
")",
"return",
"len",
"(",
"b",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pexpect/pexpect/popen_spawn.py#L132-L147 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/mooseutils/message.py | python | mooseMessage | (*args, **kwargs) | A generic message function.
Args:
args[tuple]: Comma separated items to be printed, non strings are converted with 'repr'.
Kwargs:
error[bool]: (Default: False) When True and 'dialog=True' the the "Critical" icon is included with the message.
warning[bool]: (Default: False) When True and 'dialog=True' the the "Critical" icon is included with the message.
traceback[bool]: (Default: False) When True the stack trace is printed with the message.
dialog[bool]: (Default: False) When true a QDialog object is created, the error will still print to the console as well.
color[str]: (Default: None) Add the bash color string to the message (see colorText).
debug[bool]: (Default: False) Print the message only if tools.MOOSE_DEBUG_MODE = True.
test[bool]: FOR TESTING ONLY! (Default: False) When True the QDialog is not executed, just returned.
indent[int]: Number of levels to indent (2 spaces are applied to each level) | A generic message function. | [
"A",
"generic",
"message",
"function",
"."
] | def mooseMessage(*args, **kwargs):
"""
A generic message function.
Args:
args[tuple]: Comma separated items to be printed, non strings are converted with 'repr'.
Kwargs:
error[bool]: (Default: False) When True and 'dialog=True' the the "Critical" icon is included with the message.
warning[bool]: (Default: False) When True and 'dialog=True' the the "Critical" icon is included with the message.
traceback[bool]: (Default: False) When True the stack trace is printed with the message.
dialog[bool]: (Default: False) When true a QDialog object is created, the error will still print to the console as well.
color[str]: (Default: None) Add the bash color string to the message (see colorText).
debug[bool]: (Default: False) Print the message only if tools.MOOSE_DEBUG_MODE = True.
test[bool]: FOR TESTING ONLY! (Default: False) When True the QDialog is not executed, just returned.
indent[int]: Number of levels to indent (2 spaces are applied to each level)
"""
# Grab the options
error = kwargs.pop('error', False)
warning = kwargs.pop('warning', False)
trace = kwargs.pop('traceback', False)
dialog = kwargs.pop('dialog', False)
color = kwargs.pop('color', None)
test = kwargs.pop('test', False)
indent = kwargs.pop('indent', 0)
# Build the message
message = []
for arg in args:
if not isinstance(arg, str):
message.append(repr(arg))
else:
message.append(arg)
message = '{}{}'.format(' '*2*indent, ' '.join(message))
# Show a dialog box
if MOOSE_USE_QT5 and dialog and not MOOSE_TESTING_MODE:
box = QtWidgets.QMessageBox()
box.setText(message)
if warning:
box.setIcon(QtWidgets.QMessageBox.Warning)
elif error:
box.setIcon(QtWidgets.QMessageBox.Critical)
if test:
return box
box.exec_()
# Emit the message to any listeners
if MOOSE_USE_QT5:
messageEmitter.write(message, color)
# Print the message to screen
if color:
message = colorText(message, color)
print(message)
# Show the traceback
if trace and MOOSE_USE_QT5:
traceback.print_stack()
stack = ''.join(traceback.format_stack())
messageEmitter.write(stack, color) | [
"def",
"mooseMessage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Grab the options",
"error",
"=",
"kwargs",
".",
"pop",
"(",
"'error'",
",",
"False",
")",
"warning",
"=",
"kwargs",
".",
"pop",
"(",
"'warning'",
",",
"False",
")",
"trace",
"=",
"kwargs",
".",
"pop",
"(",
"'traceback'",
",",
"False",
")",
"dialog",
"=",
"kwargs",
".",
"pop",
"(",
"'dialog'",
",",
"False",
")",
"color",
"=",
"kwargs",
".",
"pop",
"(",
"'color'",
",",
"None",
")",
"test",
"=",
"kwargs",
".",
"pop",
"(",
"'test'",
",",
"False",
")",
"indent",
"=",
"kwargs",
".",
"pop",
"(",
"'indent'",
",",
"0",
")",
"# Build the message",
"message",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"message",
".",
"append",
"(",
"repr",
"(",
"arg",
")",
")",
"else",
":",
"message",
".",
"append",
"(",
"arg",
")",
"message",
"=",
"'{}{}'",
".",
"format",
"(",
"' '",
"*",
"2",
"*",
"indent",
",",
"' '",
".",
"join",
"(",
"message",
")",
")",
"# Show a dialog box",
"if",
"MOOSE_USE_QT5",
"and",
"dialog",
"and",
"not",
"MOOSE_TESTING_MODE",
":",
"box",
"=",
"QtWidgets",
".",
"QMessageBox",
"(",
")",
"box",
".",
"setText",
"(",
"message",
")",
"if",
"warning",
":",
"box",
".",
"setIcon",
"(",
"QtWidgets",
".",
"QMessageBox",
".",
"Warning",
")",
"elif",
"error",
":",
"box",
".",
"setIcon",
"(",
"QtWidgets",
".",
"QMessageBox",
".",
"Critical",
")",
"if",
"test",
":",
"return",
"box",
"box",
".",
"exec_",
"(",
")",
"# Emit the message to any listeners",
"if",
"MOOSE_USE_QT5",
":",
"messageEmitter",
".",
"write",
"(",
"message",
",",
"color",
")",
"# Print the message to screen",
"if",
"color",
":",
"message",
"=",
"colorText",
"(",
"message",
",",
"color",
")",
"print",
"(",
"message",
")",
"# Show the traceback",
"if",
"trace",
"and",
"MOOSE_USE_QT5",
":",
"traceback",
".",
"print_stack",
"(",
")",
"stack",
"=",
"''",
".",
"join",
"(",
"traceback",
".",
"format_stack",
"(",
")",
")",
"messageEmitter",
".",
"write",
"(",
"stack",
",",
"color",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/message.py#L39-L101 | ||
TheLegendAli/DeepLab-Context | fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c | python/caffe/pycaffe.py | python | _Net_forward | (self, blobs=None, start=None, end=None, **kwargs) | return {out: self.blobs[out].data for out in outputs} | Forward pass: prepare inputs and run the net forward.
Take
blobs: list of blobs to return in addition to output blobs.
kwargs: Keys are input blob names and values are blob ndarrays.
For formatting inputs for Caffe, see Net.preprocess().
If None, input is taken from data layers.
start: optional name of layer at which to begin the forward pass
end: optional name of layer at which to finish the forward pass (inclusive)
Give
outs: {blob name: blob ndarray} dict. | Forward pass: prepare inputs and run the net forward. | [
"Forward",
"pass",
":",
"prepare",
"inputs",
"and",
"run",
"the",
"net",
"forward",
"."
] | def _Net_forward(self, blobs=None, start=None, end=None, **kwargs):
"""
Forward pass: prepare inputs and run the net forward.
Take
blobs: list of blobs to return in addition to output blobs.
kwargs: Keys are input blob names and values are blob ndarrays.
For formatting inputs for Caffe, see Net.preprocess().
If None, input is taken from data layers.
start: optional name of layer at which to begin the forward pass
end: optional name of layer at which to finish the forward pass (inclusive)
Give
outs: {blob name: blob ndarray} dict.
"""
if blobs is None:
blobs = []
if start is not None:
start_ind = list(self._layer_names).index(start)
else:
start_ind = 0
if end is not None:
end_ind = list(self._layer_names).index(end)
outputs = set([end] + blobs)
else:
end_ind = len(self.layers) - 1
outputs = set(self.outputs + blobs)
if kwargs:
if set(kwargs.keys()) != set(self.inputs):
raise Exception('Input blob arguments do not match net inputs.')
# Set input according to defined shapes and make arrays single and
# C-contiguous as Caffe expects.
for in_, blob in kwargs.iteritems():
if blob.ndim != 4:
raise Exception('{} blob is not 4-d'.format(in_))
if blob.shape[0] != self.blobs[in_].num:
raise Exception('Input is not batch sized')
self.blobs[in_].data[...] = blob
self._forward(start_ind, end_ind)
# Unpack blobs to extract
return {out: self.blobs[out].data for out in outputs} | [
"def",
"_Net_forward",
"(",
"self",
",",
"blobs",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"blobs",
"is",
"None",
":",
"blobs",
"=",
"[",
"]",
"if",
"start",
"is",
"not",
"None",
":",
"start_ind",
"=",
"list",
"(",
"self",
".",
"_layer_names",
")",
".",
"index",
"(",
"start",
")",
"else",
":",
"start_ind",
"=",
"0",
"if",
"end",
"is",
"not",
"None",
":",
"end_ind",
"=",
"list",
"(",
"self",
".",
"_layer_names",
")",
".",
"index",
"(",
"end",
")",
"outputs",
"=",
"set",
"(",
"[",
"end",
"]",
"+",
"blobs",
")",
"else",
":",
"end_ind",
"=",
"len",
"(",
"self",
".",
"layers",
")",
"-",
"1",
"outputs",
"=",
"set",
"(",
"self",
".",
"outputs",
"+",
"blobs",
")",
"if",
"kwargs",
":",
"if",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"!=",
"set",
"(",
"self",
".",
"inputs",
")",
":",
"raise",
"Exception",
"(",
"'Input blob arguments do not match net inputs.'",
")",
"# Set input according to defined shapes and make arrays single and",
"# C-contiguous as Caffe expects.",
"for",
"in_",
",",
"blob",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"blob",
".",
"ndim",
"!=",
"4",
":",
"raise",
"Exception",
"(",
"'{} blob is not 4-d'",
".",
"format",
"(",
"in_",
")",
")",
"if",
"blob",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"blobs",
"[",
"in_",
"]",
".",
"num",
":",
"raise",
"Exception",
"(",
"'Input is not batch sized'",
")",
"self",
".",
"blobs",
"[",
"in_",
"]",
".",
"data",
"[",
"...",
"]",
"=",
"blob",
"self",
".",
"_forward",
"(",
"start_ind",
",",
"end_ind",
")",
"# Unpack blobs to extract",
"return",
"{",
"out",
":",
"self",
".",
"blobs",
"[",
"out",
"]",
".",
"data",
"for",
"out",
"in",
"outputs",
"}"
] | https://github.com/TheLegendAli/DeepLab-Context/blob/fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c/python/caffe/pycaffe.py#L38-L83 | |
esa/pykep | b410363653623730b577de257c04b0e0289f2014 | pykep/trajopt/_indirect.py | python | indirect_pt2or.__init__ | (self, x0, elemf, mass, thrust, isp, atol, rtol, tof, freetime=True, alpha=1, bound=True, mu=pk.MU_SUN) | Initialises ``pykep.trajopt.indirect_pt2or`` problem.
Args:
- x0 (``list``, ``tuple``, ``numpy.ndarray``): Departure state [m, m, m, m/s, m/s, m/s, kg].
- elemf (``list``, ``tuple``, ``numpy.ndarray``): Arrival Keplerian elements SI units. (mean anomaly will be changed).
- mass (``float``, ``int``): Spacecraft wet mass [kg].
- thrust (``float``, ``int``): Spacecraft maximum thrust [N].
- isp (``float``, ``int``): Spacecraft specific impulse [s].
- atol (``float``, ``int``): Absolute integration solution tolerance.
- rtol (``float``, ``int``): Relative integration solution tolerance.
- tof (``list``): Transfer time bounds [days].
- freetime (``bool``): Activates final time transversality condition. Allows final time to vary.
- alpha (``float``, ``int``): Homotopy parameter, governing the degree to which the theoretical control law is intended to reduce propellant expenditure or energy.
- bound (``bool``): Activates bounded control, in which the control throttle is bounded between 0 and 1, otherwise the control throttle is allowed to unbounded.
- mu (``float``): Gravitational parameter of primary body [m^3/s^2]. | Initialises ``pykep.trajopt.indirect_pt2or`` problem. | [
"Initialises",
"pykep",
".",
"trajopt",
".",
"indirect_pt2or",
"problem",
"."
] | def __init__(self, x0, elemf, mass, thrust, isp, atol, rtol, tof, freetime=True, alpha=1, bound=True, mu=pk.MU_SUN):
"""Initialises ``pykep.trajopt.indirect_pt2or`` problem.
Args:
- x0 (``list``, ``tuple``, ``numpy.ndarray``): Departure state [m, m, m, m/s, m/s, m/s, kg].
- elemf (``list``, ``tuple``, ``numpy.ndarray``): Arrival Keplerian elements SI units. (mean anomaly will be changed).
- mass (``float``, ``int``): Spacecraft wet mass [kg].
- thrust (``float``, ``int``): Spacecraft maximum thrust [N].
- isp (``float``, ``int``): Spacecraft specific impulse [s].
- atol (``float``, ``int``): Absolute integration solution tolerance.
- rtol (``float``, ``int``): Relative integration solution tolerance.
- tof (``list``): Transfer time bounds [days].
- freetime (``bool``): Activates final time transversality condition. Allows final time to vary.
- alpha (``float``, ``int``): Homotopy parameter, governing the degree to which the theoretical control law is intended to reduce propellant expenditure or energy.
- bound (``bool``): Activates bounded control, in which the control throttle is bounded between 0 and 1, otherwise the control throttle is allowed to unbounded.
- mu (``float``): Gravitational parameter of primary body [m^3/s^2].
"""
# initialise base
_indirect_base.__init__(
self, mass, thrust, isp, mu, True, freetime, alpha, bound,
atol, rtol
)
# departure state and arrival Keplerian elements
self.x0 = np.asarray(x0, np.float64)
self.elemf = np.asarray(elemf, np.float64)
self.tof = tof | [
"def",
"__init__",
"(",
"self",
",",
"x0",
",",
"elemf",
",",
"mass",
",",
"thrust",
",",
"isp",
",",
"atol",
",",
"rtol",
",",
"tof",
",",
"freetime",
"=",
"True",
",",
"alpha",
"=",
"1",
",",
"bound",
"=",
"True",
",",
"mu",
"=",
"pk",
".",
"MU_SUN",
")",
":",
"# initialise base",
"_indirect_base",
".",
"__init__",
"(",
"self",
",",
"mass",
",",
"thrust",
",",
"isp",
",",
"mu",
",",
"True",
",",
"freetime",
",",
"alpha",
",",
"bound",
",",
"atol",
",",
"rtol",
")",
"# departure state and arrival Keplerian elements",
"self",
".",
"x0",
"=",
"np",
".",
"asarray",
"(",
"x0",
",",
"np",
".",
"float64",
")",
"self",
".",
"elemf",
"=",
"np",
".",
"asarray",
"(",
"elemf",
",",
"np",
".",
"float64",
")",
"self",
".",
"tof",
"=",
"tof"
] | https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/trajopt/_indirect.py#L460-L488 | ||
microsoft/DirectXShaderCompiler | 8348ff8d9e0287610ba05d3a828e10af981a1c05 | tools/clang/utils/check_cfc/obj_diff.py | python | first_diff | (a, b, fromfile, tofile) | return difference | Returns the first few lines of a difference, if there is one. Python
diff can be very slow with large objects and the most interesting changes
are the first ones. Truncate data before sending to difflib. Returns None
is there is no difference. | Returns the first few lines of a difference, if there is one. Python
diff can be very slow with large objects and the most interesting changes
are the first ones. Truncate data before sending to difflib. Returns None
is there is no difference. | [
"Returns",
"the",
"first",
"few",
"lines",
"of",
"a",
"difference",
"if",
"there",
"is",
"one",
".",
"Python",
"diff",
"can",
"be",
"very",
"slow",
"with",
"large",
"objects",
"and",
"the",
"most",
"interesting",
"changes",
"are",
"the",
"first",
"ones",
".",
"Truncate",
"data",
"before",
"sending",
"to",
"difflib",
".",
"Returns",
"None",
"is",
"there",
"is",
"no",
"difference",
"."
] | def first_diff(a, b, fromfile, tofile):
"""Returns the first few lines of a difference, if there is one. Python
diff can be very slow with large objects and the most interesting changes
are the first ones. Truncate data before sending to difflib. Returns None
is there is no difference."""
# Find first diff
first_diff_idx = None
for idx, val in enumerate(a):
if val != b[idx]:
first_diff_idx = idx
break
if first_diff_idx == None:
# No difference
return None
# Diff to first line of diff plus some lines
context = 3
diff = difflib.unified_diff(a[:first_diff_idx+context],
b[:first_diff_idx+context],
fromfile,
tofile)
difference = "\n".join(diff)
if first_diff_idx + context < len(a):
difference += "\n*** Diff truncated ***"
return difference | [
"def",
"first_diff",
"(",
"a",
",",
"b",
",",
"fromfile",
",",
"tofile",
")",
":",
"# Find first diff",
"first_diff_idx",
"=",
"None",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"a",
")",
":",
"if",
"val",
"!=",
"b",
"[",
"idx",
"]",
":",
"first_diff_idx",
"=",
"idx",
"break",
"if",
"first_diff_idx",
"==",
"None",
":",
"# No difference",
"return",
"None",
"# Diff to first line of diff plus some lines",
"context",
"=",
"3",
"diff",
"=",
"difflib",
".",
"unified_diff",
"(",
"a",
"[",
":",
"first_diff_idx",
"+",
"context",
"]",
",",
"b",
"[",
":",
"first_diff_idx",
"+",
"context",
"]",
",",
"fromfile",
",",
"tofile",
")",
"difference",
"=",
"\"\\n\"",
".",
"join",
"(",
"diff",
")",
"if",
"first_diff_idx",
"+",
"context",
"<",
"len",
"(",
"a",
")",
":",
"difference",
"+=",
"\"\\n*** Diff truncated ***\"",
"return",
"difference"
] | https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/tools/clang/utils/check_cfc/obj_diff.py#L39-L65 | |
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/websockify/websockify/websocket.py | python | WebSocketServer.vmsg | (self, *args, **kwargs) | Same as msg() but as debug. | Same as msg() but as debug. | [
"Same",
"as",
"msg",
"()",
"but",
"as",
"debug",
"."
] | def vmsg(self, *args, **kwargs):
""" Same as msg() but as debug. """
self.logger.log(logging.DEBUG, *args, **kwargs) | [
"def",
"vmsg",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"logger",
".",
"log",
"(",
"logging",
".",
"DEBUG",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/websockify/websockify/websocket.py#L873-L875 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py | python | set_tf_cuda_clang | (environ_cp) | set TF_CUDA_CLANG action_env.
Args:
environ_cp: copy of the os.environ. | set TF_CUDA_CLANG action_env. | [
"set",
"TF_CUDA_CLANG",
"action_env",
"."
] | def set_tf_cuda_clang(environ_cp):
"""set TF_CUDA_CLANG action_env.
Args:
environ_cp: copy of the os.environ.
"""
question = 'Do you want to use clang as CUDA compiler?'
yes_reply = 'Clang will be used as CUDA compiler.'
no_reply = 'nvcc will be used as CUDA compiler.'
set_action_env_var(
environ_cp,
'TF_CUDA_CLANG',
None,
False,
question=question,
yes_reply=yes_reply,
no_reply=no_reply,
bazel_config_name='cuda_clang') | [
"def",
"set_tf_cuda_clang",
"(",
"environ_cp",
")",
":",
"question",
"=",
"'Do you want to use clang as CUDA compiler?'",
"yes_reply",
"=",
"'Clang will be used as CUDA compiler.'",
"no_reply",
"=",
"'nvcc will be used as CUDA compiler.'",
"set_action_env_var",
"(",
"environ_cp",
",",
"'TF_CUDA_CLANG'",
",",
"None",
",",
"False",
",",
"question",
"=",
"question",
",",
"yes_reply",
"=",
"yes_reply",
",",
"no_reply",
"=",
"no_reply",
",",
"bazel_config_name",
"=",
"'cuda_clang'",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py#L539-L556 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xmlNode.hasNsProp | (self, name, nameSpace) | return __tmp | Search for an attribute associated to a node This attribute
has to be anchored in the namespace specified. This does
the entity substitution. This function looks in DTD
attribute declaration for #FIXED or default declaration
values unless DTD use has been turned off. Note that a
namespace of None indicates to use the default namespace. | Search for an attribute associated to a node This attribute
has to be anchored in the namespace specified. This does
the entity substitution. This function looks in DTD
attribute declaration for #FIXED or default declaration
values unless DTD use has been turned off. Note that a
namespace of None indicates to use the default namespace. | [
"Search",
"for",
"an",
"attribute",
"associated",
"to",
"a",
"node",
"This",
"attribute",
"has",
"to",
"be",
"anchored",
"in",
"the",
"namespace",
"specified",
".",
"This",
"does",
"the",
"entity",
"substitution",
".",
"This",
"function",
"looks",
"in",
"DTD",
"attribute",
"declaration",
"for",
"#FIXED",
"or",
"default",
"declaration",
"values",
"unless",
"DTD",
"use",
"has",
"been",
"turned",
"off",
".",
"Note",
"that",
"a",
"namespace",
"of",
"None",
"indicates",
"to",
"use",
"the",
"default",
"namespace",
"."
] | def hasNsProp(self, name, nameSpace):
"""Search for an attribute associated to a node This attribute
has to be anchored in the namespace specified. This does
the entity substitution. This function looks in DTD
attribute declaration for #FIXED or default declaration
values unless DTD use has been turned off. Note that a
namespace of None indicates to use the default namespace. """
ret = libxml2mod.xmlHasNsProp(self._o, name, nameSpace)
if ret is None:return None
__tmp = xmlAttr(_obj=ret)
return __tmp | [
"def",
"hasNsProp",
"(",
"self",
",",
"name",
",",
"nameSpace",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlHasNsProp",
"(",
"self",
".",
"_o",
",",
"name",
",",
"nameSpace",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"__tmp",
"=",
"xmlAttr",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L2484-L2494 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py | python | Pdb.do_retval | (self, arg) | retval
Print the return value for the last return of a function. | retval
Print the return value for the last return of a function. | [
"retval",
"Print",
"the",
"return",
"value",
"for",
"the",
"last",
"return",
"of",
"a",
"function",
"."
] | def do_retval(self, arg):
"""retval
Print the return value for the last return of a function.
"""
if '__return__' in self.curframe_locals:
self.message(repr(self.curframe_locals['__return__']))
else:
self.error('Not yet returned!') | [
"def",
"do_retval",
"(",
"self",
",",
"arg",
")",
":",
"if",
"'__return__'",
"in",
"self",
".",
"curframe_locals",
":",
"self",
".",
"message",
"(",
"repr",
"(",
"self",
".",
"curframe_locals",
"[",
"'__return__'",
"]",
")",
")",
"else",
":",
"self",
".",
"error",
"(",
"'Not yet returned!'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py#L1145-L1152 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | build/unix/makepchinput.py | python | getExtraIncludes | (headers) | return allHeadersPartContent | Add include files according to list | Add include files according to list | [
"Add",
"include",
"files",
"according",
"to",
"list"
] | def getExtraIncludes(headers):
"""
Add include files according to list
"""
allHeadersPartContent=""
for header in headers:
allHeadersPartContent+='#include "%s"\n' %header
return allHeadersPartContent | [
"def",
"getExtraIncludes",
"(",
"headers",
")",
":",
"allHeadersPartContent",
"=",
"\"\"",
"for",
"header",
"in",
"headers",
":",
"allHeadersPartContent",
"+=",
"'#include \"%s\"\\n'",
"%",
"header",
"return",
"allHeadersPartContent"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/build/unix/makepchinput.py#L164-L171 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py | python | Buffer.copy_selection | (self, _cut=False) | return clipboard_data | Copy selected text and return :class:`.ClipboardData` instance. | Copy selected text and return :class:`.ClipboardData` instance. | [
"Copy",
"selected",
"text",
"and",
"return",
":",
"class",
":",
".",
"ClipboardData",
"instance",
"."
] | def copy_selection(self, _cut=False):
"""
Copy selected text and return :class:`.ClipboardData` instance.
"""
new_document, clipboard_data = self.document.cut_selection()
if _cut:
self.document = new_document
self.selection_state = None
return clipboard_data | [
"def",
"copy_selection",
"(",
"self",
",",
"_cut",
"=",
"False",
")",
":",
"new_document",
",",
"clipboard_data",
"=",
"self",
".",
"document",
".",
"cut_selection",
"(",
")",
"if",
"_cut",
":",
"self",
".",
"document",
"=",
"new_document",
"self",
".",
"selection_state",
"=",
"None",
"return",
"clipboard_data"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py#L972-L981 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py | python | _augment_exception | (exc, version, arch='') | Add details to the exception message to help guide the user
as to what action will resolve it. | Add details to the exception message to help guide the user
as to what action will resolve it. | [
"Add",
"details",
"to",
"the",
"exception",
"message",
"to",
"help",
"guide",
"the",
"user",
"as",
"to",
"what",
"action",
"will",
"resolve",
"it",
"."
] | def _augment_exception(exc, version, arch=''):
"""
Add details to the exception message to help guide the user
as to what action will resolve it.
"""
# Error if MSVC++ directory not found or environment not set
message = exc.args[0]
if "vcvarsall" in message.lower() or "visual c" in message.lower():
# Special error message if MSVC++ not installed
tmpl = 'Microsoft Visual C++ {version:0.1f} is required.'
message = tmpl.format(**locals())
msdownload = 'www.microsoft.com/download/details.aspx?id=%d'
if version == 9.0:
if arch.lower().find('ia64') > -1:
# For VC++ 9.0, if IA64 support is needed, redirect user
# to Windows SDK 7.0
message += ' Get it with "Microsoft Windows SDK 7.0": '
message += msdownload % 3138
else:
# For VC++ 9.0 redirect user to Vc++ for Python 2.7 :
# This redirection link is maintained by Microsoft.
# Contact vspython@microsoft.com if it needs updating.
message += ' Get it from http://aka.ms/vcpython27'
elif version == 10.0:
# For VC++ 10.0 Redirect user to Windows SDK 7.1
message += ' Get it with "Microsoft Windows SDK 7.1": '
message += msdownload % 8279
elif version >= 14.0:
# For VC++ 14.0 Redirect user to Visual C++ Build Tools
message += (' Get it with "Microsoft Visual C++ Build Tools": '
r'http://landinghub.visualstudio.com/'
'visual-cpp-build-tools')
exc.args = (message, ) | [
"def",
"_augment_exception",
"(",
"exc",
",",
"version",
",",
"arch",
"=",
"''",
")",
":",
"# Error if MSVC++ directory not found or environment not set",
"message",
"=",
"exc",
".",
"args",
"[",
"0",
"]",
"if",
"\"vcvarsall\"",
"in",
"message",
".",
"lower",
"(",
")",
"or",
"\"visual c\"",
"in",
"message",
".",
"lower",
"(",
")",
":",
"# Special error message if MSVC++ not installed",
"tmpl",
"=",
"'Microsoft Visual C++ {version:0.1f} is required.'",
"message",
"=",
"tmpl",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"msdownload",
"=",
"'www.microsoft.com/download/details.aspx?id=%d'",
"if",
"version",
"==",
"9.0",
":",
"if",
"arch",
".",
"lower",
"(",
")",
".",
"find",
"(",
"'ia64'",
")",
">",
"-",
"1",
":",
"# For VC++ 9.0, if IA64 support is needed, redirect user",
"# to Windows SDK 7.0",
"message",
"+=",
"' Get it with \"Microsoft Windows SDK 7.0\": '",
"message",
"+=",
"msdownload",
"%",
"3138",
"else",
":",
"# For VC++ 9.0 redirect user to Vc++ for Python 2.7 :",
"# This redirection link is maintained by Microsoft.",
"# Contact vspython@microsoft.com if it needs updating.",
"message",
"+=",
"' Get it from http://aka.ms/vcpython27'",
"elif",
"version",
"==",
"10.0",
":",
"# For VC++ 10.0 Redirect user to Windows SDK 7.1",
"message",
"+=",
"' Get it with \"Microsoft Windows SDK 7.1\": '",
"message",
"+=",
"msdownload",
"%",
"8279",
"elif",
"version",
">=",
"14.0",
":",
"# For VC++ 14.0 Redirect user to Visual C++ Build Tools",
"message",
"+=",
"(",
"' Get it with \"Microsoft Visual C++ Build Tools\": '",
"r'http://landinghub.visualstudio.com/'",
"'visual-cpp-build-tools'",
")",
"exc",
".",
"args",
"=",
"(",
"message",
",",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py#L204-L238 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sgraph.py | python | SGraph.get_vertex_fields | (self) | Return a list of vertex attribute fields in the SGraph.
Returns
-------
out : list
Names of fields contained in the vertex data.
See Also
--------
get_fields, get_edge_fields
Examples
--------
>>> from graphlab import SGraph, Vertex, Edge
>>> g = SGraph()
>>> verts = [Vertex(0, attr={'name': 'alex'}),
Vertex(1, attr={'name': 'barbara'})]
>>> g = g.add_vertices(verts)
>>> g = g.add_edges(Edge(0, 1, attr={'frequency': 6}))
>>> fields = g.get_vertex_fields()
['__id', 'name'] | Return a list of vertex attribute fields in the SGraph. | [
"Return",
"a",
"list",
"of",
"vertex",
"attribute",
"fields",
"in",
"the",
"SGraph",
"."
] | def get_vertex_fields(self):
"""
Return a list of vertex attribute fields in the SGraph.
Returns
-------
out : list
Names of fields contained in the vertex data.
See Also
--------
get_fields, get_edge_fields
Examples
--------
>>> from graphlab import SGraph, Vertex, Edge
>>> g = SGraph()
>>> verts = [Vertex(0, attr={'name': 'alex'}),
Vertex(1, attr={'name': 'barbara'})]
>>> g = g.add_vertices(verts)
>>> g = g.add_edges(Edge(0, 1, attr={'frequency': 6}))
>>> fields = g.get_vertex_fields()
['__id', 'name']
"""
with cython_context():
return self.__proxy__.get_vertex_fields() | [
"def",
"get_vertex_fields",
"(",
"self",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"self",
".",
"__proxy__",
".",
"get_vertex_fields",
"(",
")"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sgraph.py#L757-L783 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/resource_group.py | python | ResourceGroup.add_parameters | (self, parameter_definitions, force=False) | return changed | Adds resource and parameter definitions to a resource group's resource-template.json file.
Args:
parameter_definitions: dictionary containing parameter definitions.
force (named): indicates if resource and parameter definitions replace existing definitions. Default is False.
Returns:
True if any definitions were added. | Adds resource and parameter definitions to a resource group's resource-template.json file. | [
"Adds",
"resource",
"and",
"parameter",
"definitions",
"to",
"a",
"resource",
"group",
"s",
"resource",
"-",
"template",
".",
"json",
"file",
"."
] | def add_parameters(self, parameter_definitions, force=False):
"""Adds resource and parameter definitions to a resource group's resource-template.json file.
Args:
parameter_definitions: dictionary containing parameter definitions.
force (named): indicates if resource and parameter definitions replace existing definitions. Default is False.
Returns:
True if any definitions were added.
"""
changed = False
parameters = util.dict_get_or_add(self.template, 'Parameters', {})
for parameter_name, parameter_definition in six.iteritems(parameter_definitions):
if parameter_name in parameters and not force:
self.__context.view.parameter_exists(self.template_path, parameter_name)
else:
self.__context.view.adding_parameter(self.template_path, parameter_name)
parameters[parameter_name] = parameter_definition
changed = True
return changed | [
"def",
"add_parameters",
"(",
"self",
",",
"parameter_definitions",
",",
"force",
"=",
"False",
")",
":",
"changed",
"=",
"False",
"parameters",
"=",
"util",
".",
"dict_get_or_add",
"(",
"self",
".",
"template",
",",
"'Parameters'",
",",
"{",
"}",
")",
"for",
"parameter_name",
",",
"parameter_definition",
"in",
"six",
".",
"iteritems",
"(",
"parameter_definitions",
")",
":",
"if",
"parameter_name",
"in",
"parameters",
"and",
"not",
"force",
":",
"self",
".",
"__context",
".",
"view",
".",
"parameter_exists",
"(",
"self",
".",
"template_path",
",",
"parameter_name",
")",
"else",
":",
"self",
".",
"__context",
".",
"view",
".",
"adding_parameter",
"(",
"self",
".",
"template_path",
",",
"parameter_name",
")",
"parameters",
"[",
"parameter_name",
"]",
"=",
"parameter_definition",
"changed",
"=",
"True",
"return",
"changed"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/resource_group.py#L447-L472 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Image.GetSubImage | (*args, **kwargs) | return _core_.Image_GetSubImage(*args, **kwargs) | GetSubImage(self, Rect rect) -> Image
Returns a sub image of the current one as long as the rect belongs
entirely to the image. | GetSubImage(self, Rect rect) -> Image | [
"GetSubImage",
"(",
"self",
"Rect",
"rect",
")",
"-",
">",
"Image"
] | def GetSubImage(*args, **kwargs):
"""
GetSubImage(self, Rect rect) -> Image
Returns a sub image of the current one as long as the rect belongs
entirely to the image.
"""
return _core_.Image_GetSubImage(*args, **kwargs) | [
"def",
"GetSubImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_GetSubImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3309-L3316 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/transforms/scalarize.py | python | log_sum_exp | (
objectives: List[Union[Minimize, Maximize]], weights, gamma: float = 1.0
) | return Minimize(expr) | Combines objectives as log_sum_exp of weighted terms.
The objective takes the form
log(sum_{i=1}^n exp(gamma*weights[i]*objectives[i]))/gamma
As gamma goes to 0, log_sum_exp approaches weighted_sum. As gamma goes to infinity,
log_sum_exp approaches max.
Args:
objectives: A list of Minimize/Maximize objectives.
weights: A vector of weights.
gamma: Parameter interpolating between weighted_sum and max.
Returns:
A Minimize objective. | Combines objectives as log_sum_exp of weighted terms. | [
"Combines",
"objectives",
"as",
"log_sum_exp",
"of",
"weighted",
"terms",
"."
] | def log_sum_exp(
objectives: List[Union[Minimize, Maximize]], weights, gamma: float = 1.0
) -> Minimize:
"""Combines objectives as log_sum_exp of weighted terms.
The objective takes the form
log(sum_{i=1}^n exp(gamma*weights[i]*objectives[i]))/gamma
As gamma goes to 0, log_sum_exp approaches weighted_sum. As gamma goes to infinity,
log_sum_exp approaches max.
Args:
objectives: A list of Minimize/Maximize objectives.
weights: A vector of weights.
gamma: Parameter interpolating between weighted_sum and max.
Returns:
A Minimize objective.
"""
num_objs = len(objectives)
terms = [(objectives[i]*weights[i]).args[0] for i in range(num_objs)]
expr = atoms.log_sum_exp(gamma*atoms.vstack(terms))/gamma
return Minimize(expr) | [
"def",
"log_sum_exp",
"(",
"objectives",
":",
"List",
"[",
"Union",
"[",
"Minimize",
",",
"Maximize",
"]",
"]",
",",
"weights",
",",
"gamma",
":",
"float",
"=",
"1.0",
")",
"->",
"Minimize",
":",
"num_objs",
"=",
"len",
"(",
"objectives",
")",
"terms",
"=",
"[",
"(",
"objectives",
"[",
"i",
"]",
"*",
"weights",
"[",
"i",
"]",
")",
".",
"args",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"num_objs",
")",
"]",
"expr",
"=",
"atoms",
".",
"log_sum_exp",
"(",
"gamma",
"*",
"atoms",
".",
"vstack",
"(",
"terms",
")",
")",
"/",
"gamma",
"return",
"Minimize",
"(",
"expr",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/transforms/scalarize.py#L109-L131 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/sql.py | python | SQLTable._execute_insert | (self, conn, keys, data_iter) | Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted | Execute SQL statement inserting data | [
"Execute",
"SQL",
"statement",
"inserting",
"data"
] | def _execute_insert(self, conn, keys, data_iter):
"""Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted
"""
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(), data) | [
"def",
"_execute_insert",
"(",
"self",
",",
"conn",
",",
"keys",
",",
"data_iter",
")",
":",
"data",
"=",
"[",
"dict",
"(",
"zip",
"(",
"keys",
",",
"row",
")",
")",
"for",
"row",
"in",
"data_iter",
"]",
"conn",
".",
"execute",
"(",
"self",
".",
"table",
".",
"insert",
"(",
")",
",",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/sql.py#L657-L669 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathWaterline.py | python | ObjectWaterline._findNextWlPoint | (self, lC, pC, cl, cp, pl, pp) | return [cl, cp, num] | _findNextWlPoint(lC, pC, cl, cp, pl, pp) ...
Find the next waterline point in the point cloud layer provided. | _findNextWlPoint(lC, pC, cl, cp, pl, pp) ...
Find the next waterline point in the point cloud layer provided. | [
"_findNextWlPoint",
"(",
"lC",
"pC",
"cl",
"cp",
"pl",
"pp",
")",
"...",
"Find",
"the",
"next",
"waterline",
"point",
"in",
"the",
"point",
"cloud",
"layer",
"provided",
"."
] | def _findNextWlPoint(self, lC, pC, cl, cp, pl, pp):
"""_findNextWlPoint(lC, pC, cl, cp, pl, pp) ...
Find the next waterline point in the point cloud layer provided."""
dl = cl - pl
dp = cp - pp
num = 0
i = 3
s = 0
mtch = 0
found = False
while mtch < 8: # check all 8 points around current point
if lC[i] == dl:
if pC[i] == dp:
s = i - 3
found = True
# Check for y branch where current point is connection between branches
for y in range(1, mtch):
if lC[i + y] == dl:
if pC[i + y] == dp:
num = 1
break
break
i += 1
mtch += 1
if found is False:
# ("_findNext: No start point found.")
return [cl, cp, num]
for r in range(0, 8):
l = cl + lC[s + r]
p = cp + pC[s + r]
if self.topoMap[l][p] == 1:
return [l, p, num]
# ("_findNext: No next pnt found")
return [cl, cp, num] | [
"def",
"_findNextWlPoint",
"(",
"self",
",",
"lC",
",",
"pC",
",",
"cl",
",",
"cp",
",",
"pl",
",",
"pp",
")",
":",
"dl",
"=",
"cl",
"-",
"pl",
"dp",
"=",
"cp",
"-",
"pp",
"num",
"=",
"0",
"i",
"=",
"3",
"s",
"=",
"0",
"mtch",
"=",
"0",
"found",
"=",
"False",
"while",
"mtch",
"<",
"8",
":",
"# check all 8 points around current point",
"if",
"lC",
"[",
"i",
"]",
"==",
"dl",
":",
"if",
"pC",
"[",
"i",
"]",
"==",
"dp",
":",
"s",
"=",
"i",
"-",
"3",
"found",
"=",
"True",
"# Check for y branch where current point is connection between branches",
"for",
"y",
"in",
"range",
"(",
"1",
",",
"mtch",
")",
":",
"if",
"lC",
"[",
"i",
"+",
"y",
"]",
"==",
"dl",
":",
"if",
"pC",
"[",
"i",
"+",
"y",
"]",
"==",
"dp",
":",
"num",
"=",
"1",
"break",
"break",
"i",
"+=",
"1",
"mtch",
"+=",
"1",
"if",
"found",
"is",
"False",
":",
"# (\"_findNext: No start point found.\")",
"return",
"[",
"cl",
",",
"cp",
",",
"num",
"]",
"for",
"r",
"in",
"range",
"(",
"0",
",",
"8",
")",
":",
"l",
"=",
"cl",
"+",
"lC",
"[",
"s",
"+",
"r",
"]",
"p",
"=",
"cp",
"+",
"pC",
"[",
"s",
"+",
"r",
"]",
"if",
"self",
".",
"topoMap",
"[",
"l",
"]",
"[",
"p",
"]",
"==",
"1",
":",
"return",
"[",
"l",
",",
"p",
",",
"num",
"]",
"# (\"_findNext: No next pnt found\")",
"return",
"[",
"cl",
",",
"cp",
",",
"num",
"]"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathWaterline.py#L1651-L1686 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py | python | SQLTable._execute_insert | (self, conn, keys, data_iter) | Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted | Execute SQL statement inserting data | [
"Execute",
"SQL",
"statement",
"inserting",
"data"
] | def _execute_insert(self, conn, keys, data_iter):
"""Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted
"""
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(), data) | [
"def",
"_execute_insert",
"(",
"self",
",",
"conn",
",",
"keys",
",",
"data_iter",
")",
":",
"data",
"=",
"[",
"dict",
"(",
"zip",
"(",
"keys",
",",
"row",
")",
")",
"for",
"row",
"in",
"data_iter",
"]",
"conn",
".",
"execute",
"(",
"self",
".",
"table",
".",
"insert",
"(",
")",
",",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py#L657-L669 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/libevent/event_rpcgen.py | python | EntryArray.GetDeclaration | (self, funcname) | return code | Allows direct access to elements of the array. | Allows direct access to elements of the array. | [
"Allows",
"direct",
"access",
"to",
"elements",
"of",
"the",
"array",
"."
] | def GetDeclaration(self, funcname):
"""Allows direct access to elements of the array."""
translate = self.GetTranslation()
translate["funcname"] = funcname
code = [
'int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);' %
translate ]
return code | [
"def",
"GetDeclaration",
"(",
"self",
",",
"funcname",
")",
":",
"translate",
"=",
"self",
".",
"GetTranslation",
"(",
")",
"translate",
"[",
"\"funcname\"",
"]",
"=",
"funcname",
"code",
"=",
"[",
"'int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);'",
"%",
"translate",
"]",
"return",
"code"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/libevent/event_rpcgen.py#L865-L872 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py | python | Logger.error | (self, msg, *args, **kwargs) | Log 'msg % args' with severity 'ERROR'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.error("Houston, we have a %s", "major problem", exc_info=1) | Log 'msg % args' with severity 'ERROR'. | [
"Log",
"msg",
"%",
"args",
"with",
"severity",
"ERROR",
"."
] | def error(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'ERROR'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.error("Houston, we have a %s", "major problem", exc_info=1)
"""
if self.isEnabledFor(ERROR):
self._log(ERROR, msg, args, **kwargs) | [
"def",
"error",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"ERROR",
")",
":",
"self",
".",
"_log",
"(",
"ERROR",
",",
"msg",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py#L1397-L1407 | ||
h0x91b/redis-v8 | ac8b9d49701d75bcee3719892a2a6a50b437e47a | redis/deps/v8/tools/stats-viewer.py | python | ChromeCounterCollection.Counter | (self, i) | return ChromeCounter(self.data, name_offset, value_offset) | Return the i'th counter. | Return the i'th counter. | [
"Return",
"the",
"i",
"th",
"counter",
"."
] | def Counter(self, i):
"""Return the i'th counter."""
name_offset = self.counter_names_offset + i * self._COUNTER_NAME_SIZE
value_offset = self.counter_values_offset + i * self.max_threads * 4
return ChromeCounter(self.data, name_offset, value_offset) | [
"def",
"Counter",
"(",
"self",
",",
"i",
")",
":",
"name_offset",
"=",
"self",
".",
"counter_names_offset",
"+",
"i",
"*",
"self",
".",
"_COUNTER_NAME_SIZE",
"value_offset",
"=",
"self",
".",
"counter_values_offset",
"+",
"i",
"*",
"self",
".",
"max_threads",
"*",
"4",
"return",
"ChromeCounter",
"(",
"self",
".",
"data",
",",
"name_offset",
",",
"value_offset",
")"
] | https://github.com/h0x91b/redis-v8/blob/ac8b9d49701d75bcee3719892a2a6a50b437e47a/redis/deps/v8/tools/stats-viewer.py#L444-L448 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/framework.py | python | IrNode.outputs | (self) | return [IrNode(n) for n in self.node.outputs] | Return the node outputs.
Returns:
list(IrNode): node outputs wrapped by IrNode. | Return the node outputs. | [
"Return",
"the",
"node",
"outputs",
"."
] | def outputs(self):
"""
Return the node outputs.
Returns:
list(IrNode): node outputs wrapped by IrNode.
"""
return [IrNode(n) for n in self.node.outputs] | [
"def",
"outputs",
"(",
"self",
")",
":",
"return",
"[",
"IrNode",
"(",
"n",
")",
"for",
"n",
"in",
"self",
".",
"node",
".",
"outputs",
"]"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/framework.py#L3953-L3960 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py | python | Sanitizer.__delete_object_from_source | (self,key) | Deletes object with key from source bucket. | Deletes object with key from source bucket. | [
"Deletes",
"object",
"with",
"key",
"from",
"source",
"bucket",
"."
] | def __delete_object_from_source(self,key):
''' Deletes object with key from source bucket. '''
try:
self.s3_client.delete_object(Bucket=self.source_bucket, Key=key)
except Exception as error:
self.rejected_files.append(FileStatus(key, True, "Could not delete object after moving object to target bucket.", error)) | [
"def",
"__delete_object_from_source",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"self",
".",
"s3_client",
".",
"delete_object",
"(",
"Bucket",
"=",
"self",
".",
"source_bucket",
",",
"Key",
"=",
"key",
")",
"except",
"Exception",
"as",
"error",
":",
"self",
".",
"rejected_files",
".",
"append",
"(",
"FileStatus",
"(",
"key",
",",
"True",
",",
"\"Could not delete object after moving object to target bucket.\"",
",",
"error",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py#L153-L159 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/mac_tool.py | python | MacTool.ExecMergeInfoPlist | (self, output, *inputs) | Merge multiple .plist files into a single .plist file. | Merge multiple .plist files into a single .plist file. | [
"Merge",
"multiple",
".",
"plist",
"files",
"into",
"a",
"single",
".",
"plist",
"file",
"."
] | def ExecMergeInfoPlist(self, output, *inputs):
"""Merge multiple .plist files into a single .plist file."""
merged_plist = {}
for path in inputs:
plist = self._LoadPlistMaybeBinary(path)
self._MergePlist(merged_plist, plist)
plistlib.writePlist(merged_plist, output) | [
"def",
"ExecMergeInfoPlist",
"(",
"self",
",",
"output",
",",
"*",
"inputs",
")",
":",
"merged_plist",
"=",
"{",
"}",
"for",
"path",
"in",
"inputs",
":",
"plist",
"=",
"self",
".",
"_LoadPlistMaybeBinary",
"(",
"path",
")",
"self",
".",
"_MergePlist",
"(",
"merged_plist",
",",
"plist",
")",
"plistlib",
".",
"writePlist",
"(",
"merged_plist",
",",
"output",
")"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/mac_tool.py#L344-L350 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/_multivariate.py | python | wishart_gen._mode | (self, dim, df, scale) | return out | Parameters
----------
dim : int
Dimension of the scale matrix
%(_doc_default_callparams)s
Notes
-----
As this function does no argument checking, it should not be
called directly; use 'mode' instead. | Parameters
----------
dim : int
Dimension of the scale matrix
%(_doc_default_callparams)s | [
"Parameters",
"----------",
"dim",
":",
"int",
"Dimension",
"of",
"the",
"scale",
"matrix",
"%",
"(",
"_doc_default_callparams",
")",
"s"
] | def _mode(self, dim, df, scale):
"""
Parameters
----------
dim : int
Dimension of the scale matrix
%(_doc_default_callparams)s
Notes
-----
As this function does no argument checking, it should not be
called directly; use 'mode' instead.
"""
if df >= dim + 1:
out = (df-dim-1) * scale
else:
out = None
return out | [
"def",
"_mode",
"(",
"self",
",",
"dim",
",",
"df",
",",
"scale",
")",
":",
"if",
"df",
">=",
"dim",
"+",
"1",
":",
"out",
"=",
"(",
"df",
"-",
"dim",
"-",
"1",
")",
"*",
"scale",
"else",
":",
"out",
"=",
"None",
"return",
"out"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L1748-L1766 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/msw/gizmos.py | python | StaticPicture.SetScale | (*args, **kwargs) | return _gizmos.StaticPicture_SetScale(*args, **kwargs) | SetScale(self, int scale) | SetScale(self, int scale) | [
"SetScale",
"(",
"self",
"int",
"scale",
")"
] | def SetScale(*args, **kwargs):
"""SetScale(self, int scale)"""
return _gizmos.StaticPicture_SetScale(*args, **kwargs) | [
"def",
"SetScale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"StaticPicture_SetScale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L1023-L1025 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/eigen_3.3.9/debug/gdb/printers.py | python | EigenQuaternionPrinter.__init__ | (self, val) | Extract all the necessary information | Extract all the necessary information | [
"Extract",
"all",
"the",
"necessary",
"information"
] | def __init__(self, val):
"Extract all the necessary information"
# The gdb extension does not support value template arguments - need to extract them by hand
type = val.type
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
self.type = type.unqualified().strip_typedefs()
self.innerType = self.type.template_argument(0)
self.val = val
# Quaternions have a struct as their storage, so we need to walk through this
self.data = self.val['m_coeffs']['m_storage']['m_data']['array']
self.data = self.data.cast(self.innerType.pointer()) | [
"def",
"__init__",
"(",
"self",
",",
"val",
")",
":",
"# The gdb extension does not support value template arguments - need to extract them by hand",
"type",
"=",
"val",
".",
"type",
"if",
"type",
".",
"code",
"==",
"gdb",
".",
"TYPE_CODE_REF",
":",
"type",
"=",
"type",
".",
"target",
"(",
")",
"self",
".",
"type",
"=",
"type",
".",
"unqualified",
"(",
")",
".",
"strip_typedefs",
"(",
")",
"self",
".",
"innerType",
"=",
"self",
".",
"type",
".",
"template_argument",
"(",
"0",
")",
"self",
".",
"val",
"=",
"val",
"# Quaternions have a struct as their storage, so we need to walk through this",
"self",
".",
"data",
"=",
"self",
".",
"val",
"[",
"'m_coeffs'",
"]",
"[",
"'m_storage'",
"]",
"[",
"'m_data'",
"]",
"[",
"'array'",
"]",
"self",
".",
"data",
"=",
"self",
".",
"data",
".",
"cast",
"(",
"self",
".",
"innerType",
".",
"pointer",
"(",
")",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/eigen_3.3.9/debug/gdb/printers.py#L135-L147 | ||
google/mediapipe | e6c19885c6d3c6f410c730952aeed2852790d306 | mediapipe/python/solutions/face_detection.py | python | FaceDetection.process | (self, image: np.ndarray) | return super().process(input_data={'image': image}) | Processes an RGB image and returns a list of the detected face location data.
Args:
image: An RGB image represented as a numpy ndarray.
Raises:
RuntimeError: If the underlying graph throws any error.
ValueError: If the input image is not three channel RGB.
Returns:
A NamedTuple object with a "detections" field that contains a list of the
detected face location data. | Processes an RGB image and returns a list of the detected face location data. | [
"Processes",
"an",
"RGB",
"image",
"and",
"returns",
"a",
"list",
"of",
"the",
"detected",
"face",
"location",
"data",
"."
] | def process(self, image: np.ndarray) -> NamedTuple:
"""Processes an RGB image and returns a list of the detected face location data.
Args:
image: An RGB image represented as a numpy ndarray.
Raises:
RuntimeError: If the underlying graph throws any error.
ValueError: If the input image is not three channel RGB.
Returns:
A NamedTuple object with a "detections" field that contains a list of the
detected face location data.
"""
return super().process(input_data={'image': image}) | [
"def",
"process",
"(",
"self",
",",
"image",
":",
"np",
".",
"ndarray",
")",
"->",
"NamedTuple",
":",
"return",
"super",
"(",
")",
".",
"process",
"(",
"input_data",
"=",
"{",
"'image'",
":",
"image",
"}",
")"
] | https://github.com/google/mediapipe/blob/e6c19885c6d3c6f410c730952aeed2852790d306/mediapipe/python/solutions/face_detection.py#L97-L112 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TNEANet.BegEAStrI | (self, *args) | return _snap.TNEANet_BegEAStrI(self, *args) | BegEAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegEAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const & | BegEAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI | [
"BegEAStrI",
"(",
"TNEANet",
"self",
"TStr",
"attr",
")",
"-",
">",
"TNEANet",
"::",
"TAStrI"
] | def BegEAStrI(self, *args):
"""
BegEAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegEAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegEAStrI(self, *args) | [
"def",
"BegEAStrI",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TNEANet_BegEAStrI",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L22680-L22693 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/dygraph_sharding_optimizer.py | python | DygraphShardingOptimizer._map_param_to_rank | (self) | return mapping | mapping parameters to the shard which holds it.
Return:
Dict[str, int] | mapping parameters to the shard which holds it. | [
"mapping",
"parameters",
"to",
"the",
"shard",
"which",
"holds",
"it",
"."
] | def _map_param_to_rank(self):
"""
mapping parameters to the shard which holds it.
Return:
Dict[str, int]
"""
mapping = {}
for rank, params in self._rank2params.items():
for param in params:
mapping[param.name] = rank
return mapping | [
"def",
"_map_param_to_rank",
"(",
"self",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"rank",
",",
"params",
"in",
"self",
".",
"_rank2params",
".",
"items",
"(",
")",
":",
"for",
"param",
"in",
"params",
":",
"mapping",
"[",
"param",
".",
"name",
"]",
"=",
"rank",
"return",
"mapping"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/dygraph_sharding_optimizer.py#L111-L122 | |
ideawu/ssdb | f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4 | deps/cpy/antlr3/tree.py | python | BaseTreeAdaptor.createToken | (self, fromToken=None, tokenType=None, text=None) | Tell me how to create a token for use with imaginary token nodes.
For example, there is probably no input symbol associated with imaginary
token DECL, but you need to create it as a payload or whatever for
the DECL node as in ^(DECL type ID).
If you care what the token payload objects' type is, you should
override this method and any other createToken variant. | Tell me how to create a token for use with imaginary token nodes.
For example, there is probably no input symbol associated with imaginary
token DECL, but you need to create it as a payload or whatever for
the DECL node as in ^(DECL type ID). | [
"Tell",
"me",
"how",
"to",
"create",
"a",
"token",
"for",
"use",
"with",
"imaginary",
"token",
"nodes",
".",
"For",
"example",
"there",
"is",
"probably",
"no",
"input",
"symbol",
"associated",
"with",
"imaginary",
"token",
"DECL",
"but",
"you",
"need",
"to",
"create",
"it",
"as",
"a",
"payload",
"or",
"whatever",
"for",
"the",
"DECL",
"node",
"as",
"in",
"^",
"(",
"DECL",
"type",
"ID",
")",
"."
] | def createToken(self, fromToken=None, tokenType=None, text=None):
"""
Tell me how to create a token for use with imaginary token nodes.
For example, there is probably no input symbol associated with imaginary
token DECL, but you need to create it as a payload or whatever for
the DECL node as in ^(DECL type ID).
If you care what the token payload objects' type is, you should
override this method and any other createToken variant.
"""
raise NotImplementedError | [
"def",
"createToken",
"(",
"self",
",",
"fromToken",
"=",
"None",
",",
"tokenType",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/tree.py#L1109-L1120 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py | python | _check_filter_and_make_params | (entity, includes, release_status=[], release_type=[]) | return params | Check that the status or type values are valid. Then, check that
the filters can be used with the given includes. Return a params
dict that can be passed to _do_mb_query. | Check that the status or type values are valid. Then, check that
the filters can be used with the given includes. Return a params
dict that can be passed to _do_mb_query. | [
"Check",
"that",
"the",
"status",
"or",
"type",
"values",
"are",
"valid",
".",
"Then",
"check",
"that",
"the",
"filters",
"can",
"be",
"used",
"with",
"the",
"given",
"includes",
".",
"Return",
"a",
"params",
"dict",
"that",
"can",
"be",
"passed",
"to",
"_do_mb_query",
"."
] | def _check_filter_and_make_params(entity, includes, release_status=[], release_type=[]):
"""Check that the status or type values are valid. Then, check that
the filters can be used with the given includes. Return a params
dict that can be passed to _do_mb_query.
"""
if isinstance(release_status, compat.basestring):
release_status = [release_status]
if isinstance(release_type, compat.basestring):
release_type = [release_type]
_check_filter(release_status, VALID_RELEASE_STATUSES)
_check_filter(release_type, VALID_RELEASE_TYPES)
if (release_status
and "releases" not in includes and entity != "release"):
raise InvalidFilterError("Can't have a status with no release include")
if (release_type
and "release-groups" not in includes and "releases" not in includes
and entity not in ["release-group", "release"]):
raise InvalidFilterError("Can't have a release type "
"with no releases or release-groups involved")
# Build parameters.
params = {}
if len(release_status):
params["status"] = "|".join(release_status)
if len(release_type):
params["type"] = "|".join(release_type)
return params | [
"def",
"_check_filter_and_make_params",
"(",
"entity",
",",
"includes",
",",
"release_status",
"=",
"[",
"]",
",",
"release_type",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"release_status",
",",
"compat",
".",
"basestring",
")",
":",
"release_status",
"=",
"[",
"release_status",
"]",
"if",
"isinstance",
"(",
"release_type",
",",
"compat",
".",
"basestring",
")",
":",
"release_type",
"=",
"[",
"release_type",
"]",
"_check_filter",
"(",
"release_status",
",",
"VALID_RELEASE_STATUSES",
")",
"_check_filter",
"(",
"release_type",
",",
"VALID_RELEASE_TYPES",
")",
"if",
"(",
"release_status",
"and",
"\"releases\"",
"not",
"in",
"includes",
"and",
"entity",
"!=",
"\"release\"",
")",
":",
"raise",
"InvalidFilterError",
"(",
"\"Can't have a status with no release include\"",
")",
"if",
"(",
"release_type",
"and",
"\"release-groups\"",
"not",
"in",
"includes",
"and",
"\"releases\"",
"not",
"in",
"includes",
"and",
"entity",
"not",
"in",
"[",
"\"release-group\"",
",",
"\"release\"",
"]",
")",
":",
"raise",
"InvalidFilterError",
"(",
"\"Can't have a release type \"",
"\"with no releases or release-groups involved\"",
")",
"# Build parameters.",
"params",
"=",
"{",
"}",
"if",
"len",
"(",
"release_status",
")",
":",
"params",
"[",
"\"status\"",
"]",
"=",
"\"|\"",
".",
"join",
"(",
"release_status",
")",
"if",
"len",
"(",
"release_type",
")",
":",
"params",
"[",
"\"type\"",
"]",
"=",
"\"|\"",
".",
"join",
"(",
"release_type",
")",
"return",
"params"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py#L236-L263 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.AnnotationGetStyles | (*args, **kwargs) | return _stc.StyledTextCtrl_AnnotationGetStyles(*args, **kwargs) | AnnotationGetStyles(self, int line) -> String
Get the annotation styles for a line | AnnotationGetStyles(self, int line) -> String | [
"AnnotationGetStyles",
"(",
"self",
"int",
"line",
")",
"-",
">",
"String"
] | def AnnotationGetStyles(*args, **kwargs):
"""
AnnotationGetStyles(self, int line) -> String
Get the annotation styles for a line
"""
return _stc.StyledTextCtrl_AnnotationGetStyles(*args, **kwargs) | [
"def",
"AnnotationGetStyles",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_AnnotationGetStyles",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L5959-L5965 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/dist.py | python | Distribution.parse_command_line | (self) | return True | Parse the setup script's command line, taken from the
'script_args' instance attribute (which defaults to 'sys.argv[1:]'
-- see 'setup()' in core.py). This list is first processed for
"global options" -- options that set attributes of the Distribution
instance. Then, it is alternately scanned for Distutils commands
and options for that command. Each new command terminates the
options for the previous command. The allowed options for a
command are determined by the 'user_options' attribute of the
command class -- thus, we have to be able to load command classes
in order to parse the command line. Any error in that 'options'
attribute raises DistutilsGetoptError; any error on the
command-line raises DistutilsArgError. If no Distutils commands
were found on the command line, raises DistutilsArgError. Return
true if command-line was successfully parsed and we should carry
on with executing commands; false if no errors but we shouldn't
execute commands (currently, this only happens if user asks for
help). | Parse the setup script's command line, taken from the
'script_args' instance attribute (which defaults to 'sys.argv[1:]'
-- see 'setup()' in core.py). This list is first processed for
"global options" -- options that set attributes of the Distribution
instance. Then, it is alternately scanned for Distutils commands
and options for that command. Each new command terminates the
options for the previous command. The allowed options for a
command are determined by the 'user_options' attribute of the
command class -- thus, we have to be able to load command classes
in order to parse the command line. Any error in that 'options'
attribute raises DistutilsGetoptError; any error on the
command-line raises DistutilsArgError. If no Distutils commands
were found on the command line, raises DistutilsArgError. Return
true if command-line was successfully parsed and we should carry
on with executing commands; false if no errors but we shouldn't
execute commands (currently, this only happens if user asks for
help). | [
"Parse",
"the",
"setup",
"script",
"s",
"command",
"line",
"taken",
"from",
"the",
"script_args",
"instance",
"attribute",
"(",
"which",
"defaults",
"to",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"--",
"see",
"setup",
"()",
"in",
"core",
".",
"py",
")",
".",
"This",
"list",
"is",
"first",
"processed",
"for",
"global",
"options",
"--",
"options",
"that",
"set",
"attributes",
"of",
"the",
"Distribution",
"instance",
".",
"Then",
"it",
"is",
"alternately",
"scanned",
"for",
"Distutils",
"commands",
"and",
"options",
"for",
"that",
"command",
".",
"Each",
"new",
"command",
"terminates",
"the",
"options",
"for",
"the",
"previous",
"command",
".",
"The",
"allowed",
"options",
"for",
"a",
"command",
"are",
"determined",
"by",
"the",
"user_options",
"attribute",
"of",
"the",
"command",
"class",
"--",
"thus",
"we",
"have",
"to",
"be",
"able",
"to",
"load",
"command",
"classes",
"in",
"order",
"to",
"parse",
"the",
"command",
"line",
".",
"Any",
"error",
"in",
"that",
"options",
"attribute",
"raises",
"DistutilsGetoptError",
";",
"any",
"error",
"on",
"the",
"command",
"-",
"line",
"raises",
"DistutilsArgError",
".",
"If",
"no",
"Distutils",
"commands",
"were",
"found",
"on",
"the",
"command",
"line",
"raises",
"DistutilsArgError",
".",
"Return",
"true",
"if",
"command",
"-",
"line",
"was",
"successfully",
"parsed",
"and",
"we",
"should",
"carry",
"on",
"with",
"executing",
"commands",
";",
"false",
"if",
"no",
"errors",
"but",
"we",
"shouldn",
"t",
"execute",
"commands",
"(",
"currently",
"this",
"only",
"happens",
"if",
"user",
"asks",
"for",
"help",
")",
"."
] | def parse_command_line(self):
"""Parse the setup script's command line, taken from the
'script_args' instance attribute (which defaults to 'sys.argv[1:]'
-- see 'setup()' in core.py). This list is first processed for
"global options" -- options that set attributes of the Distribution
instance. Then, it is alternately scanned for Distutils commands
and options for that command. Each new command terminates the
options for the previous command. The allowed options for a
command are determined by the 'user_options' attribute of the
command class -- thus, we have to be able to load command classes
in order to parse the command line. Any error in that 'options'
attribute raises DistutilsGetoptError; any error on the
command-line raises DistutilsArgError. If no Distutils commands
were found on the command line, raises DistutilsArgError. Return
true if command-line was successfully parsed and we should carry
on with executing commands; false if no errors but we shouldn't
execute commands (currently, this only happens if user asks for
help).
"""
#
# We now have enough information to show the Macintosh dialog
# that allows the user to interactively specify the "command line".
#
toplevel_options = self._get_toplevel_options()
# We have to parse the command line a bit at a time -- global
# options, then the first command, then its options, and so on --
# because each command will be handled by a different class, and
# the options that are valid for a particular class aren't known
# until we have loaded the command class, which doesn't happen
# until we know what the command is.
self.commands = []
parser = FancyGetopt(toplevel_options + self.display_options)
parser.set_negative_aliases(self.negative_opt)
parser.set_aliases({'licence': 'license'})
args = parser.getopt(args=self.script_args, object=self)
option_order = parser.get_option_order()
log.set_verbosity(self.verbose)
# for display options we return immediately
if self.handle_display_options(option_order):
return
while args:
args = self._parse_command_opts(parser, args)
if args is None: # user asked for help (and got it)
return
# Handle the cases of --help as a "global" option, ie.
# "setup.py --help" and "setup.py --help command ...". For the
# former, we show global options (--verbose, --dry-run, etc.)
# and display-only options (--name, --version, etc.); for the
# latter, we omit the display-only options and show help for
# each command listed on the command line.
if self.help:
self._show_help(parser,
display_options=len(self.commands) == 0,
commands=self.commands)
return
# Oops, no commands found -- an end-user error
if not self.commands:
raise DistutilsArgError("no commands supplied")
# All is well: return true
return True | [
"def",
"parse_command_line",
"(",
"self",
")",
":",
"#",
"# We now have enough information to show the Macintosh dialog",
"# that allows the user to interactively specify the \"command line\".",
"#",
"toplevel_options",
"=",
"self",
".",
"_get_toplevel_options",
"(",
")",
"# We have to parse the command line a bit at a time -- global",
"# options, then the first command, then its options, and so on --",
"# because each command will be handled by a different class, and",
"# the options that are valid for a particular class aren't known",
"# until we have loaded the command class, which doesn't happen",
"# until we know what the command is.",
"self",
".",
"commands",
"=",
"[",
"]",
"parser",
"=",
"FancyGetopt",
"(",
"toplevel_options",
"+",
"self",
".",
"display_options",
")",
"parser",
".",
"set_negative_aliases",
"(",
"self",
".",
"negative_opt",
")",
"parser",
".",
"set_aliases",
"(",
"{",
"'licence'",
":",
"'license'",
"}",
")",
"args",
"=",
"parser",
".",
"getopt",
"(",
"args",
"=",
"self",
".",
"script_args",
",",
"object",
"=",
"self",
")",
"option_order",
"=",
"parser",
".",
"get_option_order",
"(",
")",
"log",
".",
"set_verbosity",
"(",
"self",
".",
"verbose",
")",
"# for display options we return immediately",
"if",
"self",
".",
"handle_display_options",
"(",
"option_order",
")",
":",
"return",
"while",
"args",
":",
"args",
"=",
"self",
".",
"_parse_command_opts",
"(",
"parser",
",",
"args",
")",
"if",
"args",
"is",
"None",
":",
"# user asked for help (and got it)",
"return",
"# Handle the cases of --help as a \"global\" option, ie.",
"# \"setup.py --help\" and \"setup.py --help command ...\". For the",
"# former, we show global options (--verbose, --dry-run, etc.)",
"# and display-only options (--name, --version, etc.); for the",
"# latter, we omit the display-only options and show help for",
"# each command listed on the command line.",
"if",
"self",
".",
"help",
":",
"self",
".",
"_show_help",
"(",
"parser",
",",
"display_options",
"=",
"len",
"(",
"self",
".",
"commands",
")",
"==",
"0",
",",
"commands",
"=",
"self",
".",
"commands",
")",
"return",
"# Oops, no commands found -- an end-user error",
"if",
"not",
"self",
".",
"commands",
":",
"raise",
"DistutilsArgError",
"(",
"\"no commands supplied\"",
")",
"# All is well: return true",
"return",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/dist.py#L439-L504 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/examples/learn/resnet.py | python | res_net_model | (features, labels, mode) | return tf.estimator.EstimatorSpec(
mode, loss=loss, eval_metric_ops=eval_metric_ops) | Builds a residual network. | Builds a residual network. | [
"Builds",
"a",
"residual",
"network",
"."
] | def res_net_model(features, labels, mode):
"""Builds a residual network."""
# Configurations for each bottleneck group.
BottleneckGroup = namedtuple('BottleneckGroup',
['num_blocks', 'num_filters', 'bottleneck_size'])
groups = [
BottleneckGroup(3, 128, 32), BottleneckGroup(3, 256, 64),
BottleneckGroup(3, 512, 128), BottleneckGroup(3, 1024, 256)
]
x = features[X_FEATURE]
input_shape = x.get_shape().as_list()
# Reshape the input into the right shape if it's 2D tensor
if len(input_shape) == 2:
ndim = int(sqrt(input_shape[1]))
x = tf.reshape(x, [-1, ndim, ndim, 1])
# First convolution expands to 64 channels
with tf.variable_scope('conv_layer1'):
net = tf.layers.conv2d(
x,
filters=64,
kernel_size=7,
activation=tf.nn.relu)
net = tf.layers.batch_normalization(net)
# Max pool
net = tf.layers.max_pooling2d(
net, pool_size=3, strides=2, padding='same')
# First chain of resnets
with tf.variable_scope('conv_layer2'):
net = tf.layers.conv2d(
net,
filters=groups[0].num_filters,
kernel_size=1,
padding='valid')
# Create the bottleneck groups, each of which contains `num_blocks`
# bottleneck groups.
for group_i, group in enumerate(groups):
for block_i in range(group.num_blocks):
name = 'group_%d/block_%d' % (group_i, block_i)
# 1x1 convolution responsible for reducing dimension
with tf.variable_scope(name + '/conv_in'):
conv = tf.layers.conv2d(
net,
filters=group.num_filters,
kernel_size=1,
padding='valid',
activation=tf.nn.relu)
conv = tf.layers.batch_normalization(conv)
with tf.variable_scope(name + '/conv_bottleneck'):
conv = tf.layers.conv2d(
conv,
filters=group.bottleneck_size,
kernel_size=3,
padding='same',
activation=tf.nn.relu)
conv = tf.layers.batch_normalization(conv)
# 1x1 convolution responsible for restoring dimension
with tf.variable_scope(name + '/conv_out'):
input_dim = net.get_shape()[-1].value
conv = tf.layers.conv2d(
conv,
filters=input_dim,
kernel_size=1,
padding='valid',
activation=tf.nn.relu)
conv = tf.layers.batch_normalization(conv)
# shortcut connections that turn the network into its counterpart
# residual function (identity shortcut)
net = conv + net
try:
# upscale to the next group size
next_group = groups[group_i + 1]
with tf.variable_scope('block_%d/conv_upscale' % group_i):
net = tf.layers.conv2d(
net,
filters=next_group.num_filters,
kernel_size=1,
padding='same',
activation=None,
bias_initializer=None)
except IndexError:
pass
net_shape = net.get_shape().as_list()
net = tf.nn.avg_pool(
net,
ksize=[1, net_shape[1], net_shape[2], 1],
strides=[1, 1, 1, 1],
padding='VALID')
net_shape = net.get_shape().as_list()
net = tf.reshape(net, [-1, net_shape[1] * net_shape[2] * net_shape[3]])
# Compute logits (1 per class) and compute loss.
logits = tf.layers.dense(net, N_DIGITS, activation=None)
# Compute predictions.
predicted_classes = tf.argmax(logits, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
'class': predicted_classes,
'prob': tf.nn.softmax(logits)
}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
# Compute loss.
onehot_labels = tf.one_hot(tf.cast(labels, tf.int32), N_DIGITS, 1, 0)
loss = tf.losses.softmax_cross_entropy(
onehot_labels=onehot_labels, logits=logits)
# Create training op.
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.AdagradOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
# Compute evaluation metrics.
eval_metric_ops = {
'accuracy': tf.metrics.accuracy(
labels=labels, predictions=predicted_classes)
}
return tf.estimator.EstimatorSpec(
mode, loss=loss, eval_metric_ops=eval_metric_ops) | [
"def",
"res_net_model",
"(",
"features",
",",
"labels",
",",
"mode",
")",
":",
"# Configurations for each bottleneck group.",
"BottleneckGroup",
"=",
"namedtuple",
"(",
"'BottleneckGroup'",
",",
"[",
"'num_blocks'",
",",
"'num_filters'",
",",
"'bottleneck_size'",
"]",
")",
"groups",
"=",
"[",
"BottleneckGroup",
"(",
"3",
",",
"128",
",",
"32",
")",
",",
"BottleneckGroup",
"(",
"3",
",",
"256",
",",
"64",
")",
",",
"BottleneckGroup",
"(",
"3",
",",
"512",
",",
"128",
")",
",",
"BottleneckGroup",
"(",
"3",
",",
"1024",
",",
"256",
")",
"]",
"x",
"=",
"features",
"[",
"X_FEATURE",
"]",
"input_shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"# Reshape the input into the right shape if it's 2D tensor",
"if",
"len",
"(",
"input_shape",
")",
"==",
"2",
":",
"ndim",
"=",
"int",
"(",
"sqrt",
"(",
"input_shape",
"[",
"1",
"]",
")",
")",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
",",
"ndim",
",",
"ndim",
",",
"1",
"]",
")",
"# First convolution expands to 64 channels",
"with",
"tf",
".",
"variable_scope",
"(",
"'conv_layer1'",
")",
":",
"net",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"x",
",",
"filters",
"=",
"64",
",",
"kernel_size",
"=",
"7",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"net",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"net",
")",
"# Max pool",
"net",
"=",
"tf",
".",
"layers",
".",
"max_pooling2d",
"(",
"net",
",",
"pool_size",
"=",
"3",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"'same'",
")",
"# First chain of resnets",
"with",
"tf",
".",
"variable_scope",
"(",
"'conv_layer2'",
")",
":",
"net",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"net",
",",
"filters",
"=",
"groups",
"[",
"0",
"]",
".",
"num_filters",
",",
"kernel_size",
"=",
"1",
",",
"padding",
"=",
"'valid'",
")",
"# Create the bottleneck groups, each of which contains `num_blocks`",
"# bottleneck groups.",
"for",
"group_i",
",",
"group",
"in",
"enumerate",
"(",
"groups",
")",
":",
"for",
"block_i",
"in",
"range",
"(",
"group",
".",
"num_blocks",
")",
":",
"name",
"=",
"'group_%d/block_%d'",
"%",
"(",
"group_i",
",",
"block_i",
")",
"# 1x1 convolution responsible for reducing dimension",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
"+",
"'/conv_in'",
")",
":",
"conv",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"net",
",",
"filters",
"=",
"group",
".",
"num_filters",
",",
"kernel_size",
"=",
"1",
",",
"padding",
"=",
"'valid'",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"conv",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"conv",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
"+",
"'/conv_bottleneck'",
")",
":",
"conv",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"conv",
",",
"filters",
"=",
"group",
".",
"bottleneck_size",
",",
"kernel_size",
"=",
"3",
",",
"padding",
"=",
"'same'",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"conv",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"conv",
")",
"# 1x1 convolution responsible for restoring dimension",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
"+",
"'/conv_out'",
")",
":",
"input_dim",
"=",
"net",
".",
"get_shape",
"(",
")",
"[",
"-",
"1",
"]",
".",
"value",
"conv",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"conv",
",",
"filters",
"=",
"input_dim",
",",
"kernel_size",
"=",
"1",
",",
"padding",
"=",
"'valid'",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"conv",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"conv",
")",
"# shortcut connections that turn the network into its counterpart",
"# residual function (identity shortcut)",
"net",
"=",
"conv",
"+",
"net",
"try",
":",
"# upscale to the next group size",
"next_group",
"=",
"groups",
"[",
"group_i",
"+",
"1",
"]",
"with",
"tf",
".",
"variable_scope",
"(",
"'block_%d/conv_upscale'",
"%",
"group_i",
")",
":",
"net",
"=",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"net",
",",
"filters",
"=",
"next_group",
".",
"num_filters",
",",
"kernel_size",
"=",
"1",
",",
"padding",
"=",
"'same'",
",",
"activation",
"=",
"None",
",",
"bias_initializer",
"=",
"None",
")",
"except",
"IndexError",
":",
"pass",
"net_shape",
"=",
"net",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"net",
"=",
"tf",
".",
"nn",
".",
"avg_pool",
"(",
"net",
",",
"ksize",
"=",
"[",
"1",
",",
"net_shape",
"[",
"1",
"]",
",",
"net_shape",
"[",
"2",
"]",
",",
"1",
"]",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"'VALID'",
")",
"net_shape",
"=",
"net",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"net",
"=",
"tf",
".",
"reshape",
"(",
"net",
",",
"[",
"-",
"1",
",",
"net_shape",
"[",
"1",
"]",
"*",
"net_shape",
"[",
"2",
"]",
"*",
"net_shape",
"[",
"3",
"]",
"]",
")",
"# Compute logits (1 per class) and compute loss.",
"logits",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"net",
",",
"N_DIGITS",
",",
"activation",
"=",
"None",
")",
"# Compute predictions.",
"predicted_classes",
"=",
"tf",
".",
"argmax",
"(",
"logits",
",",
"1",
")",
"if",
"mode",
"==",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"PREDICT",
":",
"predictions",
"=",
"{",
"'class'",
":",
"predicted_classes",
",",
"'prob'",
":",
"tf",
".",
"nn",
".",
"softmax",
"(",
"logits",
")",
"}",
"return",
"tf",
".",
"estimator",
".",
"EstimatorSpec",
"(",
"mode",
",",
"predictions",
"=",
"predictions",
")",
"# Compute loss.",
"onehot_labels",
"=",
"tf",
".",
"one_hot",
"(",
"tf",
".",
"cast",
"(",
"labels",
",",
"tf",
".",
"int32",
")",
",",
"N_DIGITS",
",",
"1",
",",
"0",
")",
"loss",
"=",
"tf",
".",
"losses",
".",
"softmax_cross_entropy",
"(",
"onehot_labels",
"=",
"onehot_labels",
",",
"logits",
"=",
"logits",
")",
"# Create training op.",
"if",
"mode",
"==",
"tf",
".",
"estimator",
".",
"ModeKeys",
".",
"TRAIN",
":",
"optimizer",
"=",
"tf",
".",
"train",
".",
"AdagradOptimizer",
"(",
"learning_rate",
"=",
"0.01",
")",
"train_op",
"=",
"optimizer",
".",
"minimize",
"(",
"loss",
",",
"global_step",
"=",
"tf",
".",
"train",
".",
"get_global_step",
"(",
")",
")",
"return",
"tf",
".",
"estimator",
".",
"EstimatorSpec",
"(",
"mode",
",",
"loss",
"=",
"loss",
",",
"train_op",
"=",
"train_op",
")",
"# Compute evaluation metrics.",
"eval_metric_ops",
"=",
"{",
"'accuracy'",
":",
"tf",
".",
"metrics",
".",
"accuracy",
"(",
"labels",
"=",
"labels",
",",
"predictions",
"=",
"predicted_classes",
")",
"}",
"return",
"tf",
".",
"estimator",
".",
"EstimatorSpec",
"(",
"mode",
",",
"loss",
"=",
"loss",
",",
"eval_metric_ops",
"=",
"eval_metric_ops",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/examples/learn/resnet.py#L37-L170 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PropertyGrid.GetSelectionForegroundColour | (*args, **kwargs) | return _propgrid.PropertyGrid_GetSelectionForegroundColour(*args, **kwargs) | GetSelectionForegroundColour(self) -> Colour | GetSelectionForegroundColour(self) -> Colour | [
"GetSelectionForegroundColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetSelectionForegroundColour(*args, **kwargs):
"""GetSelectionForegroundColour(self) -> Colour"""
return _propgrid.PropertyGrid_GetSelectionForegroundColour(*args, **kwargs) | [
"def",
"GetSelectionForegroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_GetSelectionForegroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2134-L2136 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/bayesflow/python/ops/stochastic_gradient_estimators.py | python | get_score_function_with_constant_baseline | (baseline, name="ScoreFunction") | return score_function_with_constant_baseline | Score function estimator with constant baseline.
Args:
baseline: `Tensor` to be subtracted from loss.
name: name to prepend ops with.
Returns:
Callable score function estimator that takes the `DistributionTensor`, the
sampled `value`, and the downstream `loss`, and subtracts the provided
`baseline` from the `loss`. | Score function estimator with constant baseline. | [
"Score",
"function",
"estimator",
"with",
"constant",
"baseline",
"."
] | def get_score_function_with_constant_baseline(baseline, name="ScoreFunction"):
"""Score function estimator with constant baseline.
Args:
baseline: `Tensor` to be subtracted from loss.
name: name to prepend ops with.
Returns:
Callable score function estimator that takes the `DistributionTensor`, the
sampled `value`, and the downstream `loss`, and subtracts the provided
`baseline` from the `loss`.
"""
def score_function_with_constant_baseline(dist_tensor, value, loss):
return score_function(dist_tensor, value, loss, baseline, name)
return score_function_with_constant_baseline | [
"def",
"get_score_function_with_constant_baseline",
"(",
"baseline",
",",
"name",
"=",
"\"ScoreFunction\"",
")",
":",
"def",
"score_function_with_constant_baseline",
"(",
"dist_tensor",
",",
"value",
",",
"loss",
")",
":",
"return",
"score_function",
"(",
"dist_tensor",
",",
"value",
",",
"loss",
",",
"baseline",
",",
"name",
")",
"return",
"score_function_with_constant_baseline"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/bayesflow/python/ops/stochastic_gradient_estimators.py#L124-L140 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/base/OutputWidgetBase.py | python | OutputWidgetBase._callbackPythonButton | (self) | Open dialog and write script. | Open dialog and write script. | [
"Open",
"dialog",
"and",
"write",
"script",
"."
] | def _callbackPythonButton(self):
"""
Open dialog and write script.
"""
dialog = QtWidgets.QFileDialog()
dialog.setWindowTitle('Write Python Script')
dialog.setNameFilter('Python Files (*.py)')
dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)
dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
filename = str(dialog.selectedFiles()[0])
self.write.emit(filename) | [
"def",
"_callbackPythonButton",
"(",
"self",
")",
":",
"dialog",
"=",
"QtWidgets",
".",
"QFileDialog",
"(",
")",
"dialog",
".",
"setWindowTitle",
"(",
"'Write Python Script'",
")",
"dialog",
".",
"setNameFilter",
"(",
"'Python Files (*.py)'",
")",
"dialog",
".",
"setFileMode",
"(",
"QtWidgets",
".",
"QFileDialog",
".",
"AnyFile",
")",
"dialog",
".",
"setAcceptMode",
"(",
"QtWidgets",
".",
"QFileDialog",
".",
"AcceptSave",
")",
"dialog",
".",
"setOption",
"(",
"QtWidgets",
".",
"QFileDialog",
".",
"DontUseNativeDialog",
")",
"if",
"dialog",
".",
"exec_",
"(",
")",
"==",
"QtWidgets",
".",
"QDialog",
".",
"Accepted",
":",
"filename",
"=",
"str",
"(",
"dialog",
".",
"selectedFiles",
"(",
")",
"[",
"0",
"]",
")",
"self",
".",
"write",
".",
"emit",
"(",
"filename",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/base/OutputWidgetBase.py#L65-L78 | ||
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/descriptor_pool.py | python | DescriptorPool.FindEnumTypeByName | (self, full_name) | return self._enum_descriptors[full_name] | Loads the named enum descriptor from the pool.
Args:
full_name (str): The full name of the enum descriptor to load.
Returns:
EnumDescriptor: The enum descriptor for the named type.
Raises:
KeyError: if the enum cannot be found in the pool. | Loads the named enum descriptor from the pool. | [
"Loads",
"the",
"named",
"enum",
"descriptor",
"from",
"the",
"pool",
"."
] | def FindEnumTypeByName(self, full_name):
"""Loads the named enum descriptor from the pool.
Args:
full_name (str): The full name of the enum descriptor to load.
Returns:
EnumDescriptor: The enum descriptor for the named type.
Raises:
KeyError: if the enum cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._enum_descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._enum_descriptors[full_name] | [
"def",
"FindEnumTypeByName",
"(",
"self",
",",
"full_name",
")",
":",
"full_name",
"=",
"_NormalizeFullyQualifiedName",
"(",
"full_name",
")",
"if",
"full_name",
"not",
"in",
"self",
".",
"_enum_descriptors",
":",
"self",
".",
"_FindFileContainingSymbolInDb",
"(",
"full_name",
")",
"return",
"self",
".",
"_enum_descriptors",
"[",
"full_name",
"]"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/descriptor_pool.py#L519-L535 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/msvc.py | python | generate | (env) | Add Builders and construction variables for MSVC++ to an Environment. | Add Builders and construction variables for MSVC++ to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"MSVC",
"++",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for MSVC++ to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
# TODO(batch): shouldn't reach in to cmdgen this way; necessary
# for now to bypass the checks in Builder.DictCmdGenerator.__call__()
# and allow .cc and .cpp to be compiled in the same command line.
static_obj.cmdgen.source_ext_match = False
shared_obj.cmdgen.source_ext_match = False
for suffix in CSuffixes:
static_obj.add_action(suffix, CAction)
shared_obj.add_action(suffix, ShCAction)
static_obj.add_emitter(suffix, static_object_emitter)
shared_obj.add_emitter(suffix, shared_object_emitter)
for suffix in CXXSuffixes:
static_obj.add_action(suffix, CXXAction)
shared_obj.add_action(suffix, ShCXXAction)
static_obj.add_emitter(suffix, static_object_emitter)
shared_obj.add_emitter(suffix, shared_object_emitter)
env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Z7") or ""}'])
env['CCPCHFLAGS'] = SCons.Util.CLVar(['${(PCH and "/Yu%s \\\"/Fp%s\\\""%(PCHSTOP or "",File(PCH))) or ""}'])
env['_MSVC_OUTPUT_FLAG'] = msvc_output_flag
env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS'
env['CC'] = 'cl'
env['CCFLAGS'] = SCons.Util.CLVar('/nologo')
env['CFLAGS'] = SCons.Util.CLVar('')
env['CCCOM'] = '${TEMPFILE("$CC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CFLAGS $CCFLAGS $_CCCOMCOM","$CCCOMSTR")}'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
env['SHCCCOM'] = '${TEMPFILE("$SHCC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCFLAGS $SHCCFLAGS $_CCCOMCOM","$SHCCCOMSTR")}'
env['CXX'] = '$CC'
env['CXXFLAGS'] = SCons.Util.CLVar('$( /TP $)')
env['CXXCOM'] = '${TEMPFILE("$CXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CXXFLAGS $CCFLAGS $_CCCOMCOM","$CXXCOMSTR")}'
env['SHCXX'] = '$CXX'
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
env['SHCXXCOM'] = '${TEMPFILE("$SHCXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM","$SHCXXCOMSTR")}'
env['CPPDEFPREFIX'] = '/D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '/I'
env['INCSUFFIX'] = ''
# env.Append(OBJEMITTER = [static_object_emitter])
# env.Append(SHOBJEMITTER = [shared_object_emitter])
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env['RC'] = 'rc'
env['RCFLAGS'] = SCons.Util.CLVar('')
env['RCSUFFIXES']=['.rc','.rc2']
env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'
env['BUILDERS']['RES'] = res_builder
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj'
env['SHOBJPREFIX'] = '$OBJPREFIX'
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
# Set-up ms tools paths
msvc_setup_env_once(env)
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cc'
env['PCHPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Yd") or ""}'])
env['PCHCOM'] = '$CXX /Fo${TARGETS[1]} $CXXFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS'
env['BUILDERS']['PCH'] = pch_builder
if 'ENV' not in env:
env['ENV'] = {}
if 'SystemRoot' not in env['ENV']: # required for dlls in the winsxs folders
env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root() | [
"def",
"generate",
"(",
"env",
")",
":",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"# TODO(batch): shouldn't reach in to cmdgen this way; necessary",
"# for now to bypass the checks in Builder.DictCmdGenerator.__call__()",
"# and allow .cc and .cpp to be compiled in the same command line.",
"static_obj",
".",
"cmdgen",
".",
"source_ext_match",
"=",
"False",
"shared_obj",
".",
"cmdgen",
".",
"source_ext_match",
"=",
"False",
"for",
"suffix",
"in",
"CSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"CAction",
")",
"shared_obj",
".",
"add_action",
"(",
"suffix",
",",
"ShCAction",
")",
"static_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"static_object_emitter",
")",
"shared_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"shared_object_emitter",
")",
"for",
"suffix",
"in",
"CXXSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"CXXAction",
")",
"shared_obj",
".",
"add_action",
"(",
"suffix",
",",
"ShCXXAction",
")",
"static_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"static_object_emitter",
")",
"shared_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"shared_object_emitter",
")",
"env",
"[",
"'CCPDBFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"[",
"'${(PDB and \"/Z7\") or \"\"}'",
"]",
")",
"env",
"[",
"'CCPCHFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"[",
"'${(PCH and \"/Yu%s \\\\\\\"/Fp%s\\\\\\\"\"%(PCHSTOP or \"\",File(PCH))) or \"\"}'",
"]",
")",
"env",
"[",
"'_MSVC_OUTPUT_FLAG'",
"]",
"=",
"msvc_output_flag",
"env",
"[",
"'_CCCOMCOM'",
"]",
"=",
"'$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS'",
"env",
"[",
"'CC'",
"]",
"=",
"'cl'",
"env",
"[",
"'CCFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'/nologo'",
")",
"env",
"[",
"'CFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
"env",
"[",
"'CCCOM'",
"]",
"=",
"'${TEMPFILE(\"$CC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CFLAGS $CCFLAGS $_CCCOMCOM\",\"$CCCOMSTR\")}'",
"env",
"[",
"'SHCC'",
"]",
"=",
"'$CC'",
"env",
"[",
"'SHCCFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$CCFLAGS'",
")",
"env",
"[",
"'SHCFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$CFLAGS'",
")",
"env",
"[",
"'SHCCCOM'",
"]",
"=",
"'${TEMPFILE(\"$SHCC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCFLAGS $SHCCFLAGS $_CCCOMCOM\",\"$SHCCCOMSTR\")}'",
"env",
"[",
"'CXX'",
"]",
"=",
"'$CC'",
"env",
"[",
"'CXXFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$( /TP $)'",
")",
"env",
"[",
"'CXXCOM'",
"]",
"=",
"'${TEMPFILE(\"$CXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CXXFLAGS $CCFLAGS $_CCCOMCOM\",\"$CXXCOMSTR\")}'",
"env",
"[",
"'SHCXX'",
"]",
"=",
"'$CXX'",
"env",
"[",
"'SHCXXFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$CXXFLAGS'",
")",
"env",
"[",
"'SHCXXCOM'",
"]",
"=",
"'${TEMPFILE(\"$SHCXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM\",\"$SHCXXCOMSTR\")}'",
"env",
"[",
"'CPPDEFPREFIX'",
"]",
"=",
"'/D'",
"env",
"[",
"'CPPDEFSUFFIX'",
"]",
"=",
"''",
"env",
"[",
"'INCPREFIX'",
"]",
"=",
"'/I'",
"env",
"[",
"'INCSUFFIX'",
"]",
"=",
"''",
"# env.Append(OBJEMITTER = [static_object_emitter])",
"# env.Append(SHOBJEMITTER = [shared_object_emitter])",
"env",
"[",
"'STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'",
"]",
"=",
"1",
"env",
"[",
"'RC'",
"]",
"=",
"'rc'",
"env",
"[",
"'RCFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
"env",
"[",
"'RCSUFFIXES'",
"]",
"=",
"[",
"'.rc'",
",",
"'.rc2'",
"]",
"env",
"[",
"'RCCOM'",
"]",
"=",
"'$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'RES'",
"]",
"=",
"res_builder",
"env",
"[",
"'OBJPREFIX'",
"]",
"=",
"''",
"env",
"[",
"'OBJSUFFIX'",
"]",
"=",
"'.obj'",
"env",
"[",
"'SHOBJPREFIX'",
"]",
"=",
"'$OBJPREFIX'",
"env",
"[",
"'SHOBJSUFFIX'",
"]",
"=",
"'$OBJSUFFIX'",
"# Set-up ms tools paths",
"msvc_setup_env_once",
"(",
"env",
")",
"env",
"[",
"'CFILESUFFIX'",
"]",
"=",
"'.c'",
"env",
"[",
"'CXXFILESUFFIX'",
"]",
"=",
"'.cc'",
"env",
"[",
"'PCHPDBFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"[",
"'${(PDB and \"/Yd\") or \"\"}'",
"]",
")",
"env",
"[",
"'PCHCOM'",
"]",
"=",
"'$CXX /Fo${TARGETS[1]} $CXXFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS'",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'PCH'",
"]",
"=",
"pch_builder",
"if",
"'ENV'",
"not",
"in",
"env",
":",
"env",
"[",
"'ENV'",
"]",
"=",
"{",
"}",
"if",
"'SystemRoot'",
"not",
"in",
"env",
"[",
"'ENV'",
"]",
":",
"# required for dlls in the winsxs folders",
"env",
"[",
"'ENV'",
"]",
"[",
"'SystemRoot'",
"]",
"=",
"SCons",
".",
"Platform",
".",
"win32",
".",
"get_system_root",
"(",
")"
] | 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/msvc.py#L198-L269 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/tracking/util.py | python | _LoadStatus.assert_nontrivial_match | (self) | Raises an exception if only the root object matched. | Raises an exception if only the root object matched. | [
"Raises",
"an",
"exception",
"if",
"only",
"the",
"root",
"object",
"matched",
"."
] | def assert_nontrivial_match(self):
"""Raises an exception if only the root object matched."""
pass | [
"def",
"assert_nontrivial_match",
"(",
"self",
")",
":",
"pass"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/tracking/util.py#L694-L696 | ||
lhmRyan/deep-supervised-hashing-DSH | 631901f82e2ab031fbac33f914a5b08ef8e21d57 | python/caffe/io.py | python | blobproto_to_array | (blob, return_diff=False) | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | [
"Convert",
"a",
"blob",
"proto",
"to",
"an",
"array",
".",
"In",
"default",
"we",
"will",
"just",
"return",
"the",
"data",
"unless",
"return_diff",
"is",
"True",
"in",
"which",
"case",
"we",
"will",
"return",
"the",
"diff",
"."
] | def blobproto_to_array(blob, return_diff=False):
"""
Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff.
"""
# Read the data into an array
if return_diff:
data = np.array(blob.diff)
else:
data = np.array(blob.data)
# Reshape the array
if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'):
# Use legacy 4D shape
return data.reshape(blob.num, blob.channels, blob.height, blob.width)
else:
return data.reshape(blob.shape.dim) | [
"def",
"blobproto_to_array",
"(",
"blob",
",",
"return_diff",
"=",
"False",
")",
":",
"# Read the data into an array",
"if",
"return_diff",
":",
"data",
"=",
"np",
".",
"array",
"(",
"blob",
".",
"diff",
")",
"else",
":",
"data",
"=",
"np",
".",
"array",
"(",
"blob",
".",
"data",
")",
"# Reshape the array",
"if",
"blob",
".",
"HasField",
"(",
"'num'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'channels'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'height'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'width'",
")",
":",
"# Use legacy 4D shape",
"return",
"data",
".",
"reshape",
"(",
"blob",
".",
"num",
",",
"blob",
".",
"channels",
",",
"blob",
".",
"height",
",",
"blob",
".",
"width",
")",
"else",
":",
"return",
"data",
".",
"reshape",
"(",
"blob",
".",
"shape",
".",
"dim",
")"
] | https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/python/caffe/io.py#L18-L34 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | SpinCtrlDouble.SetValue | (*args, **kwargs) | return _controls_.SpinCtrlDouble_SetValue(*args, **kwargs) | SetValue(self, double value) | SetValue(self, double value) | [
"SetValue",
"(",
"self",
"double",
"value",
")"
] | def SetValue(*args, **kwargs):
"""SetValue(self, double value)"""
return _controls_.SpinCtrlDouble_SetValue(*args, **kwargs) | [
"def",
"SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SpinCtrlDouble_SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2512-L2514 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/cpplint_1.4.5/cpplint.py | python | _BlockInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
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. | Run checks that applies to text after the closing brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"after",
"the",
"closing",
"brace",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
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.
"""
pass | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/cpplint_1.4.5/cpplint.py#L2462-L2473 | ||
MVIG-SJTU/RMPE | 5188c230ec800c12be7369c3619615bc9b020aa4 | examples/pycaffe/tools.py | python | SimpleTransformer.set_mean | (self, mean) | Set the mean to subtract for centering the data. | Set the mean to subtract for centering the data. | [
"Set",
"the",
"mean",
"to",
"subtract",
"for",
"centering",
"the",
"data",
"."
] | def set_mean(self, mean):
"""
Set the mean to subtract for centering the data.
"""
self.mean = mean | [
"def",
"set_mean",
"(",
"self",
",",
"mean",
")",
":",
"self",
".",
"mean",
"=",
"mean"
] | https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/examples/pycaffe/tools.py#L15-L19 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pygram.py | python | Symbols.__init__ | (self, grammar) | Initializer.
Creates an attribute for each grammar symbol (nonterminal),
whose value is the symbol's type (an int >= 256). | Initializer. | [
"Initializer",
"."
] | def __init__(self, grammar):
"""Initializer.
Creates an attribute for each grammar symbol (nonterminal),
whose value is the symbol's type (an int >= 256).
"""
for name, symbol in grammar.symbol2number.iteritems():
setattr(self, name, symbol) | [
"def",
"__init__",
"(",
"self",
",",
"grammar",
")",
":",
"for",
"name",
",",
"symbol",
"in",
"grammar",
".",
"symbol2number",
".",
"iteritems",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"name",
",",
"symbol",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pygram.py#L22-L29 | ||
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | storage/ndb/mcc/remote_clusterhost.py | python | RemoteClusterHost._exec_cmdv | (self, cmdv, procCtrl, stdinFile) | return self._exec_cmdln(' '.join([quote_if_contains_space(a) for a in cmdv]), procCtrl, stdinFile) | Execute an OS command vector on the remote host.
cmdv - complete command vector (argv) of the OS command
procCtrl - procCtrl object from message which controls how the process
is started (blocking vs non-blocking and output reporting) | Execute an OS command vector on the remote host.
cmdv - complete command vector (argv) of the OS command
procCtrl - procCtrl object from message which controls how the process
is started (blocking vs non-blocking and output reporting) | [
"Execute",
"an",
"OS",
"command",
"vector",
"on",
"the",
"remote",
"host",
".",
"cmdv",
"-",
"complete",
"command",
"vector",
"(",
"argv",
")",
"of",
"the",
"OS",
"command",
"procCtrl",
"-",
"procCtrl",
"object",
"from",
"message",
"which",
"controls",
"how",
"the",
"process",
"is",
"started",
"(",
"blocking",
"vs",
"non",
"-",
"blocking",
"and",
"output",
"reporting",
")"
] | def _exec_cmdv(self, cmdv, procCtrl, stdinFile):
"""Execute an OS command vector on the remote host.
cmdv - complete command vector (argv) of the OS command
procCtrl - procCtrl object from message which controls how the process
is started (blocking vs non-blocking and output reporting)
"""
assert isinstance(cmdv, list)
return self._exec_cmdln(' '.join([quote_if_contains_space(a) for a in cmdv]), procCtrl, stdinFile) | [
"def",
"_exec_cmdv",
"(",
"self",
",",
"cmdv",
",",
"procCtrl",
",",
"stdinFile",
")",
":",
"assert",
"isinstance",
"(",
"cmdv",
",",
"list",
")",
"return",
"self",
".",
"_exec_cmdln",
"(",
"' '",
".",
"join",
"(",
"[",
"quote_if_contains_space",
"(",
"a",
")",
"for",
"a",
"in",
"cmdv",
"]",
")",
",",
"procCtrl",
",",
"stdinFile",
")"
] | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/storage/ndb/mcc/remote_clusterhost.py#L279-L287 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | RegionFromBitmapColour | (*args, **kwargs) | return val | RegionFromBitmapColour(Bitmap bmp, Colour transColour, int tolerance=0) -> Region | RegionFromBitmapColour(Bitmap bmp, Colour transColour, int tolerance=0) -> Region | [
"RegionFromBitmapColour",
"(",
"Bitmap",
"bmp",
"Colour",
"transColour",
"int",
"tolerance",
"=",
"0",
")",
"-",
">",
"Region"
] | def RegionFromBitmapColour(*args, **kwargs):
"""RegionFromBitmapColour(Bitmap bmp, Colour transColour, int tolerance=0) -> Region"""
val = _gdi_.new_RegionFromBitmapColour(*args, **kwargs)
return val | [
"def",
"RegionFromBitmapColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_gdi_",
".",
"new_RegionFromBitmapColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1740-L1743 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/rds/__init__.py | python | RDSConnection.get_log_file | (self, dbinstance_id, log_file_name, marker=None, number_of_lines=None, max_records=None) | return logfile | Download a log file from RDS
:type instance_id: str
:param instance_id: The identifier of a DBInstance.
:type log_file_name: str
:param log_file_name: The name of the log file to retrieve
:type marker: str
:param marker: A marker returned from a previous call to this method, or 0 to indicate the start of file. If
no marker is specified, this will fetch log lines from the end of file instead.
:type number_of_lines: int
:param marker: The maximium number of lines to be returned. | Download a log file from RDS | [
"Download",
"a",
"log",
"file",
"from",
"RDS"
] | def get_log_file(self, dbinstance_id, log_file_name, marker=None, number_of_lines=None, max_records=None):
"""
Download a log file from RDS
:type instance_id: str
:param instance_id: The identifier of a DBInstance.
:type log_file_name: str
:param log_file_name: The name of the log file to retrieve
:type marker: str
:param marker: A marker returned from a previous call to this method, or 0 to indicate the start of file. If
no marker is specified, this will fetch log lines from the end of file instead.
:type number_of_lines: int
:param marker: The maximium number of lines to be returned.
"""
params = {
'DBInstanceIdentifier': dbinstance_id,
'LogFileName': log_file_name,
}
if marker:
params['Marker'] = marker
if number_of_lines:
params['NumberOfLines'] = number_of_lines
if max_records:
params['MaxRecords'] = max_records
logfile = self.get_object('DownloadDBLogFilePortion', params, LogFileObject)
if logfile:
logfile.log_filename = log_file_name
logfile.dbinstance_id = dbinstance_id
return logfile | [
"def",
"get_log_file",
"(",
"self",
",",
"dbinstance_id",
",",
"log_file_name",
",",
"marker",
"=",
"None",
",",
"number_of_lines",
"=",
"None",
",",
"max_records",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'DBInstanceIdentifier'",
":",
"dbinstance_id",
",",
"'LogFileName'",
":",
"log_file_name",
",",
"}",
"if",
"marker",
":",
"params",
"[",
"'Marker'",
"]",
"=",
"marker",
"if",
"number_of_lines",
":",
"params",
"[",
"'NumberOfLines'",
"]",
"=",
"number_of_lines",
"if",
"max_records",
":",
"params",
"[",
"'MaxRecords'",
"]",
"=",
"max_records",
"logfile",
"=",
"self",
".",
"get_object",
"(",
"'DownloadDBLogFilePortion'",
",",
"params",
",",
"LogFileObject",
")",
"if",
"logfile",
":",
"logfile",
".",
"log_filename",
"=",
"log_file_name",
"logfile",
".",
"dbinstance_id",
"=",
"dbinstance_id",
"return",
"logfile"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/rds/__init__.py#L1124-L1162 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/aicpu/mirror_pad.py | python | _mirror_pad_aicpu | () | return | MirrorPad AiCPU register | MirrorPad AiCPU register | [
"MirrorPad",
"AiCPU",
"register"
] | def _mirror_pad_aicpu():
"""MirrorPad AiCPU register"""
return | [
"def",
"_mirror_pad_aicpu",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/aicpu/mirror_pad.py#L50-L52 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/tabbedpages.py | python | TabSet.add_tab | (self, tab_name) | Add a new tab with the name given in tab_name. | Add a new tab with the name given in tab_name. | [
"Add",
"a",
"new",
"tab",
"with",
"the",
"name",
"given",
"in",
"tab_name",
"."
] | def add_tab(self, tab_name):
"""Add a new tab with the name given in tab_name."""
if not tab_name:
raise InvalidNameError("Invalid Tab name: '%s'" % tab_name)
if tab_name in self._tab_names:
raise AlreadyExistsError("Tab named '%s' already exists" %tab_name)
self._tab_names.append(tab_name)
self._arrange_tabs() | [
"def",
"add_tab",
"(",
"self",
",",
"tab_name",
")",
":",
"if",
"not",
"tab_name",
":",
"raise",
"InvalidNameError",
"(",
"\"Invalid Tab name: '%s'\"",
"%",
"tab_name",
")",
"if",
"tab_name",
"in",
"self",
".",
"_tab_names",
":",
"raise",
"AlreadyExistsError",
"(",
"\"Tab named '%s' already exists\"",
"%",
"tab_name",
")",
"self",
".",
"_tab_names",
".",
"append",
"(",
"tab_name",
")",
"self",
".",
"_arrange_tabs",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/tabbedpages.py#L68-L76 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/libmintspointgrp.py | python | IrreducibleRepresentation.__str__ | (self, out=None) | This prints the irrep to the given file, or stdout if none is
given. The second argument is an optional string of spaces to
offset by. | This prints the irrep to the given file, or stdout if none is
given. The second argument is an optional string of spaces to
offset by. | [
"This",
"prints",
"the",
"irrep",
"to",
"the",
"given",
"file",
"or",
"stdout",
"if",
"none",
"is",
"given",
".",
"The",
"second",
"argument",
"is",
"an",
"optional",
"string",
"of",
"spaces",
"to",
"offset",
"by",
"."
] | def __str__(self, out=None):
"""This prints the irrep to the given file, or stdout if none is
given. The second argument is an optional string of spaces to
offset by.
"""
if self.g == 0:
return
text = " %-5s" % (self.symb)
for i in range(self.g):
text += " %6.3f" % (self.character(i))
text += " | %d t, %d R\n" % (self.PYntrans, self.PYnrot)
for d in range(self.nproj()):
text += " "
for i in range(self.g):
text += " %6.3f" % (self.p(d, i))
text += "\n"
if out is None:
return text
else:
with open(out, mode='w') as handle:
handle.write(text) | [
"def",
"__str__",
"(",
"self",
",",
"out",
"=",
"None",
")",
":",
"if",
"self",
".",
"g",
"==",
"0",
":",
"return",
"text",
"=",
"\" %-5s\"",
"%",
"(",
"self",
".",
"symb",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"g",
")",
":",
"text",
"+=",
"\" %6.3f\"",
"%",
"(",
"self",
".",
"character",
"(",
"i",
")",
")",
"text",
"+=",
"\" | %d t, %d R\\n\"",
"%",
"(",
"self",
".",
"PYntrans",
",",
"self",
".",
"PYnrot",
")",
"for",
"d",
"in",
"range",
"(",
"self",
".",
"nproj",
"(",
")",
")",
":",
"text",
"+=",
"\" \"",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"g",
")",
":",
"text",
"+=",
"\" %6.3f\"",
"%",
"(",
"self",
".",
"p",
"(",
"d",
",",
"i",
")",
")",
"text",
"+=",
"\"\\n\"",
"if",
"out",
"is",
"None",
":",
"return",
"text",
"else",
":",
"with",
"open",
"(",
"out",
",",
"mode",
"=",
"'w'",
")",
"as",
"handle",
":",
"handle",
".",
"write",
"(",
"text",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintspointgrp.py#L805-L830 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGridPage.GetStatePtr | (*args) | return _propgrid.PropertyGridPage_GetStatePtr(*args) | GetStatePtr(self)
GetStatePtr(self) | GetStatePtr(self)
GetStatePtr(self) | [
"GetStatePtr",
"(",
"self",
")",
"GetStatePtr",
"(",
"self",
")"
] | def GetStatePtr(*args):
"""
GetStatePtr(self)
GetStatePtr(self)
"""
return _propgrid.PropertyGridPage_GetStatePtr(*args) | [
"def",
"GetStatePtr",
"(",
"*",
"args",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridPage_GetStatePtr",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3371-L3376 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/simpla/_pvehicle.py | python | PVehicle.__init__ | (self, ID, controlInterval) | Constructor(string, float)
Create a PVehicle representing a SUMOVehicle for the PlatoonManager. The controlInterval is only piped through
to the singelton platoon created by the vehicle. | Constructor(string, float) | [
"Constructor",
"(",
"string",
"float",
")"
] | def __init__(self, ID, controlInterval):
'''Constructor(string, float)
Create a PVehicle representing a SUMOVehicle for the PlatoonManager. The controlInterval is only piped through
to the singelton platoon created by the vehicle.
'''
# vehicle ID (should be the one used in SUMO)
self._ID = ID
# vehicle state (is updated by platoon manager in every step)
self.state = pVehicleState(ID)
# store the vehicle's vTypes, speedfactors and lanechangemodes
self._vTypes = dict()
self._speedFactors = dict()
self._laneChangeModes = dict()
# original vtype, speedFactor and lanechangemodes
self._vTypes[PlatoonMode.NONE] = traci.vehicle.getTypeID(ID)
self._speedFactors[PlatoonMode.NONE] = traci.vehicle.getSpeedFactor(ID)
# This is the default mode
self._laneChangeModes[PlatoonMode.NONE] = 0b1001010101
# vTypes, speedFactors and lanechangemodes parametrizing the platoon behaviour
for mode in [PlatoonMode.LEADER, PlatoonMode.FOLLOWER, PlatoonMode.CATCHUP, PlatoonMode.CATCHUP_FOLLOWER]:
self._vTypes[mode] = self._determinePlatoonVType(mode)
self._laneChangeModes[mode] = cfg.LC_MODE[mode]
self._speedFactors[mode] = cfg.SPEEDFACTOR[mode]
self._speedFactors[PlatoonMode.NONE] = traci.vehicletype.getSpeedFactor(self._vTypes[PlatoonMode.NONE])
# Initialize platoon mode to none
self._currentPlatoonMode = PlatoonMode.NONE
# the active speed factor is decreased as the waiting time for a mode switch rises
# (assuming that the main hindrance to switching is too close following)
self._activeSpeedFactor = cfg.SPEEDFACTOR[self._currentPlatoonMode]
# The switch impatience factor determines the magnitude of the effect
# that an increasing waiting time has on the active speed factor:
# activeSpeedFactor = modeSpecificSpeedFactor/(1+impatienceFactor*waitingTime)
self._switchImpatienceFactor = cfg.SWITCH_IMPATIENCE_FACTOR
# create a new platoon containing only this vehicle
self._platoon = Platoon([self], controlInterval)
# the time left until splitting from a platoon if loosing coherence as a follower
self._timeUntilSplit = cfg.PLATOON_SPLIT_TIME
# Whether split conditions are fulfilled (i.e. leader in th platoon
# is not found directly in front of the vehicle)
self._splitConditions = False
# waiting time for switching into different modes
self._switchWaitingTime = {}
self.resetSwitchWaitingTime() | [
"def",
"__init__",
"(",
"self",
",",
"ID",
",",
"controlInterval",
")",
":",
"# vehicle ID (should be the one used in SUMO)",
"self",
".",
"_ID",
"=",
"ID",
"# vehicle state (is updated by platoon manager in every step)",
"self",
".",
"state",
"=",
"pVehicleState",
"(",
"ID",
")",
"# store the vehicle's vTypes, speedfactors and lanechangemodes",
"self",
".",
"_vTypes",
"=",
"dict",
"(",
")",
"self",
".",
"_speedFactors",
"=",
"dict",
"(",
")",
"self",
".",
"_laneChangeModes",
"=",
"dict",
"(",
")",
"# original vtype, speedFactor and lanechangemodes",
"self",
".",
"_vTypes",
"[",
"PlatoonMode",
".",
"NONE",
"]",
"=",
"traci",
".",
"vehicle",
".",
"getTypeID",
"(",
"ID",
")",
"self",
".",
"_speedFactors",
"[",
"PlatoonMode",
".",
"NONE",
"]",
"=",
"traci",
".",
"vehicle",
".",
"getSpeedFactor",
"(",
"ID",
")",
"# This is the default mode",
"self",
".",
"_laneChangeModes",
"[",
"PlatoonMode",
".",
"NONE",
"]",
"=",
"0b1001010101",
"# vTypes, speedFactors and lanechangemodes parametrizing the platoon behaviour",
"for",
"mode",
"in",
"[",
"PlatoonMode",
".",
"LEADER",
",",
"PlatoonMode",
".",
"FOLLOWER",
",",
"PlatoonMode",
".",
"CATCHUP",
",",
"PlatoonMode",
".",
"CATCHUP_FOLLOWER",
"]",
":",
"self",
".",
"_vTypes",
"[",
"mode",
"]",
"=",
"self",
".",
"_determinePlatoonVType",
"(",
"mode",
")",
"self",
".",
"_laneChangeModes",
"[",
"mode",
"]",
"=",
"cfg",
".",
"LC_MODE",
"[",
"mode",
"]",
"self",
".",
"_speedFactors",
"[",
"mode",
"]",
"=",
"cfg",
".",
"SPEEDFACTOR",
"[",
"mode",
"]",
"self",
".",
"_speedFactors",
"[",
"PlatoonMode",
".",
"NONE",
"]",
"=",
"traci",
".",
"vehicletype",
".",
"getSpeedFactor",
"(",
"self",
".",
"_vTypes",
"[",
"PlatoonMode",
".",
"NONE",
"]",
")",
"# Initialize platoon mode to none",
"self",
".",
"_currentPlatoonMode",
"=",
"PlatoonMode",
".",
"NONE",
"# the active speed factor is decreased as the waiting time for a mode switch rises",
"# (assuming that the main hindrance to switching is too close following)",
"self",
".",
"_activeSpeedFactor",
"=",
"cfg",
".",
"SPEEDFACTOR",
"[",
"self",
".",
"_currentPlatoonMode",
"]",
"# The switch impatience factor determines the magnitude of the effect",
"# that an increasing waiting time has on the active speed factor:",
"# activeSpeedFactor = modeSpecificSpeedFactor/(1+impatienceFactor*waitingTime)",
"self",
".",
"_switchImpatienceFactor",
"=",
"cfg",
".",
"SWITCH_IMPATIENCE_FACTOR",
"# create a new platoon containing only this vehicle",
"self",
".",
"_platoon",
"=",
"Platoon",
"(",
"[",
"self",
"]",
",",
"controlInterval",
")",
"# the time left until splitting from a platoon if loosing coherence as a follower",
"self",
".",
"_timeUntilSplit",
"=",
"cfg",
".",
"PLATOON_SPLIT_TIME",
"# Whether split conditions are fulfilled (i.e. leader in th platoon",
"# is not found directly in front of the vehicle)",
"self",
".",
"_splitConditions",
"=",
"False",
"# waiting time for switching into different modes",
"self",
".",
"_switchWaitingTime",
"=",
"{",
"}",
"self",
".",
"resetSwitchWaitingTime",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/simpla/_pvehicle.py#L65-L111 | ||
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/datasets/shapenet_single.py | python | shapenet_single.label_path_at | (self, i) | return self.label_path_from_index(self.image_index[i]) | Return the absolute path to metadata i in the image sequence. | Return the absolute path to metadata i in the image sequence. | [
"Return",
"the",
"absolute",
"path",
"to",
"metadata",
"i",
"in",
"the",
"image",
"sequence",
"."
] | def label_path_at(self, i):
"""
Return the absolute path to metadata i in the image sequence.
"""
return self.label_path_from_index(self.image_index[i]) | [
"def",
"label_path_at",
"(",
"self",
",",
"i",
")",
":",
"return",
"self",
".",
"label_path_from_index",
"(",
"self",
".",
"image_index",
"[",
"i",
"]",
")"
] | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/datasets/shapenet_single.py#L68-L72 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/extractor.py | python | add_input_ops | (graph: Graph, user_defined_inputs: dict, before_infer: bool) | return inputs | This function add user defined input operations.
For cutting without port:
Op_1 -> Op_2 -> output, user_defined_inputs = {'Op_2': {'shape':[1, 2]}} =>
Op_1, New_input (op=Parameter, shape=[1, 2]) -> Op_2 -> output
For cutting with input port:
Op_1 -> Op_2 -> output, user_defined_inputs = {'Op_2': {'shape':[1, 2], 'in': 0}} =>
Op_1, New_input (op=Parameter, shape=[1, 2]) -> Op_2 -> output
For cutting with output port:
Op_1 -> Op_2 -> output, user_defined_inputs = {'Op_2': {'shape':[1, 2], 'out': 0}} =>
Op_1 -> Op_2, New_input (op=Parameter, shape=[1, 2]) -> output
For case with before_infer=False data nodes are added to this schemes. | This function add user defined input operations.
For cutting without port:
Op_1 -> Op_2 -> output, user_defined_inputs = {'Op_2': {'shape':[1, 2]}} =>
Op_1, New_input (op=Parameter, shape=[1, 2]) -> Op_2 -> output | [
"This",
"function",
"add",
"user",
"defined",
"input",
"operations",
".",
"For",
"cutting",
"without",
"port",
":",
"Op_1",
"-",
">",
"Op_2",
"-",
">",
"output",
"user_defined_inputs",
"=",
"{",
"Op_2",
":",
"{",
"shape",
":",
"[",
"1",
"2",
"]",
"}}",
"=",
">",
"Op_1",
"New_input",
"(",
"op",
"=",
"Parameter",
"shape",
"=",
"[",
"1",
"2",
"]",
")",
"-",
">",
"Op_2",
"-",
">",
"output"
] | def add_input_ops(graph: Graph, user_defined_inputs: dict, before_infer: bool):
"""
This function add user defined input operations.
For cutting without port:
Op_1 -> Op_2 -> output, user_defined_inputs = {'Op_2': {'shape':[1, 2]}} =>
Op_1, New_input (op=Parameter, shape=[1, 2]) -> Op_2 -> output
For cutting with input port:
Op_1 -> Op_2 -> output, user_defined_inputs = {'Op_2': {'shape':[1, 2], 'in': 0}} =>
Op_1, New_input (op=Parameter, shape=[1, 2]) -> Op_2 -> output
For cutting with output port:
Op_1 -> Op_2 -> output, user_defined_inputs = {'Op_2': {'shape':[1, 2], 'out': 0}} =>
Op_1 -> Op_2, New_input (op=Parameter, shape=[1, 2]) -> output
For case with before_infer=False data nodes are added to this schemes.
"""
inputs = []
set_is_input(graph, graph.get_nodes_with_attributes(op='Parameter'), False)
if user_defined_inputs is None:
inputs = graph.get_nodes_with_attributes(op='Parameter')
else:
# cutting the net by inputs
assert isinstance(user_defined_inputs, dict)
edges_to_remove = []
for node_id in user_defined_inputs:
for port_and_shape_info in user_defined_inputs[node_id]:
if 'added' in port_and_shape_info and port_and_shape_info['added']:
continue
is_out_port = 'out' in port_and_shape_info # by default we assume input port or input node without port
shape = port_and_shape_info['shape'] if 'shape' in port_and_shape_info else None
user_shape = None
if shape is not None:
user_shape = shape
shape = shape_array(
[dim if type(dim) != tuple and dim >= 0 else dynamic_dimension_value for dim in shape])
data_type = port_and_shape_info['data_type'] if 'data_type' in port_and_shape_info else None
smart_node = Node(graph, node_id)
# Common port index check
if is_out_port:
port = port_and_shape_info['out'] # we check that 'out' in port_and_shape_info earlier
if port is None:
raise Error('Output port for input node {} should be specified, it cannot be None!'.format(
node_id
))
if port is not None and port not in smart_node.out_nodes():
raise Error('Output port index {} is out of number of available output ports for node "{}". ' +
refer_to_faq_msg(29), port, node_id)
else:
port = port_and_shape_info['in'] if 'in' in port_and_shape_info else None
if port is not None and port not in smart_node.in_nodes():
raise Error('Input port index {} is out of number of available input ports for node "{}". ' +
refer_to_faq_msg(29), port, node_id)
# specific Parameter case
if smart_node.op == 'Parameter':
if port is not None:
raise Error(
'Parameter node "{}" doesn\'t have input port, but input port {} was provided. ' +
refer_to_faq_msg(28), node_id, port)
if shape is not None:
smart_node['shape'] = shape
smart_node['user_shape'] = user_shape
if data_type is not None:
smart_node['data_type'] = data_type
inputs.append(node_id)
port_and_shape_info['added'] = True
if smart_node.out_edges():
# User specified input is Parameter, so input cut is not needed, but
# Op name needs to be added to tensor names
op_name = smart_node.soft_get('name')
if graph.has_tensor_name(op_name):
continue
fw_info = []
if 'fw_tensor_debug_info' in smart_node.out_edge(0):
fw_info += smart_node.out_edge(0)['fw_tensor_debug_info']
smart_node.out_edge(0)['fw_tensor_debug_info'] = fw_info + [(op_name, op_name)]
continue
if before_infer:
if shape is None:
continue
# We cut with shapes provided by user and there is no need to wait till infer
if is_out_port:
add_input_ops_helper_before_infer_output_port(graph, port, node_id, shape, user_shape,
data_type, inputs, edges_to_remove)
else:
add_input_ops_helper_before_infer_input_port(graph, smart_node, port, node_id, shape,
user_shape, data_type, inputs,
edges_to_remove)
else:
# We cut after infer and we need inferred shapes in nodes
if is_out_port:
add_input_ops_helper_after_infer_output_port(graph, smart_node, port, node_id, inputs,
edges_to_remove)
else:
add_input_ops_helper_after_infer_input_port(graph, smart_node, port, node_id, inputs,
edges_to_remove)
port_and_shape_info['added'] = True
graph.remove_edges_from(edges_to_remove)
# if len(inputs) == 0, shapes were not provided for all nodes in input-cut request,
# we didn't cut inputs before infer, so this check is useless and invalid
if len(inputs):
set_is_input(graph, inputs, True)
# Check if there are inputs that are not listed in user_defined_inputs and are needed to calculate outputs
outputs = graph.get_nodes_with_attributes(op='Result')
visited = set()
for output_name in outputs:
reverse_dfs(graph, output_name, check_input, visited)
return inputs | [
"def",
"add_input_ops",
"(",
"graph",
":",
"Graph",
",",
"user_defined_inputs",
":",
"dict",
",",
"before_infer",
":",
"bool",
")",
":",
"inputs",
"=",
"[",
"]",
"set_is_input",
"(",
"graph",
",",
"graph",
".",
"get_nodes_with_attributes",
"(",
"op",
"=",
"'Parameter'",
")",
",",
"False",
")",
"if",
"user_defined_inputs",
"is",
"None",
":",
"inputs",
"=",
"graph",
".",
"get_nodes_with_attributes",
"(",
"op",
"=",
"'Parameter'",
")",
"else",
":",
"# cutting the net by inputs",
"assert",
"isinstance",
"(",
"user_defined_inputs",
",",
"dict",
")",
"edges_to_remove",
"=",
"[",
"]",
"for",
"node_id",
"in",
"user_defined_inputs",
":",
"for",
"port_and_shape_info",
"in",
"user_defined_inputs",
"[",
"node_id",
"]",
":",
"if",
"'added'",
"in",
"port_and_shape_info",
"and",
"port_and_shape_info",
"[",
"'added'",
"]",
":",
"continue",
"is_out_port",
"=",
"'out'",
"in",
"port_and_shape_info",
"# by default we assume input port or input node without port",
"shape",
"=",
"port_and_shape_info",
"[",
"'shape'",
"]",
"if",
"'shape'",
"in",
"port_and_shape_info",
"else",
"None",
"user_shape",
"=",
"None",
"if",
"shape",
"is",
"not",
"None",
":",
"user_shape",
"=",
"shape",
"shape",
"=",
"shape_array",
"(",
"[",
"dim",
"if",
"type",
"(",
"dim",
")",
"!=",
"tuple",
"and",
"dim",
">=",
"0",
"else",
"dynamic_dimension_value",
"for",
"dim",
"in",
"shape",
"]",
")",
"data_type",
"=",
"port_and_shape_info",
"[",
"'data_type'",
"]",
"if",
"'data_type'",
"in",
"port_and_shape_info",
"else",
"None",
"smart_node",
"=",
"Node",
"(",
"graph",
",",
"node_id",
")",
"# Common port index check",
"if",
"is_out_port",
":",
"port",
"=",
"port_and_shape_info",
"[",
"'out'",
"]",
"# we check that 'out' in port_and_shape_info earlier",
"if",
"port",
"is",
"None",
":",
"raise",
"Error",
"(",
"'Output port for input node {} should be specified, it cannot be None!'",
".",
"format",
"(",
"node_id",
")",
")",
"if",
"port",
"is",
"not",
"None",
"and",
"port",
"not",
"in",
"smart_node",
".",
"out_nodes",
"(",
")",
":",
"raise",
"Error",
"(",
"'Output port index {} is out of number of available output ports for node \"{}\". '",
"+",
"refer_to_faq_msg",
"(",
"29",
")",
",",
"port",
",",
"node_id",
")",
"else",
":",
"port",
"=",
"port_and_shape_info",
"[",
"'in'",
"]",
"if",
"'in'",
"in",
"port_and_shape_info",
"else",
"None",
"if",
"port",
"is",
"not",
"None",
"and",
"port",
"not",
"in",
"smart_node",
".",
"in_nodes",
"(",
")",
":",
"raise",
"Error",
"(",
"'Input port index {} is out of number of available input ports for node \"{}\". '",
"+",
"refer_to_faq_msg",
"(",
"29",
")",
",",
"port",
",",
"node_id",
")",
"# specific Parameter case",
"if",
"smart_node",
".",
"op",
"==",
"'Parameter'",
":",
"if",
"port",
"is",
"not",
"None",
":",
"raise",
"Error",
"(",
"'Parameter node \"{}\" doesn\\'t have input port, but input port {} was provided. '",
"+",
"refer_to_faq_msg",
"(",
"28",
")",
",",
"node_id",
",",
"port",
")",
"if",
"shape",
"is",
"not",
"None",
":",
"smart_node",
"[",
"'shape'",
"]",
"=",
"shape",
"smart_node",
"[",
"'user_shape'",
"]",
"=",
"user_shape",
"if",
"data_type",
"is",
"not",
"None",
":",
"smart_node",
"[",
"'data_type'",
"]",
"=",
"data_type",
"inputs",
".",
"append",
"(",
"node_id",
")",
"port_and_shape_info",
"[",
"'added'",
"]",
"=",
"True",
"if",
"smart_node",
".",
"out_edges",
"(",
")",
":",
"# User specified input is Parameter, so input cut is not needed, but",
"# Op name needs to be added to tensor names",
"op_name",
"=",
"smart_node",
".",
"soft_get",
"(",
"'name'",
")",
"if",
"graph",
".",
"has_tensor_name",
"(",
"op_name",
")",
":",
"continue",
"fw_info",
"=",
"[",
"]",
"if",
"'fw_tensor_debug_info'",
"in",
"smart_node",
".",
"out_edge",
"(",
"0",
")",
":",
"fw_info",
"+=",
"smart_node",
".",
"out_edge",
"(",
"0",
")",
"[",
"'fw_tensor_debug_info'",
"]",
"smart_node",
".",
"out_edge",
"(",
"0",
")",
"[",
"'fw_tensor_debug_info'",
"]",
"=",
"fw_info",
"+",
"[",
"(",
"op_name",
",",
"op_name",
")",
"]",
"continue",
"if",
"before_infer",
":",
"if",
"shape",
"is",
"None",
":",
"continue",
"# We cut with shapes provided by user and there is no need to wait till infer",
"if",
"is_out_port",
":",
"add_input_ops_helper_before_infer_output_port",
"(",
"graph",
",",
"port",
",",
"node_id",
",",
"shape",
",",
"user_shape",
",",
"data_type",
",",
"inputs",
",",
"edges_to_remove",
")",
"else",
":",
"add_input_ops_helper_before_infer_input_port",
"(",
"graph",
",",
"smart_node",
",",
"port",
",",
"node_id",
",",
"shape",
",",
"user_shape",
",",
"data_type",
",",
"inputs",
",",
"edges_to_remove",
")",
"else",
":",
"# We cut after infer and we need inferred shapes in nodes",
"if",
"is_out_port",
":",
"add_input_ops_helper_after_infer_output_port",
"(",
"graph",
",",
"smart_node",
",",
"port",
",",
"node_id",
",",
"inputs",
",",
"edges_to_remove",
")",
"else",
":",
"add_input_ops_helper_after_infer_input_port",
"(",
"graph",
",",
"smart_node",
",",
"port",
",",
"node_id",
",",
"inputs",
",",
"edges_to_remove",
")",
"port_and_shape_info",
"[",
"'added'",
"]",
"=",
"True",
"graph",
".",
"remove_edges_from",
"(",
"edges_to_remove",
")",
"# if len(inputs) == 0, shapes were not provided for all nodes in input-cut request,",
"# we didn't cut inputs before infer, so this check is useless and invalid",
"if",
"len",
"(",
"inputs",
")",
":",
"set_is_input",
"(",
"graph",
",",
"inputs",
",",
"True",
")",
"# Check if there are inputs that are not listed in user_defined_inputs and are needed to calculate outputs",
"outputs",
"=",
"graph",
".",
"get_nodes_with_attributes",
"(",
"op",
"=",
"'Result'",
")",
"visited",
"=",
"set",
"(",
")",
"for",
"output_name",
"in",
"outputs",
":",
"reverse_dfs",
"(",
"graph",
",",
"output_name",
",",
"check_input",
",",
"visited",
")",
"return",
"inputs"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/extractor.py#L1019-L1134 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/subprocess.py | python | check_call | (*popenargs, **kwargs) | return retcode | Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
check_call(["ls", "-l"]) | Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute. | [
"Run",
"command",
"with",
"arguments",
".",
"Wait",
"for",
"command",
"to",
"complete",
".",
"If",
"the",
"exit",
"code",
"was",
"zero",
"then",
"return",
"otherwise",
"raise",
"CalledProcessError",
".",
"The",
"CalledProcessError",
"object",
"will",
"have",
"the",
"return",
"code",
"in",
"the",
"returncode",
"attribute",
"."
] | def check_call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
check_call(["ls", "-l"])
"""
retcode = call(*popenargs, **kwargs)
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
if retcode:
raise CalledProcessError(retcode, cmd)
return retcode | [
"def",
"check_call",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
":",
"retcode",
"=",
"call",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
"cmd",
"=",
"kwargs",
".",
"get",
"(",
"\"args\"",
")",
"if",
"cmd",
"is",
"None",
":",
"cmd",
"=",
"popenargs",
"[",
"0",
"]",
"if",
"retcode",
":",
"raise",
"CalledProcessError",
"(",
"retcode",
",",
"cmd",
")",
"return",
"retcode"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/subprocess.py#L483-L499 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ListItem.SetBackgroundColour | (*args, **kwargs) | return _controls_.ListItem_SetBackgroundColour(*args, **kwargs) | SetBackgroundColour(self, Colour colBack) | SetBackgroundColour(self, Colour colBack) | [
"SetBackgroundColour",
"(",
"self",
"Colour",
"colBack",
")"
] | def SetBackgroundColour(*args, **kwargs):
"""SetBackgroundColour(self, Colour colBack)"""
return _controls_.ListItem_SetBackgroundColour(*args, **kwargs) | [
"def",
"SetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListItem_SetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4204-L4206 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/posixpath.py | python | join | (a, *p) | return path | Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with a separator. | Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with a separator. | [
"Join",
"two",
"or",
"more",
"pathname",
"components",
"inserting",
"/",
"as",
"needed",
".",
"If",
"any",
"component",
"is",
"an",
"absolute",
"path",
"all",
"previous",
"path",
"components",
"will",
"be",
"discarded",
".",
"An",
"empty",
"last",
"part",
"will",
"result",
"in",
"a",
"path",
"that",
"ends",
"with",
"a",
"separator",
"."
] | def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with a separator."""
a = os.fspath(a)
sep = _get_sep(a)
path = a
try:
if not p:
path[:0] + sep #23780: Ensure compatible data type even if p is null.
for b in map(os.fspath, p):
if b.startswith(sep):
path = b
elif not path or path.endswith(sep):
path += b
else:
path += sep + b
except (TypeError, AttributeError, BytesWarning):
genericpath._check_arg_types('join', a, *p)
raise
return path | [
"def",
"join",
"(",
"a",
",",
"*",
"p",
")",
":",
"a",
"=",
"os",
".",
"fspath",
"(",
"a",
")",
"sep",
"=",
"_get_sep",
"(",
"a",
")",
"path",
"=",
"a",
"try",
":",
"if",
"not",
"p",
":",
"path",
"[",
":",
"0",
"]",
"+",
"sep",
"#23780: Ensure compatible data type even if p is null.",
"for",
"b",
"in",
"map",
"(",
"os",
".",
"fspath",
",",
"p",
")",
":",
"if",
"b",
".",
"startswith",
"(",
"sep",
")",
":",
"path",
"=",
"b",
"elif",
"not",
"path",
"or",
"path",
".",
"endswith",
"(",
"sep",
")",
":",
"path",
"+=",
"b",
"else",
":",
"path",
"+=",
"sep",
"+",
"b",
"except",
"(",
"TypeError",
",",
"AttributeError",
",",
"BytesWarning",
")",
":",
"genericpath",
".",
"_check_arg_types",
"(",
"'join'",
",",
"a",
",",
"*",
"p",
")",
"raise",
"return",
"path"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/posixpath.py#L75-L96 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py | python | BaseHTTPRequestHandler.parse_request | (self) | return True | Parse a request (internal).
The request should be stored in self.raw_requestline; the results
are in self.command, self.path, self.request_version and
self.headers.
Return True for success, False for failure; on failure, any relevant
error response has already been sent back. | Parse a request (internal). | [
"Parse",
"a",
"request",
"(",
"internal",
")",
"."
] | def parse_request(self):
"""Parse a request (internal).
The request should be stored in self.raw_requestline; the results
are in self.command, self.path, self.request_version and
self.headers.
Return True for success, False for failure; on failure, any relevant
error response has already been sent back.
"""
self.command = None # set in case of error on the first line
self.request_version = version = self.default_request_version
self.close_connection = True
requestline = str(self.raw_requestline, 'iso-8859-1')
requestline = requestline.rstrip('\r\n')
self.requestline = requestline
words = requestline.split()
if len(words) == 0:
return False
if len(words) >= 3: # Enough to determine protocol version
version = words[-1]
try:
if not version.startswith('HTTP/'):
raise ValueError
base_version_number = version.split('/', 1)[1]
version_number = base_version_number.split(".")
# RFC 2145 section 3.1 says there can be only one "." and
# - major and minor numbers MUST be treated as
# separate integers;
# - HTTP/2.4 is a lower version than HTTP/2.13, which in
# turn is lower than HTTP/12.3;
# - Leading zeros MUST be ignored by recipients.
if len(version_number) != 2:
raise ValueError
version_number = int(version_number[0]), int(version_number[1])
except (ValueError, IndexError):
self.send_error(
HTTPStatus.BAD_REQUEST,
"Bad request version (%r)" % version)
return False
if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
self.close_connection = False
if version_number >= (2, 0):
self.send_error(
HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
"Invalid HTTP version (%s)" % base_version_number)
return False
self.request_version = version
if not 2 <= len(words) <= 3:
self.send_error(
HTTPStatus.BAD_REQUEST,
"Bad request syntax (%r)" % requestline)
return False
command, path = words[:2]
if len(words) == 2:
self.close_connection = True
if command != 'GET':
self.send_error(
HTTPStatus.BAD_REQUEST,
"Bad HTTP/0.9 request type (%r)" % command)
return False
self.command, self.path = command, path
# Examine the headers and look for a Connection directive.
try:
self.headers = http.client.parse_headers(self.rfile,
_class=self.MessageClass)
except http.client.LineTooLong as err:
self.send_error(
HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
"Line too long",
str(err))
return False
except http.client.HTTPException as err:
self.send_error(
HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
"Too many headers",
str(err)
)
return False
conntype = self.headers.get('Connection', "")
if conntype.lower() == 'close':
self.close_connection = True
elif (conntype.lower() == 'keep-alive' and
self.protocol_version >= "HTTP/1.1"):
self.close_connection = False
# Examine the headers and look for an Expect directive
expect = self.headers.get('Expect', "")
if (expect.lower() == "100-continue" and
self.protocol_version >= "HTTP/1.1" and
self.request_version >= "HTTP/1.1"):
if not self.handle_expect_100():
return False
return True | [
"def",
"parse_request",
"(",
"self",
")",
":",
"self",
".",
"command",
"=",
"None",
"# set in case of error on the first line",
"self",
".",
"request_version",
"=",
"version",
"=",
"self",
".",
"default_request_version",
"self",
".",
"close_connection",
"=",
"True",
"requestline",
"=",
"str",
"(",
"self",
".",
"raw_requestline",
",",
"'iso-8859-1'",
")",
"requestline",
"=",
"requestline",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"self",
".",
"requestline",
"=",
"requestline",
"words",
"=",
"requestline",
".",
"split",
"(",
")",
"if",
"len",
"(",
"words",
")",
"==",
"0",
":",
"return",
"False",
"if",
"len",
"(",
"words",
")",
">=",
"3",
":",
"# Enough to determine protocol version",
"version",
"=",
"words",
"[",
"-",
"1",
"]",
"try",
":",
"if",
"not",
"version",
".",
"startswith",
"(",
"'HTTP/'",
")",
":",
"raise",
"ValueError",
"base_version_number",
"=",
"version",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"[",
"1",
"]",
"version_number",
"=",
"base_version_number",
".",
"split",
"(",
"\".\"",
")",
"# RFC 2145 section 3.1 says there can be only one \".\" and",
"# - major and minor numbers MUST be treated as",
"# separate integers;",
"# - HTTP/2.4 is a lower version than HTTP/2.13, which in",
"# turn is lower than HTTP/12.3;",
"# - Leading zeros MUST be ignored by recipients.",
"if",
"len",
"(",
"version_number",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"version_number",
"=",
"int",
"(",
"version_number",
"[",
"0",
"]",
")",
",",
"int",
"(",
"version_number",
"[",
"1",
"]",
")",
"except",
"(",
"ValueError",
",",
"IndexError",
")",
":",
"self",
".",
"send_error",
"(",
"HTTPStatus",
".",
"BAD_REQUEST",
",",
"\"Bad request version (%r)\"",
"%",
"version",
")",
"return",
"False",
"if",
"version_number",
">=",
"(",
"1",
",",
"1",
")",
"and",
"self",
".",
"protocol_version",
">=",
"\"HTTP/1.1\"",
":",
"self",
".",
"close_connection",
"=",
"False",
"if",
"version_number",
">=",
"(",
"2",
",",
"0",
")",
":",
"self",
".",
"send_error",
"(",
"HTTPStatus",
".",
"HTTP_VERSION_NOT_SUPPORTED",
",",
"\"Invalid HTTP version (%s)\"",
"%",
"base_version_number",
")",
"return",
"False",
"self",
".",
"request_version",
"=",
"version",
"if",
"not",
"2",
"<=",
"len",
"(",
"words",
")",
"<=",
"3",
":",
"self",
".",
"send_error",
"(",
"HTTPStatus",
".",
"BAD_REQUEST",
",",
"\"Bad request syntax (%r)\"",
"%",
"requestline",
")",
"return",
"False",
"command",
",",
"path",
"=",
"words",
"[",
":",
"2",
"]",
"if",
"len",
"(",
"words",
")",
"==",
"2",
":",
"self",
".",
"close_connection",
"=",
"True",
"if",
"command",
"!=",
"'GET'",
":",
"self",
".",
"send_error",
"(",
"HTTPStatus",
".",
"BAD_REQUEST",
",",
"\"Bad HTTP/0.9 request type (%r)\"",
"%",
"command",
")",
"return",
"False",
"self",
".",
"command",
",",
"self",
".",
"path",
"=",
"command",
",",
"path",
"# Examine the headers and look for a Connection directive.",
"try",
":",
"self",
".",
"headers",
"=",
"http",
".",
"client",
".",
"parse_headers",
"(",
"self",
".",
"rfile",
",",
"_class",
"=",
"self",
".",
"MessageClass",
")",
"except",
"http",
".",
"client",
".",
"LineTooLong",
"as",
"err",
":",
"self",
".",
"send_error",
"(",
"HTTPStatus",
".",
"REQUEST_HEADER_FIELDS_TOO_LARGE",
",",
"\"Line too long\"",
",",
"str",
"(",
"err",
")",
")",
"return",
"False",
"except",
"http",
".",
"client",
".",
"HTTPException",
"as",
"err",
":",
"self",
".",
"send_error",
"(",
"HTTPStatus",
".",
"REQUEST_HEADER_FIELDS_TOO_LARGE",
",",
"\"Too many headers\"",
",",
"str",
"(",
"err",
")",
")",
"return",
"False",
"conntype",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'Connection'",
",",
"\"\"",
")",
"if",
"conntype",
".",
"lower",
"(",
")",
"==",
"'close'",
":",
"self",
".",
"close_connection",
"=",
"True",
"elif",
"(",
"conntype",
".",
"lower",
"(",
")",
"==",
"'keep-alive'",
"and",
"self",
".",
"protocol_version",
">=",
"\"HTTP/1.1\"",
")",
":",
"self",
".",
"close_connection",
"=",
"False",
"# Examine the headers and look for an Expect directive",
"expect",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'Expect'",
",",
"\"\"",
")",
"if",
"(",
"expect",
".",
"lower",
"(",
")",
"==",
"\"100-continue\"",
"and",
"self",
".",
"protocol_version",
">=",
"\"HTTP/1.1\"",
"and",
"self",
".",
"request_version",
">=",
"\"HTTP/1.1\"",
")",
":",
"if",
"not",
"self",
".",
"handle_expect_100",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py#L268-L365 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Main/glue/vboxapi.py | python | VirtualBoxManager.getPerfCollector | (self, oIVBox) | return PerfCollector(self, oIVBox) | Returns a helper class (PerfCollector) for accessing performance
collector goodies. See PerfCollector for details. | Returns a helper class (PerfCollector) for accessing performance
collector goodies. See PerfCollector for details. | [
"Returns",
"a",
"helper",
"class",
"(",
"PerfCollector",
")",
"for",
"accessing",
"performance",
"collector",
"goodies",
".",
"See",
"PerfCollector",
"for",
"details",
"."
] | def getPerfCollector(self, oIVBox):
"""
Returns a helper class (PerfCollector) for accessing performance
collector goodies. See PerfCollector for details.
"""
return PerfCollector(self, oIVBox) | [
"def",
"getPerfCollector",
"(",
"self",
",",
"oIVBox",
")",
":",
"return",
"PerfCollector",
"(",
"self",
",",
"oIVBox",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Main/glue/vboxapi.py#L1131-L1136 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/tldnVaporScope.py | python | tldnVaporScope.IEngageTelescope | (self) | After the behavior gets our eyes in the telescope, engage ourselves with the camera | After the behavior gets our eyes in the telescope, engage ourselves with the camera | [
"After",
"the",
"behavior",
"gets",
"our",
"eyes",
"in",
"the",
"telescope",
"engage",
"ourselves",
"with",
"the",
"camera"
] | def IEngageTelescope(self):
"After the behavior gets our eyes in the telescope, engage ourselves with the camera"
# Disable First Person Camera
cam = ptCamera()
cam.undoFirstPerson()
cam.disableFirstPersonOverride()
# set camera to telescope
virtCam = ptCamera()
virtCam.save(Camera.sceneobject.getKey())
# show the cockpit
if Vignette.value:
PtLoadDialog(Vignette.value,self.key, "Teledahn")
if ( PtIsDialogLoaded(Vignette.value) ):
PtShowDialog(Vignette.value)
# get control key events
PtEnableControlKeyEvents(self.key) | [
"def",
"IEngageTelescope",
"(",
"self",
")",
":",
"# Disable First Person Camera",
"cam",
"=",
"ptCamera",
"(",
")",
"cam",
".",
"undoFirstPerson",
"(",
")",
"cam",
".",
"disableFirstPersonOverride",
"(",
")",
"# set camera to telescope",
"virtCam",
"=",
"ptCamera",
"(",
")",
"virtCam",
".",
"save",
"(",
"Camera",
".",
"sceneobject",
".",
"getKey",
"(",
")",
")",
"# show the cockpit",
"if",
"Vignette",
".",
"value",
":",
"PtLoadDialog",
"(",
"Vignette",
".",
"value",
",",
"self",
".",
"key",
",",
"\"Teledahn\"",
")",
"if",
"(",
"PtIsDialogLoaded",
"(",
"Vignette",
".",
"value",
")",
")",
":",
"PtShowDialog",
"(",
"Vignette",
".",
"value",
")",
"# get control key events",
"PtEnableControlKeyEvents",
"(",
"self",
".",
"key",
")"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/tldnVaporScope.py#L364-L379 | ||
chihyaoma/regretful-agent | 5caf7b500667981bc7064e4d31b49e83db64c95a | tasks/R2R-pano/utils.py | python | load_nav_graphs | (scans) | return graphs | Load connectivity graph for each scan | Load connectivity graph for each scan | [
"Load",
"connectivity",
"graph",
"for",
"each",
"scan"
] | def load_nav_graphs(scans):
""" Load connectivity graph for each scan """
def distance(pose1, pose2):
""" Euclidean distance between two graph poses """
return ((pose1['pose'][3] - pose2['pose'][3]) ** 2
+ (pose1['pose'][7] - pose2['pose'][7]) ** 2
+ (pose1['pose'][11] - pose2['pose'][11]) ** 2) ** 0.5
graphs = {}
for scan in scans:
with open('connectivity/%s_connectivity.json' % scan) as f:
G = nx.Graph()
positions = {}
data = json.load(f)
for i, item in enumerate(data):
if item['included']:
for j, conn in enumerate(item['unobstructed']):
if conn and data[j]['included']:
positions[item['image_id']] = np.array([item['pose'][3],
item['pose'][7], item['pose'][11]])
assert data[j]['unobstructed'][i], 'Graph should be undirected'
G.add_edge(item['image_id'], data[j]['image_id'], weight=distance(item, data[j]))
nx.set_node_attributes(G, values=positions, name='position')
graphs[scan] = G
return graphs | [
"def",
"load_nav_graphs",
"(",
"scans",
")",
":",
"def",
"distance",
"(",
"pose1",
",",
"pose2",
")",
":",
"\"\"\" Euclidean distance between two graph poses \"\"\"",
"return",
"(",
"(",
"pose1",
"[",
"'pose'",
"]",
"[",
"3",
"]",
"-",
"pose2",
"[",
"'pose'",
"]",
"[",
"3",
"]",
")",
"**",
"2",
"+",
"(",
"pose1",
"[",
"'pose'",
"]",
"[",
"7",
"]",
"-",
"pose2",
"[",
"'pose'",
"]",
"[",
"7",
"]",
")",
"**",
"2",
"+",
"(",
"pose1",
"[",
"'pose'",
"]",
"[",
"11",
"]",
"-",
"pose2",
"[",
"'pose'",
"]",
"[",
"11",
"]",
")",
"**",
"2",
")",
"**",
"0.5",
"graphs",
"=",
"{",
"}",
"for",
"scan",
"in",
"scans",
":",
"with",
"open",
"(",
"'connectivity/%s_connectivity.json'",
"%",
"scan",
")",
"as",
"f",
":",
"G",
"=",
"nx",
".",
"Graph",
"(",
")",
"positions",
"=",
"{",
"}",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"data",
")",
":",
"if",
"item",
"[",
"'included'",
"]",
":",
"for",
"j",
",",
"conn",
"in",
"enumerate",
"(",
"item",
"[",
"'unobstructed'",
"]",
")",
":",
"if",
"conn",
"and",
"data",
"[",
"j",
"]",
"[",
"'included'",
"]",
":",
"positions",
"[",
"item",
"[",
"'image_id'",
"]",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"item",
"[",
"'pose'",
"]",
"[",
"3",
"]",
",",
"item",
"[",
"'pose'",
"]",
"[",
"7",
"]",
",",
"item",
"[",
"'pose'",
"]",
"[",
"11",
"]",
"]",
")",
"assert",
"data",
"[",
"j",
"]",
"[",
"'unobstructed'",
"]",
"[",
"i",
"]",
",",
"'Graph should be undirected'",
"G",
".",
"add_edge",
"(",
"item",
"[",
"'image_id'",
"]",
",",
"data",
"[",
"j",
"]",
"[",
"'image_id'",
"]",
",",
"weight",
"=",
"distance",
"(",
"item",
",",
"data",
"[",
"j",
"]",
")",
")",
"nx",
".",
"set_node_attributes",
"(",
"G",
",",
"values",
"=",
"positions",
",",
"name",
"=",
"'position'",
")",
"graphs",
"[",
"scan",
"]",
"=",
"G",
"return",
"graphs"
] | https://github.com/chihyaoma/regretful-agent/blob/5caf7b500667981bc7064e4d31b49e83db64c95a/tasks/R2R-pano/utils.py#L31-L56 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/sparse/base.py | python | spmatrix.getformat | (self) | return getattr(self, 'format', 'und') | Format of a matrix representation as a string. | Format of a matrix representation as a string. | [
"Format",
"of",
"a",
"matrix",
"representation",
"as",
"a",
"string",
"."
] | def getformat(self):
"""Format of a matrix representation as a string."""
return getattr(self, 'format', 'und') | [
"def",
"getformat",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"'format'",
",",
"'und'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/base.py#L251-L253 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | apps/ngs_roi/tool_shed/ctd2galaxy.py | python | ParametersNode.find | (self, path) | return self.children[path[0]].find(path[1:]) | Return ParametersNode object at the path below the node. | Return ParametersNode object at the path below the node. | [
"Return",
"ParametersNode",
"object",
"at",
"the",
"path",
"below",
"the",
"node",
"."
] | def find(self, path):
"""Return ParametersNode object at the path below the node."""
if not path:
return self
if not self.children.get(path[0]):
return None
return self.children[path[0]].find(path[1:]) | [
"def",
"find",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"self",
"if",
"not",
"self",
".",
"children",
".",
"get",
"(",
"path",
"[",
"0",
"]",
")",
":",
"return",
"None",
"return",
"self",
".",
"children",
"[",
"path",
"[",
"0",
"]",
"]",
".",
"find",
"(",
"path",
"[",
"1",
":",
"]",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/apps/ngs_roi/tool_shed/ctd2galaxy.py#L115-L121 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py | python | AbstractRpcServer._GetAuthCookie | (self, auth_token) | Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies. | Fetches authentication cookies for an authentication token. | [
"Fetches",
"authentication",
"cookies",
"for",
"an",
"authentication",
"token",
"."
] | def _GetAuthCookie(self, auth_token):
"""Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies.
"""
# This is a dummy value to allow us to identify when we're successful.
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
req = self._CreateRequest("%s/_ah/login?%s" %
(self.host, urllib.urlencode(args)))
try:
response = self.opener.open(req)
except urllib2.HTTPError, e:
response = e
if (response.code != 302 or
response.info()["location"] != continue_location):
raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
response.headers, response.fp)
self.authenticated = True | [
"def",
"_GetAuthCookie",
"(",
"self",
",",
"auth_token",
")",
":",
"# This is a dummy value to allow us to identify when we're successful.",
"continue_location",
"=",
"\"http://localhost/\"",
"args",
"=",
"{",
"\"continue\"",
":",
"continue_location",
",",
"\"auth\"",
":",
"auth_token",
"}",
"req",
"=",
"self",
".",
"_CreateRequest",
"(",
"\"%s/_ah/login?%s\"",
"%",
"(",
"self",
".",
"host",
",",
"urllib",
".",
"urlencode",
"(",
"args",
")",
")",
")",
"try",
":",
"response",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"req",
")",
"except",
"urllib2",
".",
"HTTPError",
",",
"e",
":",
"response",
"=",
"e",
"if",
"(",
"response",
".",
"code",
"!=",
"302",
"or",
"response",
".",
"info",
"(",
")",
"[",
"\"location\"",
"]",
"!=",
"continue_location",
")",
":",
"raise",
"urllib2",
".",
"HTTPError",
"(",
"req",
".",
"get_full_url",
"(",
")",
",",
"response",
".",
"code",
",",
"response",
".",
"msg",
",",
"response",
".",
"headers",
",",
"response",
".",
"fp",
")",
"self",
".",
"authenticated",
"=",
"True"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L276-L298 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/function.py | python | ConcreteFunction._structured_signature_check_arg_type | (self, arg, spec, name) | Raise TypeError if `arg`'s type doesn't match `spec`. | Raise TypeError if `arg`'s type doesn't match `spec`. | [
"Raise",
"TypeError",
"if",
"arg",
"s",
"type",
"doesn",
"t",
"match",
"spec",
"."
] | def _structured_signature_check_arg_type(self, arg, spec, name):
"""Raise TypeError if `arg`'s type doesn't match `spec`."""
if arg is _BOUND_VALUE:
return
# Check the overall nested structure of the argument.
try:
nest.assert_same_structure(arg, spec, expand_composites=True)
except (ValueError, TypeError):
try:
nest.assert_same_structure(arg, spec, expand_composites=False)
expected, got = spec, arg
except (ValueError, TypeError):
expected, got = _structure_summary(spec), _structure_summary(arg)
raise TypeError(f"{self._structured_signature_summary()}: argument "
f"{name} had incorrect type\n"
f" expected: {expected}\n"
f" got: {got}")
# Check the type for each leaf in the nested structure.
arg_pieces = nest.flatten(arg, expand_composites=True)
spec_pieces = nest.flatten(spec, expand_composites=True)
for (arg_piece, spec_piece) in zip(arg_pieces, spec_pieces):
# TODO(mdan): Use consistent error messages.
if isinstance(spec_piece, tensor_spec.DenseSpec):
# TODO(edloper): Consider calling convert_to_tensor on non-tensor
# values here. That would match the behavior of
# _call_concrete_function() in function_deserialization.py. If
# we do, then we need to change the nest assert_same_structure and
# flatten calls above to use shallow variants.
tensor_types = (ops.Tensor, resource_variable_ops.BaseResourceVariable)
if not isinstance(arg_piece, tensor_types):
raise TypeError(f"{self._structured_signature_summary()} expected a "
f"Tensor in {name}, but got "
f"{type(arg_piece).__name__} value {arg_piece}.")
elif arg_piece is not _BOUND_VALUE:
try:
arg_matches_spec = bool(arg_piece == spec_piece)
except (ValueError, TypeError):
logging.vlog(1, "Error matching value with spec", exc_info=True)
arg_matches_spec = False
if not arg_matches_spec:
raise TypeError(
f"ConcreteFunction {self._structured_signature_summary()} was "
f"constructed with {type(spec_piece).__name__} value "
f"{spec_piece} in {name}, but was called with "
f"{type(arg_piece).__name__} value {arg_piece}.") | [
"def",
"_structured_signature_check_arg_type",
"(",
"self",
",",
"arg",
",",
"spec",
",",
"name",
")",
":",
"if",
"arg",
"is",
"_BOUND_VALUE",
":",
"return",
"# Check the overall nested structure of the argument.",
"try",
":",
"nest",
".",
"assert_same_structure",
"(",
"arg",
",",
"spec",
",",
"expand_composites",
"=",
"True",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"try",
":",
"nest",
".",
"assert_same_structure",
"(",
"arg",
",",
"spec",
",",
"expand_composites",
"=",
"False",
")",
"expected",
",",
"got",
"=",
"spec",
",",
"arg",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"expected",
",",
"got",
"=",
"_structure_summary",
"(",
"spec",
")",
",",
"_structure_summary",
"(",
"arg",
")",
"raise",
"TypeError",
"(",
"f\"{self._structured_signature_summary()}: argument \"",
"f\"{name} had incorrect type\\n\"",
"f\" expected: {expected}\\n\"",
"f\" got: {got}\"",
")",
"# Check the type for each leaf in the nested structure.",
"arg_pieces",
"=",
"nest",
".",
"flatten",
"(",
"arg",
",",
"expand_composites",
"=",
"True",
")",
"spec_pieces",
"=",
"nest",
".",
"flatten",
"(",
"spec",
",",
"expand_composites",
"=",
"True",
")",
"for",
"(",
"arg_piece",
",",
"spec_piece",
")",
"in",
"zip",
"(",
"arg_pieces",
",",
"spec_pieces",
")",
":",
"# TODO(mdan): Use consistent error messages.",
"if",
"isinstance",
"(",
"spec_piece",
",",
"tensor_spec",
".",
"DenseSpec",
")",
":",
"# TODO(edloper): Consider calling convert_to_tensor on non-tensor",
"# values here. That would match the behavior of",
"# _call_concrete_function() in function_deserialization.py. If",
"# we do, then we need to change the nest assert_same_structure and",
"# flatten calls above to use shallow variants.",
"tensor_types",
"=",
"(",
"ops",
".",
"Tensor",
",",
"resource_variable_ops",
".",
"BaseResourceVariable",
")",
"if",
"not",
"isinstance",
"(",
"arg_piece",
",",
"tensor_types",
")",
":",
"raise",
"TypeError",
"(",
"f\"{self._structured_signature_summary()} expected a \"",
"f\"Tensor in {name}, but got \"",
"f\"{type(arg_piece).__name__} value {arg_piece}.\"",
")",
"elif",
"arg_piece",
"is",
"not",
"_BOUND_VALUE",
":",
"try",
":",
"arg_matches_spec",
"=",
"bool",
"(",
"arg_piece",
"==",
"spec_piece",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"logging",
".",
"vlog",
"(",
"1",
",",
"\"Error matching value with spec\"",
",",
"exc_info",
"=",
"True",
")",
"arg_matches_spec",
"=",
"False",
"if",
"not",
"arg_matches_spec",
":",
"raise",
"TypeError",
"(",
"f\"ConcreteFunction {self._structured_signature_summary()} was \"",
"f\"constructed with {type(spec_piece).__name__} value \"",
"f\"{spec_piece} in {name}, but was called with \"",
"f\"{type(arg_piece).__name__} value {arg_piece}.\"",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/function.py#L1736-L1782 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Point2D.__add__ | (*args) | return _core_.Point2D___add__(*args) | __add__(self, Point2D pt) -> Point2D | __add__(self, Point2D pt) -> Point2D | [
"__add__",
"(",
"self",
"Point2D",
"pt",
")",
"-",
">",
"Point2D"
] | def __add__(*args):
"""__add__(self, Point2D pt) -> Point2D"""
return _core_.Point2D___add__(*args) | [
"def",
"__add__",
"(",
"*",
"args",
")",
":",
"return",
"_core_",
".",
"Point2D___add__",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1734-L1736 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/ttk.py | python | Style.element_names | (self) | return self.tk.splitlist(self.tk.call(self._name, "element", "names")) | Returns the list of elements defined in the current theme. | Returns the list of elements defined in the current theme. | [
"Returns",
"the",
"list",
"of",
"elements",
"defined",
"in",
"the",
"current",
"theme",
"."
] | def element_names(self):
"""Returns the list of elements defined in the current theme."""
return self.tk.splitlist(self.tk.call(self._name, "element", "names")) | [
"def",
"element_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"splitlist",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_name",
",",
"\"element\"",
",",
"\"names\"",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L469-L471 | |
chatopera/clause | dee31153d5ffdef33deedb6bff03e7806c296968 | var/assets/clients/gen-py/clause/Serving.py | python | Iface.status | (self, request) | Parameters:
- request | Parameters:
- request | [
"Parameters",
":",
"-",
"request"
] | def status(self, request):
"""
Parameters:
- request
"""
pass | [
"def",
"status",
"(",
"self",
",",
"request",
")",
":",
"pass"
] | https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/var/assets/clients/gen-py/clause/Serving.py#L296-L302 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/intelhex/__init__.py | python | IntelHex.find | (self, sub, start=None, end=None) | return -1 | Return the lowest index in self[start:end] where subsection sub is found.
Optional arguments start and end are interpreted as in slice notation.
@param sub bytes-like subsection to find
@param start start of section to search within (optional)
@param end end of section to search within (optional) | Return the lowest index in self[start:end] where subsection sub is found.
Optional arguments start and end are interpreted as in slice notation. | [
"Return",
"the",
"lowest",
"index",
"in",
"self",
"[",
"start",
":",
"end",
"]",
"where",
"subsection",
"sub",
"is",
"found",
".",
"Optional",
"arguments",
"start",
"and",
"end",
"are",
"interpreted",
"as",
"in",
"slice",
"notation",
"."
] | def find(self, sub, start=None, end=None):
"""Return the lowest index in self[start:end] where subsection sub is found.
Optional arguments start and end are interpreted as in slice notation.
@param sub bytes-like subsection to find
@param start start of section to search within (optional)
@param end end of section to search within (optional)
"""
sub = bytes(sub)
for start, end in self[slice(start,end)].segments():
b = self.gets(start, end-start)
i = b.find(sub)
if i != -1:
return start+i
return -1 | [
"def",
"find",
"(",
"self",
",",
"sub",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"sub",
"=",
"bytes",
"(",
"sub",
")",
"for",
"start",
",",
"end",
"in",
"self",
"[",
"slice",
"(",
"start",
",",
"end",
")",
"]",
".",
"segments",
"(",
")",
":",
"b",
"=",
"self",
".",
"gets",
"(",
"start",
",",
"end",
"-",
"start",
")",
"i",
"=",
"b",
".",
"find",
"(",
"sub",
")",
"if",
"i",
"!=",
"-",
"1",
":",
"return",
"start",
"+",
"i",
"return",
"-",
"1"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/intelhex/__init__.py#L768-L782 | |
linyouhappy/kongkongxiyou | 7a69b2913eb29f4be77f9a62fb90cdd72c4160f1 | cocosjs/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | SourceLocation.offset | (self) | return self._get_instantiation()[3] | Get the file offset represented by this source location. | Get the file offset represented by this source location. | [
"Get",
"the",
"file",
"offset",
"represented",
"by",
"this",
"source",
"location",
"."
] | def offset(self):
"""Get the file offset represented by this source location."""
return self._get_instantiation()[3] | [
"def",
"offset",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_instantiation",
"(",
")",
"[",
"3",
"]"
] | https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L213-L215 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/zoombar.py | python | ZoomBar.__init__ | (self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
name="ZoomBar") | Default class constructor.
:param `parent`: the :class:`ZoomBar` parent. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `name`: the window name. | Default class constructor. | [
"Default",
"class",
"constructor",
"."
] | def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
name="ZoomBar"):
"""
Default class constructor.
:param `parent`: the :class:`ZoomBar` parent. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `name`: the window name.
"""
wx.PyControl.__init__(self, parent, id, pos, size, style=wx.BORDER_THEME)
# Zoom from the center. If True button zooms upwards.
self._centerZoom = False
# Whether you want reflections or not
self._showReflections = True
# Allows us to nudge a reflection closer to original
self._nudgeReflection = 0
# Extension of the reflection. BMP or PNG etc.
# Initial size of the buttons
self._buttonSize = 48
# Show labels on hovering
self._showLabels = True
# used internally
self._noResize = False
self._buttons = []
self._reflectionButtons = []
self._imgBar = ImageBar()
self._previousHit = -1
self._currentHit = -1
wx.CallLater(200, self.OnLeaveWindow, None)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
if wx.Platform == "__WXMSW__":
self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"id",
"=",
"wx",
".",
"ID_ANY",
",",
"pos",
"=",
"wx",
".",
"DefaultPosition",
",",
"size",
"=",
"wx",
".",
"DefaultSize",
",",
"name",
"=",
"\"ZoomBar\"",
")",
":",
"wx",
".",
"PyControl",
".",
"__init__",
"(",
"self",
",",
"parent",
",",
"id",
",",
"pos",
",",
"size",
",",
"style",
"=",
"wx",
".",
"BORDER_THEME",
")",
"# Zoom from the center. If True button zooms upwards.",
"self",
".",
"_centerZoom",
"=",
"False",
"# Whether you want reflections or not",
"self",
".",
"_showReflections",
"=",
"True",
"# Allows us to nudge a reflection closer to original",
"self",
".",
"_nudgeReflection",
"=",
"0",
"# Extension of the reflection. BMP or PNG etc.",
"# Initial size of the buttons",
"self",
".",
"_buttonSize",
"=",
"48",
"# Show labels on hovering",
"self",
".",
"_showLabels",
"=",
"True",
"# used internally",
"self",
".",
"_noResize",
"=",
"False",
"self",
".",
"_buttons",
"=",
"[",
"]",
"self",
".",
"_reflectionButtons",
"=",
"[",
"]",
"self",
".",
"_imgBar",
"=",
"ImageBar",
"(",
")",
"self",
".",
"_previousHit",
"=",
"-",
"1",
"self",
".",
"_currentHit",
"=",
"-",
"1",
"wx",
".",
"CallLater",
"(",
"200",
",",
"self",
".",
"OnLeaveWindow",
",",
"None",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_PAINT",
",",
"self",
".",
"OnPaint",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_ERASE_BACKGROUND",
",",
"self",
".",
"OnEraseBackground",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_SIZE",
",",
"self",
".",
"OnSize",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_MOTION",
",",
"self",
".",
"OnMotion",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_LEAVE_WINDOW",
",",
"self",
".",
"OnLeaveWindow",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_LEFT_DOWN",
",",
"self",
".",
"OnLeftDown",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_LEFT_UP",
",",
"self",
".",
"OnLeftUp",
")",
"if",
"wx",
".",
"Platform",
"==",
"\"__WXMSW__\"",
":",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_LEFT_DCLICK",
",",
"self",
".",
"OnLeftDown",
")",
"self",
".",
"SetBackgroundStyle",
"(",
"wx",
".",
"BG_STYLE_CUSTOM",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/zoombar.py#L716-L765 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/pfor.py | python | PForConfig.reduce_sum | (self, x) | return math_ops.reduce_sum(y, axis=0) | Performs a sum reduction on `x` across pfor iterations.
Note that this currently may not work inside a control flow construct.
Args:
x: an unvectorized Tensor.
Returns:
A Tensor that has same rank as `x`. The value is the sum of the values
of `x` across the pfor iterations. | Performs a sum reduction on `x` across pfor iterations. | [
"Performs",
"a",
"sum",
"reduction",
"on",
"x",
"across",
"pfor",
"iterations",
"."
] | def reduce_sum(self, x):
"""Performs a sum reduction on `x` across pfor iterations.
Note that this currently may not work inside a control flow construct.
Args:
x: an unvectorized Tensor.
Returns:
A Tensor that has same rank as `x`. The value is the sum of the values
of `x` across the pfor iterations.
"""
y = self.reduce_concat(x)
return math_ops.reduce_sum(y, axis=0) | [
"def",
"reduce_sum",
"(",
"self",
",",
"x",
")",
":",
"y",
"=",
"self",
".",
"reduce_concat",
"(",
"x",
")",
"return",
"math_ops",
".",
"reduce_sum",
"(",
"y",
",",
"axis",
"=",
"0",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/pfor.py#L1034-L1046 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/encoding.py | python | _assemble_objects | (assign, defi, rep, val, dic, d, null, null_val, max_defi, prev_i) | return i | Dremel-assembly of arrays of values into lists
Parameters
----------
assign: array dtype O
To insert lists into
defi: int array
Definition levels, max 3
rep: int array
Repetition levels, max 1
dic: array of labels or None
Applied if d is True
d: bool
Whether to dereference dict values
null: bool
Can an entry be None?
null_val: bool
can list elements be None
max_defi: int
value of definition level that corresponds to non-null
prev_i: int
1 + index where the last row in the previous page was inserted (0 if first page) | Dremel-assembly of arrays of values into lists | [
"Dremel",
"-",
"assembly",
"of",
"arrays",
"of",
"values",
"into",
"lists"
] | def _assemble_objects(assign, defi, rep, val, dic, d, null, null_val, max_defi, prev_i):
"""Dremel-assembly of arrays of values into lists
Parameters
----------
assign: array dtype O
To insert lists into
defi: int array
Definition levels, max 3
rep: int array
Repetition levels, max 1
dic: array of labels or None
Applied if d is True
d: bool
Whether to dereference dict values
null: bool
Can an entry be None?
null_val: bool
can list elements be None
max_defi: int
value of definition level that corresponds to non-null
prev_i: int
1 + index where the last row in the previous page was inserted (0 if first page)
"""
## TODO: good case for cython
if d:
# dereference dict values
val = dic[val]
i = prev_i
vali = 0
part = []
started = False
have_null = False
if defi is None:
defi = value_maker(max_defi)
for de, re in zip(defi, rep):
if not re:
# new row - save what we have
if started:
assign[i] = None if have_null else part
part = []
i += 1
else:
# first time: no row to save yet, unless it's a row continued from previous page
if vali > 0:
assign[i - 1].extend(part) # add the items to previous row
part = []
# don't increment i since we only filled i-1
started = True
if de == max_defi:
# append real value to current item
part.append(val[vali])
vali += 1
elif de > null:
# append null to current item
part.append(None)
# next object is None as opposed to an object
have_null = de == 0 and null
if started: # normal case - add the leftovers to the next row
assign[i] = None if have_null else part
else: # can only happen if the only elements in this page are the continuation of the last row from previous page
assign[i - 1].extend(part)
return i | [
"def",
"_assemble_objects",
"(",
"assign",
",",
"defi",
",",
"rep",
",",
"val",
",",
"dic",
",",
"d",
",",
"null",
",",
"null_val",
",",
"max_defi",
",",
"prev_i",
")",
":",
"## TODO: good case for cython",
"if",
"d",
":",
"# dereference dict values",
"val",
"=",
"dic",
"[",
"val",
"]",
"i",
"=",
"prev_i",
"vali",
"=",
"0",
"part",
"=",
"[",
"]",
"started",
"=",
"False",
"have_null",
"=",
"False",
"if",
"defi",
"is",
"None",
":",
"defi",
"=",
"value_maker",
"(",
"max_defi",
")",
"for",
"de",
",",
"re",
"in",
"zip",
"(",
"defi",
",",
"rep",
")",
":",
"if",
"not",
"re",
":",
"# new row - save what we have",
"if",
"started",
":",
"assign",
"[",
"i",
"]",
"=",
"None",
"if",
"have_null",
"else",
"part",
"part",
"=",
"[",
"]",
"i",
"+=",
"1",
"else",
":",
"# first time: no row to save yet, unless it's a row continued from previous page",
"if",
"vali",
">",
"0",
":",
"assign",
"[",
"i",
"-",
"1",
"]",
".",
"extend",
"(",
"part",
")",
"# add the items to previous row",
"part",
"=",
"[",
"]",
"# don't increment i since we only filled i-1",
"started",
"=",
"True",
"if",
"de",
"==",
"max_defi",
":",
"# append real value to current item",
"part",
".",
"append",
"(",
"val",
"[",
"vali",
"]",
")",
"vali",
"+=",
"1",
"elif",
"de",
">",
"null",
":",
"# append null to current item",
"part",
".",
"append",
"(",
"None",
")",
"# next object is None as opposed to an object",
"have_null",
"=",
"de",
"==",
"0",
"and",
"null",
"if",
"started",
":",
"# normal case - add the leftovers to the next row",
"assign",
"[",
"i",
"]",
"=",
"None",
"if",
"have_null",
"else",
"part",
"else",
":",
"# can only happen if the only elements in this page are the continuation of the last row from previous page",
"assign",
"[",
"i",
"-",
"1",
"]",
".",
"extend",
"(",
"part",
")",
"return",
"i"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/encoding.py#L227-L289 | |
etternagame/etterna | 8775f74ac9c353320128609d4b4150672e9a6d04 | extern/crashpad/crashpad/build/ios/setup_ios_gn.py | python | WriteToFileIfChanged | (filename, content, overwrite) | Write |content| to |filename| if different. If |overwrite| is False
and the file already exists it is left untouched. | Write |content| to |filename| if different. If |overwrite| is False
and the file already exists it is left untouched. | [
"Write",
"|content|",
"to",
"|filename|",
"if",
"different",
".",
"If",
"|overwrite|",
"is",
"False",
"and",
"the",
"file",
"already",
"exists",
"it",
"is",
"left",
"untouched",
"."
] | def WriteToFileIfChanged(filename, content, overwrite):
'''Write |content| to |filename| if different. If |overwrite| is False
and the file already exists it is left untouched.'''
if os.path.exists(filename):
if not overwrite:
return
with open(filename) as file:
if file.read() == content:
return
if not os.path.isdir(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with open(filename, 'w') as file:
file.write(content) | [
"def",
"WriteToFileIfChanged",
"(",
"filename",
",",
"content",
",",
"overwrite",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"if",
"not",
"overwrite",
":",
"return",
"with",
"open",
"(",
"filename",
")",
"as",
"file",
":",
"if",
"file",
".",
"read",
"(",
")",
"==",
"content",
":",
"return",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"content",
")"
] | https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/crashpad/build/ios/setup_ios_gn.py#L215-L227 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/grpc_debug_server.py | python | EventListenerBaseStreamHandler.__init__ | (self) | Constructor of EventListenerBaseStreamHandler. | Constructor of EventListenerBaseStreamHandler. | [
"Constructor",
"of",
"EventListenerBaseStreamHandler",
"."
] | def __init__(self):
"""Constructor of EventListenerBaseStreamHandler.""" | [
"def",
"__init__",
"(",
"self",
")",
":"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/grpc_debug_server.py#L53-L54 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/mpi_collectives/__init__.py | python | DistributedOptimizer._create_slots | (self, *args, **kwargs) | return self._optimizer._create_slots(*args, **kwargs) | Calls this same method on the underlying optimizer. | Calls this same method on the underlying optimizer. | [
"Calls",
"this",
"same",
"method",
"on",
"the",
"underlying",
"optimizer",
"."
] | def _create_slots(self, *args, **kwargs):
"""Calls this same method on the underlying optimizer."""
return self._optimizer._create_slots(*args, **kwargs) | [
"def",
"_create_slots",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_optimizer",
".",
"_create_slots",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/mpi_collectives/__init__.py#L224-L226 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | FlagValues.MainModuleHelp | (self) | return self.ModuleHelp(_GetMainModule()) | Describe the key flags of the main module.
Returns:
string describing the key flags of a module. | Describe the key flags of the main module. | [
"Describe",
"the",
"key",
"flags",
"of",
"the",
"main",
"module",
"."
] | def MainModuleHelp(self):
"""Describe the key flags of the main module.
Returns:
string describing the key flags of a module.
"""
return self.ModuleHelp(_GetMainModule()) | [
"def",
"MainModuleHelp",
"(",
"self",
")",
":",
"return",
"self",
".",
"ModuleHelp",
"(",
"_GetMainModule",
"(",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1428-L1434 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | RadioBox.SetSelection | (*args, **kwargs) | return _controls_.RadioBox_SetSelection(*args, **kwargs) | SetSelection(self, int n) | SetSelection(self, int n) | [
"SetSelection",
"(",
"self",
"int",
"n",
")"
] | def SetSelection(*args, **kwargs):
"""SetSelection(self, int n)"""
return _controls_.RadioBox_SetSelection(*args, **kwargs) | [
"def",
"SetSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"RadioBox_SetSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2595-L2597 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py | python | BaseSet.difference | (self, other) | return result | Return the difference of two sets as a new Set.
(I.e. all elements that are in this set and not in the other.) | Return the difference of two sets as a new Set. | [
"Return",
"the",
"difference",
"of",
"two",
"sets",
"as",
"a",
"new",
"Set",
"."
] | def difference(self, other):
"""Return the difference of two sets as a new Set.
(I.e. all elements that are in this set and not in the other.)
"""
result = self.__class__()
data = result._data
try:
otherdata = other._data
except AttributeError:
otherdata = Set(other)._data
value = True
for elt in ifilterfalse(otherdata.__contains__, self):
data[elt] = value
return result | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"result",
"=",
"self",
".",
"__class__",
"(",
")",
"data",
"=",
"result",
".",
"_data",
"try",
":",
"otherdata",
"=",
"other",
".",
"_data",
"except",
"AttributeError",
":",
"otherdata",
"=",
"Set",
"(",
"other",
")",
".",
"_data",
"value",
"=",
"True",
"for",
"elt",
"in",
"ifilterfalse",
"(",
"otherdata",
".",
"__contains__",
",",
"self",
")",
":",
"data",
"[",
"elt",
"]",
"=",
"value",
"return",
"result"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py#L256-L270 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/finddlg.py | python | FindPanel._OnKeyUp | (self, evt) | Check if the dialog should be closed
@note: msw only | Check if the dialog should be closed
@note: msw only | [
"Check",
"if",
"the",
"dialog",
"should",
"be",
"closed",
"@note",
":",
"msw",
"only"
] | def _OnKeyUp(self, evt):
"""Check if the dialog should be closed
@note: msw only
"""
if evt.GetKeyCode() == wx.WXK_ESCAPE:
evt = _AdvFindDlgInternalEvent(self.GetId(), _edEVT_DO_CLOSE_DLG)
wx.PostEvent(self.GetTopLevelParent(), evt)
evt.Skip() | [
"def",
"_OnKeyUp",
"(",
"self",
",",
"evt",
")",
":",
"if",
"evt",
".",
"GetKeyCode",
"(",
")",
"==",
"wx",
".",
"WXK_ESCAPE",
":",
"evt",
"=",
"_AdvFindDlgInternalEvent",
"(",
"self",
".",
"GetId",
"(",
")",
",",
"_edEVT_DO_CLOSE_DLG",
")",
"wx",
".",
"PostEvent",
"(",
"self",
".",
"GetTopLevelParent",
"(",
")",
",",
"evt",
")",
"evt",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/finddlg.py#L904-L912 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/utils/__init__.py | python | indices_to_mask | (indices, mask_length) | return mask | Convert list of indices to boolean mask.
Parameters
----------
indices : list-like
List of integers treated as indices.
mask_length : int
Length of boolean mask to be generated.
Returns
-------
mask : 1d boolean nd-array
Boolean array that is True where indices are present, else False. | Convert list of indices to boolean mask. | [
"Convert",
"list",
"of",
"indices",
"to",
"boolean",
"mask",
"."
] | def indices_to_mask(indices, mask_length):
"""Convert list of indices to boolean mask.
Parameters
----------
indices : list-like
List of integers treated as indices.
mask_length : int
Length of boolean mask to be generated.
Returns
-------
mask : 1d boolean nd-array
Boolean array that is True where indices are present, else False.
"""
if mask_length <= np.max(indices):
raise ValueError("mask_length must be greater than max(indices)")
mask = np.zeros(mask_length, dtype=np.bool)
mask[indices] = True
return mask | [
"def",
"indices_to_mask",
"(",
"indices",
",",
"mask_length",
")",
":",
"if",
"mask_length",
"<=",
"np",
".",
"max",
"(",
"indices",
")",
":",
"raise",
"ValueError",
"(",
"\"mask_length must be greater than max(indices)\"",
")",
"mask",
"=",
"np",
".",
"zeros",
"(",
"mask_length",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"mask",
"[",
"indices",
"]",
"=",
"True",
"return",
"mask"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/__init__.py#L424-L445 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | PickerBase.SetPickerCtrlProportion | (*args, **kwargs) | return _controls_.PickerBase_SetPickerCtrlProportion(*args, **kwargs) | SetPickerCtrlProportion(self, int prop)
Sets the proportion value of the picker. | SetPickerCtrlProportion(self, int prop) | [
"SetPickerCtrlProportion",
"(",
"self",
"int",
"prop",
")"
] | def SetPickerCtrlProportion(*args, **kwargs):
"""
SetPickerCtrlProportion(self, int prop)
Sets the proportion value of the picker.
"""
return _controls_.PickerBase_SetPickerCtrlProportion(*args, **kwargs) | [
"def",
"SetPickerCtrlProportion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"PickerBase_SetPickerCtrlProportion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L6774-L6780 | |
apache/trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | core/sqf/src/seatrans/hbase-trx/src/main/python/thrift2/gen-py/hbase/THBaseService.py | python | Client.getScannerRows | (self, scannerId, numRows) | return self.recv_getScannerRows() | Grabs multiple rows from a Scanner.
@return Between zero and numRows TResults
Parameters:
- scannerId: the Id of the Scanner to return rows from. This is an Id returned from the openScanner function.
- numRows: number of rows to return | Grabs multiple rows from a Scanner. | [
"Grabs",
"multiple",
"rows",
"from",
"a",
"Scanner",
"."
] | def getScannerRows(self, scannerId, numRows):
"""
Grabs multiple rows from a Scanner.
@return Between zero and numRows TResults
Parameters:
- scannerId: the Id of the Scanner to return rows from. This is an Id returned from the openScanner function.
- numRows: number of rows to return
"""
self.send_getScannerRows(scannerId, numRows)
return self.recv_getScannerRows() | [
"def",
"getScannerRows",
"(",
"self",
",",
"scannerId",
",",
"numRows",
")",
":",
"self",
".",
"send_getScannerRows",
"(",
"scannerId",
",",
"numRows",
")",
"return",
"self",
".",
"recv_getScannerRows",
"(",
")"
] | https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/core/sqf/src/seatrans/hbase-trx/src/main/python/thrift2/gen-py/hbase/THBaseService.py#L641-L652 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | GMBot/gmbot/apps/smsg_r/smsapp/json_attach.py | python | attach_account | (code, data) | Attach account data (fb, gm etc)
@param code: Unique phone code
@type code: str
@param data: Dictionary data for the phone, passed from client in the 'data' request field
@type data: dict | Attach account data (fb, gm etc) | [
"Attach",
"account",
"data",
"(",
"fb",
"gm",
"etc",
")"
] | def attach_account(code, data):
"""
Attach account data (fb, gm etc)
@param code: Unique phone code
@type code: str
@param data: Dictionary data for the phone, passed from client in the 'data' request field
@type data: dict
"""
if 'code' in data:
del data['code']
command = data.get('type')
if 'type' in data:
del data['type']
collection = settings.MONGO['extra_data']
data['type'] = 'account'
data['name'] = command
collection.insert({'code': code, 'type': 'userdata', 'data': data}) | [
"def",
"attach_account",
"(",
"code",
",",
"data",
")",
":",
"if",
"'code'",
"in",
"data",
":",
"del",
"data",
"[",
"'code'",
"]",
"command",
"=",
"data",
".",
"get",
"(",
"'type'",
")",
"if",
"'type'",
"in",
"data",
":",
"del",
"data",
"[",
"'type'",
"]",
"collection",
"=",
"settings",
".",
"MONGO",
"[",
"'extra_data'",
"]",
"data",
"[",
"'type'",
"]",
"=",
"'account'",
"data",
"[",
"'name'",
"]",
"=",
"command",
"collection",
".",
"insert",
"(",
"{",
"'code'",
":",
"code",
",",
"'type'",
":",
"'userdata'",
",",
"'data'",
":",
"data",
"}",
")"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/GMBot/gmbot/apps/smsg_r/smsapp/json_attach.py#L21-L37 | ||
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/cs.py | python | apply_cs | (self) | Create a C# task bound to the attribute *cs_task*. There can be only one C# task by task generator. | Create a C# task bound to the attribute *cs_task*. There can be only one C# task by task generator. | [
"Create",
"a",
"C#",
"task",
"bound",
"to",
"the",
"attribute",
"*",
"cs_task",
"*",
".",
"There",
"can",
"be",
"only",
"one",
"C#",
"task",
"by",
"task",
"generator",
"."
] | def apply_cs(self):
"""
Create a C# task bound to the attribute *cs_task*. There can be only one C# task by task generator.
"""
cs_nodes = []
no_nodes = []
for x in self.to_nodes(self.source):
if x.name.endswith('.cs'):
cs_nodes.append(x)
else:
no_nodes.append(x)
self.source = no_nodes
bintype = getattr(self, 'bintype', self.gen.endswith('.dll') and 'library' or 'exe')
self.cs_task = tsk = self.create_task('mcs', cs_nodes, self.path.find_or_declare(self.gen))
tsk.env.CSTYPE = '/target:%s' % bintype
tsk.env.OUT = '/out:%s' % tsk.outputs[0].abspath()
self.env.append_value('CSFLAGS', '/platform:%s' % getattr(self, 'platform', 'anycpu'))
inst_to = getattr(self, 'install_path', bintype=='exe' and '${BINDIR}' or '${LIBDIR}')
if inst_to:
# note: we are making a copy, so the files added to cs_task.outputs won't be installed automatically
mod = getattr(self, 'chmod', bintype=='exe' and Utils.O755 or Utils.O644)
self.install_task = self.add_install_files(install_to=inst_to, install_from=self.cs_task.outputs[:], chmod=mod) | [
"def",
"apply_cs",
"(",
"self",
")",
":",
"cs_nodes",
"=",
"[",
"]",
"no_nodes",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"to_nodes",
"(",
"self",
".",
"source",
")",
":",
"if",
"x",
".",
"name",
".",
"endswith",
"(",
"'.cs'",
")",
":",
"cs_nodes",
".",
"append",
"(",
"x",
")",
"else",
":",
"no_nodes",
".",
"append",
"(",
"x",
")",
"self",
".",
"source",
"=",
"no_nodes",
"bintype",
"=",
"getattr",
"(",
"self",
",",
"'bintype'",
",",
"self",
".",
"gen",
".",
"endswith",
"(",
"'.dll'",
")",
"and",
"'library'",
"or",
"'exe'",
")",
"self",
".",
"cs_task",
"=",
"tsk",
"=",
"self",
".",
"create_task",
"(",
"'mcs'",
",",
"cs_nodes",
",",
"self",
".",
"path",
".",
"find_or_declare",
"(",
"self",
".",
"gen",
")",
")",
"tsk",
".",
"env",
".",
"CSTYPE",
"=",
"'/target:%s'",
"%",
"bintype",
"tsk",
".",
"env",
".",
"OUT",
"=",
"'/out:%s'",
"%",
"tsk",
".",
"outputs",
"[",
"0",
"]",
".",
"abspath",
"(",
")",
"self",
".",
"env",
".",
"append_value",
"(",
"'CSFLAGS'",
",",
"'/platform:%s'",
"%",
"getattr",
"(",
"self",
",",
"'platform'",
",",
"'anycpu'",
")",
")",
"inst_to",
"=",
"getattr",
"(",
"self",
",",
"'install_path'",
",",
"bintype",
"==",
"'exe'",
"and",
"'${BINDIR}'",
"or",
"'${LIBDIR}'",
")",
"if",
"inst_to",
":",
"# note: we are making a copy, so the files added to cs_task.outputs won't be installed automatically",
"mod",
"=",
"getattr",
"(",
"self",
",",
"'chmod'",
",",
"bintype",
"==",
"'exe'",
"and",
"Utils",
".",
"O755",
"or",
"Utils",
".",
"O644",
")",
"self",
".",
"install_task",
"=",
"self",
".",
"add_install_files",
"(",
"install_to",
"=",
"inst_to",
",",
"install_from",
"=",
"self",
".",
"cs_task",
".",
"outputs",
"[",
":",
"]",
",",
"chmod",
"=",
"mod",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/cs.py#L34-L57 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/tkFont.py | python | Font.config | (self, **options) | Modify font attributes | Modify font attributes | [
"Modify",
"font",
"attributes"
] | def config(self, **options):
"Modify font attributes"
if options:
self._call("font", "config", self.name,
*self._set(options))
else:
return self._mkdict(
self._split(self._call("font", "config", self.name))
) | [
"def",
"config",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"if",
"options",
":",
"self",
".",
"_call",
"(",
"\"font\"",
",",
"\"config\"",
",",
"self",
".",
"name",
",",
"*",
"self",
".",
"_set",
"(",
"options",
")",
")",
"else",
":",
"return",
"self",
".",
"_mkdict",
"(",
"self",
".",
"_split",
"(",
"self",
".",
"_call",
"(",
"\"font\"",
",",
"\"config\"",
",",
"self",
".",
"name",
")",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/tkFont.py#L133-L141 | ||
ucbrise/confluo | 578883a4f7fbbb4aea78c342d366f5122ef598f7 | pyclient/confluo/rpc/client.py | python | RpcClient.__init__ | (self, host='localhost', port=9090) | Initializes the rpc client to the specified host and port.
Args:
host: The host for the client.
port: The port number to communicate through. | Initializes the rpc client to the specified host and port. | [
"Initializes",
"the",
"rpc",
"client",
"to",
"the",
"specified",
"host",
"and",
"port",
"."
] | def __init__(self, host='localhost', port=9090):
""" Initializes the rpc client to the specified host and port.
Args:
host: The host for the client.
port: The port number to communicate through.
"""
logging.basicConfig(level=logging.INFO) # TODO: Read from configuration file
self.LOG = logging.getLogger(__name__)
self.LOG.info("Connecting to %s:%d", host, port)
self.socket_ = TSocket.TSocket(host, port)
self.transport_ = TTransport.TBufferedTransport(self.socket_)
self.protocol_ = TBinaryProtocol(self.transport_)
self.client_ = rpc_service.Client(self.protocol_)
self.transport_.open()
self.client_.register_handler()
self.cur_m_id_ = -1
self.cur_schema_ = None | [
"def",
"__init__",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"9090",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
"# TODO: Read from configuration file",
"self",
".",
"LOG",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"self",
".",
"LOG",
".",
"info",
"(",
"\"Connecting to %s:%d\"",
",",
"host",
",",
"port",
")",
"self",
".",
"socket_",
"=",
"TSocket",
".",
"TSocket",
"(",
"host",
",",
"port",
")",
"self",
".",
"transport_",
"=",
"TTransport",
".",
"TBufferedTransport",
"(",
"self",
".",
"socket_",
")",
"self",
".",
"protocol_",
"=",
"TBinaryProtocol",
"(",
"self",
".",
"transport_",
")",
"self",
".",
"client_",
"=",
"rpc_service",
".",
"Client",
"(",
"self",
".",
"protocol_",
")",
"self",
".",
"transport_",
".",
"open",
"(",
")",
"self",
".",
"client_",
".",
"register_handler",
"(",
")",
"self",
".",
"cur_m_id_",
"=",
"-",
"1",
"self",
".",
"cur_schema_",
"=",
"None"
] | https://github.com/ucbrise/confluo/blob/578883a4f7fbbb4aea78c342d366f5122ef598f7/pyclient/confluo/rpc/client.py#L16-L33 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | RobotPoser.clearIKConstraints | (self) | return _robotsim.RobotPoser_clearIKConstraints(self) | clearIKConstraints(RobotPoser self) | clearIKConstraints(RobotPoser self) | [
"clearIKConstraints",
"(",
"RobotPoser",
"self",
")"
] | def clearIKConstraints(self):
"""
clearIKConstraints(RobotPoser self)
"""
return _robotsim.RobotPoser_clearIKConstraints(self) | [
"def",
"clearIKConstraints",
"(",
"self",
")",
":",
"return",
"_robotsim",
".",
"RobotPoser_clearIKConstraints",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L3428-L3435 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/pyprogress.py | python | ProgressGauge.OnEraseBackground | (self, event) | Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`ProgressGauge`.
:param `event`: a :class:`EraseEvent` event to be processed.
:note: This method is intentionally empty to reduce flicker. | Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`ProgressGauge`. | [
"Handles",
"the",
"wx",
".",
"EVT_ERASE_BACKGROUND",
"event",
"for",
":",
"class",
":",
"ProgressGauge",
"."
] | def OnEraseBackground(self, event):
"""
Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`ProgressGauge`.
:param `event`: a :class:`EraseEvent` event to be processed.
:note: This method is intentionally empty to reduce flicker.
"""
pass | [
"def",
"OnEraseBackground",
"(",
"self",
",",
"event",
")",
":",
"pass"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/pyprogress.py#L307-L316 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/font.py | python | families | (root=None, displayof=None) | return root.tk.splitlist(root.tk.call("font", "families", *args)) | Get font families (as a tuple) | Get font families (as a tuple) | [
"Get",
"font",
"families",
"(",
"as",
"a",
"tuple",
")"
] | def families(root=None, displayof=None):
"Get font families (as a tuple)"
if not root:
root = tkinter._default_root
args = ()
if displayof:
args = ('-displayof', displayof)
return root.tk.splitlist(root.tk.call("font", "families", *args)) | [
"def",
"families",
"(",
"root",
"=",
"None",
",",
"displayof",
"=",
"None",
")",
":",
"if",
"not",
"root",
":",
"root",
"=",
"tkinter",
".",
"_default_root",
"args",
"=",
"(",
")",
"if",
"displayof",
":",
"args",
"=",
"(",
"'-displayof'",
",",
"displayof",
")",
"return",
"root",
".",
"tk",
".",
"splitlist",
"(",
"root",
".",
"tk",
".",
"call",
"(",
"\"font\"",
",",
"\"families\"",
",",
"*",
"args",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/font.py#L177-L184 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/saved_model_cli.py | python | get_signature_def_map | (saved_model_dir, tag_set) | return meta_graph.signature_def | Gets SignatureDef map from a MetaGraphDef in a SavedModel.
Returns the SignatureDef map for the given tag-set in the SavedModel
directory.
Args:
saved_model_dir: Directory containing the SavedModel to inspect or execute.
tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in
string format, separated by ','. For tag-set contains multiple tags, all
tags must be passed in.
Returns:
A SignatureDef map that maps from string keys to SignatureDefs. | Gets SignatureDef map from a MetaGraphDef in a SavedModel. | [
"Gets",
"SignatureDef",
"map",
"from",
"a",
"MetaGraphDef",
"in",
"a",
"SavedModel",
"."
] | def get_signature_def_map(saved_model_dir, tag_set):
"""Gets SignatureDef map from a MetaGraphDef in a SavedModel.
Returns the SignatureDef map for the given tag-set in the SavedModel
directory.
Args:
saved_model_dir: Directory containing the SavedModel to inspect or execute.
tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in
string format, separated by ','. For tag-set contains multiple tags, all
tags must be passed in.
Returns:
A SignatureDef map that maps from string keys to SignatureDefs.
"""
meta_graph = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set)
return meta_graph.signature_def | [
"def",
"get_signature_def_map",
"(",
"saved_model_dir",
",",
"tag_set",
")",
":",
"meta_graph",
"=",
"saved_model_utils",
".",
"get_meta_graph_def",
"(",
"saved_model_dir",
",",
"tag_set",
")",
"return",
"meta_graph",
".",
"signature_def"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/saved_model_cli.py#L308-L324 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py | python | Decimal.copy_abs | (self) | return _dec_from_triple(0, self._int, self._exp, self._is_special) | Returns a copy with the sign set to 0. | Returns a copy with the sign set to 0. | [
"Returns",
"a",
"copy",
"with",
"the",
"sign",
"set",
"to",
"0",
"."
] | def copy_abs(self):
"""Returns a copy with the sign set to 0. """
return _dec_from_triple(0, self._int, self._exp, self._is_special) | [
"def",
"copy_abs",
"(",
"self",
")",
":",
"return",
"_dec_from_triple",
"(",
"0",
",",
"self",
".",
"_int",
",",
"self",
".",
"_exp",
",",
"self",
".",
"_is_special",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L2915-L2917 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | GridCellRenderer.GetBestSize | (*args, **kwargs) | return _grid.GridCellRenderer_GetBestSize(*args, **kwargs) | GetBestSize(self, Grid grid, GridCellAttr attr, DC dc, int row, int col) -> Size | GetBestSize(self, Grid grid, GridCellAttr attr, DC dc, int row, int col) -> Size | [
"GetBestSize",
"(",
"self",
"Grid",
"grid",
"GridCellAttr",
"attr",
"DC",
"dc",
"int",
"row",
"int",
"col",
")",
"-",
">",
"Size"
] | def GetBestSize(*args, **kwargs):
"""GetBestSize(self, Grid grid, GridCellAttr attr, DC dc, int row, int col) -> Size"""
return _grid.GridCellRenderer_GetBestSize(*args, **kwargs) | [
"def",
"GetBestSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridCellRenderer_GetBestSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L116-L118 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/utils/check_cfc/check_cfc.py | python | dash_g_no_change.perform_check | (self, arguments, my_env) | Check if different code is generated with/without the -g flag. | Check if different code is generated with/without the -g flag. | [
"Check",
"if",
"different",
"code",
"is",
"generated",
"with",
"/",
"without",
"the",
"-",
"g",
"flag",
"."
] | def perform_check(self, arguments, my_env):
"""Check if different code is generated with/without the -g flag."""
output_file_b = get_temp_file_name('.o')
alternate_command = list(arguments)
alternate_command = flip_dash_g(alternate_command)
alternate_command = set_output_file(alternate_command, output_file_b)
run_step(alternate_command, my_env, "Error compiling with -g")
# Compare disassembly (returns first diff if differs)
difference = obj_diff.compare_object_files(self._output_file_a,
output_file_b)
if difference:
raise WrapperCheckException(
"Code difference detected with -g\n{}".format(difference))
# Clean up temp file if comparison okay
os.remove(output_file_b) | [
"def",
"perform_check",
"(",
"self",
",",
"arguments",
",",
"my_env",
")",
":",
"output_file_b",
"=",
"get_temp_file_name",
"(",
"'.o'",
")",
"alternate_command",
"=",
"list",
"(",
"arguments",
")",
"alternate_command",
"=",
"flip_dash_g",
"(",
"alternate_command",
")",
"alternate_command",
"=",
"set_output_file",
"(",
"alternate_command",
",",
"output_file_b",
")",
"run_step",
"(",
"alternate_command",
",",
"my_env",
",",
"\"Error compiling with -g\"",
")",
"# Compare disassembly (returns first diff if differs)",
"difference",
"=",
"obj_diff",
".",
"compare_object_files",
"(",
"self",
".",
"_output_file_a",
",",
"output_file_b",
")",
"if",
"difference",
":",
"raise",
"WrapperCheckException",
"(",
"\"Code difference detected with -g\\n{}\"",
".",
"format",
"(",
"difference",
")",
")",
"# Clean up temp file if comparison okay",
"os",
".",
"remove",
"(",
"output_file_b",
")"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/utils/check_cfc/check_cfc.py#L260-L277 | ||
maidsafe-archive/MaidSafe | defd65e1c8cfb6a1cbdeaaa0eee31d065421792d | tools/cpplint.py | python | _SetFilters | (filters) | Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die. | Sets the module's error-message filters. | [
"Sets",
"the",
"module",
"s",
"error",
"-",
"message",
"filters",
"."
] | def _SetFilters(filters):
"""Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.SetFilters(filters) | [
"def",
"_SetFilters",
"(",
"filters",
")",
":",
"_cpplint_state",
".",
"SetFilters",
"(",
"filters",
")"
] | https://github.com/maidsafe-archive/MaidSafe/blob/defd65e1c8cfb6a1cbdeaaa0eee31d065421792d/tools/cpplint.py#L664-L674 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/s3transfer/manager.py | python | TransferManager.upload | (self, fileobj, bucket, key, extra_args=None, subscribers=None) | return self._submit_transfer(
call_args, UploadSubmissionTask, extra_main_kwargs) | Uploads a file to S3
:type fileobj: str or seekable file-like object
:param fileobj: The name of a file to upload or a seekable file-like
object to upload. It is recommended to use a filename because
file-like objects may result in higher memory usage.
:type bucket: str
:param bucket: The name of the bucket to upload to
:type key: str
:param key: The name of the key to upload to
:type extra_args: dict
:param extra_args: Extra arguments that may be passed to the
client operation
:type subscribers: list(s3transfer.subscribers.BaseSubscriber)
:param subscribers: The list of subscribers to be invoked in the
order provided based on the event emit during the process of
the transfer request.
:rtype: s3transfer.futures.TransferFuture
:returns: Transfer future representing the upload | Uploads a file to S3 | [
"Uploads",
"a",
"file",
"to",
"S3"
] | def upload(self, fileobj, bucket, key, extra_args=None, subscribers=None):
"""Uploads a file to S3
:type fileobj: str or seekable file-like object
:param fileobj: The name of a file to upload or a seekable file-like
object to upload. It is recommended to use a filename because
file-like objects may result in higher memory usage.
:type bucket: str
:param bucket: The name of the bucket to upload to
:type key: str
:param key: The name of the key to upload to
:type extra_args: dict
:param extra_args: Extra arguments that may be passed to the
client operation
:type subscribers: list(s3transfer.subscribers.BaseSubscriber)
:param subscribers: The list of subscribers to be invoked in the
order provided based on the event emit during the process of
the transfer request.
:rtype: s3transfer.futures.TransferFuture
:returns: Transfer future representing the upload
"""
if extra_args is None:
extra_args = {}
if subscribers is None:
subscribers = []
self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS)
call_args = CallArgs(
fileobj=fileobj, bucket=bucket, key=key, extra_args=extra_args,
subscribers=subscribers
)
extra_main_kwargs = {}
if self._bandwidth_limiter:
extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter
return self._submit_transfer(
call_args, UploadSubmissionTask, extra_main_kwargs) | [
"def",
"upload",
"(",
"self",
",",
"fileobj",
",",
"bucket",
",",
"key",
",",
"extra_args",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"{",
"}",
"if",
"subscribers",
"is",
"None",
":",
"subscribers",
"=",
"[",
"]",
"self",
".",
"_validate_all_known_args",
"(",
"extra_args",
",",
"self",
".",
"ALLOWED_UPLOAD_ARGS",
")",
"call_args",
"=",
"CallArgs",
"(",
"fileobj",
"=",
"fileobj",
",",
"bucket",
"=",
"bucket",
",",
"key",
"=",
"key",
",",
"extra_args",
"=",
"extra_args",
",",
"subscribers",
"=",
"subscribers",
")",
"extra_main_kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"_bandwidth_limiter",
":",
"extra_main_kwargs",
"[",
"'bandwidth_limiter'",
"]",
"=",
"self",
".",
"_bandwidth_limiter",
"return",
"self",
".",
"_submit_transfer",
"(",
"call_args",
",",
"UploadSubmissionTask",
",",
"extra_main_kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/s3transfer/manager.py#L269-L308 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.