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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wuye9036/SalviaRenderer | a3931dec1b1e5375ef497a9d4d064f0521ba6f37 | blibs/cpuinfo.py | python | _get_cpu_info_from_sysinfo_v1 | () | Returns the CPU info gathered from sysinfo.
Returns {} if sysinfo is not found. | Returns the CPU info gathered from sysinfo.
Returns {} if sysinfo is not found. | [
"Returns",
"the",
"CPU",
"info",
"gathered",
"from",
"sysinfo",
".",
"Returns",
"{}",
"if",
"sysinfo",
"is",
"not",
"found",
"."
] | def _get_cpu_info_from_sysinfo_v1():
'''
Returns the CPU info gathered from sysinfo.
Returns {} if sysinfo is not found.
'''
try:
# Just return {} if there is no sysinfo
if not DataSource.has_sysinfo():
return {}
# If sysinfo fails return {}
returncode, output = DataSource.sysinfo_cpu()
if output == None or returncode != 0:
return {}
# Various fields
vendor_id = '' #_get_field(False, output, None, None, 'CPU #0: ')
processor_brand = output.split('CPU #0: "')[1].split('"\n')[0]
cache_size = '' #_get_field(False, output, None, None, 'machdep.cpu.cache.size')
stepping = int(output.split(', stepping ')[1].split(',')[0].strip())
model = int(output.split(', model ')[1].split(',')[0].strip())
family = int(output.split(', family ')[1].split(',')[0].strip())
# Flags
flags = []
for line in output.split('\n'):
if line.startswith('\t\t'):
for flag in line.strip().lower().split():
flags.append(flag)
flags.sort()
# Convert from GHz/MHz string to Hz
scale, hz_advertised = _get_hz_string_from_brand(processor_brand)
hz_actual = hz_advertised
info = {
'vendor_id' : vendor_id,
'brand' : processor_brand,
'hz_advertised' : _to_friendly_hz(hz_advertised, scale),
'hz_actual' : _to_friendly_hz(hz_actual, scale),
'hz_advertised_raw' : _to_raw_hz(hz_advertised, scale),
'hz_actual_raw' : _to_raw_hz(hz_actual, scale),
'l2_cache_size' : _to_friendly_bytes(cache_size),
'stepping' : stepping,
'model' : model,
'family' : family,
'flags' : flags
}
info = {k: v for k, v in info.items() if v}
return info
except:
return {} | [
"def",
"_get_cpu_info_from_sysinfo_v1",
"(",
")",
":",
"try",
":",
"# Just return {} if there is no sysinfo",
"if",
"not",
"DataSource",
".",
"has_sysinfo",
"(",
")",
":",
"return",
"{",
"}",
"# If sysinfo fails return {}",
"returncode",
",",
"output",
"=",
"DataSource",
".",
"sysinfo_cpu",
"(",
")",
"if",
"output",
"==",
"None",
"or",
"returncode",
"!=",
"0",
":",
"return",
"{",
"}",
"# Various fields",
"vendor_id",
"=",
"''",
"#_get_field(False, output, None, None, 'CPU #0: ')",
"processor_brand",
"=",
"output",
".",
"split",
"(",
"'CPU #0: \"'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'\"\\n'",
")",
"[",
"0",
"]",
"cache_size",
"=",
"''",
"#_get_field(False, output, None, None, 'machdep.cpu.cache.size')",
"stepping",
"=",
"int",
"(",
"output",
".",
"split",
"(",
"', stepping '",
")",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
"model",
"=",
"int",
"(",
"output",
".",
"split",
"(",
"', model '",
")",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
"family",
"=",
"int",
"(",
"output",
".",
"split",
"(",
"', family '",
")",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
"# Flags",
"flags",
"=",
"[",
"]",
"for",
"line",
"in",
"output",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'\\t\\t'",
")",
":",
"for",
"flag",
"in",
"line",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
":",
"flags",
".",
"append",
"(",
"flag",
")",
"flags",
".",
"sort",
"(",
")",
"# Convert from GHz/MHz string to Hz",
"scale",
",",
"hz_advertised",
"=",
"_get_hz_string_from_brand",
"(",
"processor_brand",
")",
"hz_actual",
"=",
"hz_advertised",
"info",
"=",
"{",
"'vendor_id'",
":",
"vendor_id",
",",
"'brand'",
":",
"processor_brand",
",",
"'hz_advertised'",
":",
"_to_friendly_hz",
"(",
"hz_advertised",
",",
"scale",
")",
",",
"'hz_actual'",
":",
"_to_friendly_hz",
"(",
"hz_actual",
",",
"scale",
")",
",",
"'hz_advertised_raw'",
":",
"_to_raw_hz",
"(",
"hz_advertised",
",",
"scale",
")",
",",
"'hz_actual_raw'",
":",
"_to_raw_hz",
"(",
"hz_actual",
",",
"scale",
")",
",",
"'l2_cache_size'",
":",
"_to_friendly_bytes",
"(",
"cache_size",
")",
",",
"'stepping'",
":",
"stepping",
",",
"'model'",
":",
"model",
",",
"'family'",
":",
"family",
",",
"'flags'",
":",
"flags",
"}",
"info",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"info",
".",
"items",
"(",
")",
"if",
"v",
"}",
"return",
"info",
"except",
":",
"return",
"{",
"}"
] | https://github.com/wuye9036/SalviaRenderer/blob/a3931dec1b1e5375ef497a9d4d064f0521ba6f37/blibs/cpuinfo.py#L1736-L1791 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/wizard.py | python | PyWizardPage.DoGetPosition | (*args, **kwargs) | return _wizard.PyWizardPage_DoGetPosition(*args, **kwargs) | DoGetPosition() -> (x,y) | DoGetPosition() -> (x,y) | [
"DoGetPosition",
"()",
"-",
">",
"(",
"x",
"y",
")"
] | def DoGetPosition(*args, **kwargs):
"""DoGetPosition() -> (x,y)"""
return _wizard.PyWizardPage_DoGetPosition(*args, **kwargs) | [
"def",
"DoGetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_wizard",
".",
"PyWizardPage_DoGetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/wizard.py#L175-L177 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/ndimage/filters.py | python | convolve | (input, weights, output=None, mode='reflect', cval=0.0,
origin=0) | return _correlate_or_convolve(input, weights, output, mode, cval,
origin, True) | Multidimensional convolution.
The array is convolved with the given kernel.
Parameters
----------
%(input)s
weights : array_like
Array of weights, same number of dimensions as input
%(output)s
%(mode_multiple)s
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0
%(origin_multiple)s
Returns
-------
result : ndarray
The result of convolution of `input` with `weights`.
See Also
--------
correlate : Correlate an image with a kernel.
Notes
-----
Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
W is the `weights` kernel,
j is the n-D spatial index over :math:`W`,
I is the `input` and k is the coordinate of the center of
W, specified by `origin` in the input parameters.
Examples
--------
Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
because in this case borders (i.e. where the `weights` kernel, centered
on any one value, extends beyond an edge of `input`) are treated as zeros.
>>> a = np.array([[1, 2, 0, 0],
... [5, 3, 0, 4],
... [0, 0, 0, 7],
... [9, 3, 0, 0]])
>>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
>>> from scipy import ndimage
>>> ndimage.convolve(a, k, mode='constant', cval=0.0)
array([[11, 10, 7, 4],
[10, 3, 11, 11],
[15, 12, 14, 7],
[12, 3, 7, 0]])
Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
with 1.0's (and then extracting only the original region of the result).
>>> ndimage.convolve(a, k, mode='constant', cval=1.0)
array([[13, 11, 8, 7],
[11, 3, 11, 14],
[16, 12, 14, 10],
[15, 6, 10, 5]])
With ``mode='reflect'`` (the default), outer values are reflected at the
edge of `input` to fill in missing values.
>>> b = np.array([[2, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
>>> ndimage.convolve(b, k, mode='reflect')
array([[5, 0, 0],
[3, 0, 0],
[1, 0, 0]])
This includes diagonally at the corners.
>>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
>>> ndimage.convolve(b, k)
array([[4, 2, 0],
[3, 2, 0],
[1, 1, 0]])
With ``mode='nearest'``, the single nearest value in to an edge in
`input` is repeated as many times as needed to match the overlapping
`weights`.
>>> c = np.array([[2, 0, 1],
... [1, 0, 0],
... [0, 0, 0]])
>>> k = np.array([[0, 1, 0],
... [0, 1, 0],
... [0, 1, 0],
... [0, 1, 0],
... [0, 1, 0]])
>>> ndimage.convolve(c, k, mode='nearest')
array([[7, 0, 3],
[5, 0, 2],
[3, 0, 1]]) | Multidimensional convolution. | [
"Multidimensional",
"convolution",
"."
] | def convolve(input, weights, output=None, mode='reflect', cval=0.0,
origin=0):
"""
Multidimensional convolution.
The array is convolved with the given kernel.
Parameters
----------
%(input)s
weights : array_like
Array of weights, same number of dimensions as input
%(output)s
%(mode_multiple)s
cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0
%(origin_multiple)s
Returns
-------
result : ndarray
The result of convolution of `input` with `weights`.
See Also
--------
correlate : Correlate an image with a kernel.
Notes
-----
Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
W is the `weights` kernel,
j is the n-D spatial index over :math:`W`,
I is the `input` and k is the coordinate of the center of
W, specified by `origin` in the input parameters.
Examples
--------
Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
because in this case borders (i.e. where the `weights` kernel, centered
on any one value, extends beyond an edge of `input`) are treated as zeros.
>>> a = np.array([[1, 2, 0, 0],
... [5, 3, 0, 4],
... [0, 0, 0, 7],
... [9, 3, 0, 0]])
>>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
>>> from scipy import ndimage
>>> ndimage.convolve(a, k, mode='constant', cval=0.0)
array([[11, 10, 7, 4],
[10, 3, 11, 11],
[15, 12, 14, 7],
[12, 3, 7, 0]])
Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
with 1.0's (and then extracting only the original region of the result).
>>> ndimage.convolve(a, k, mode='constant', cval=1.0)
array([[13, 11, 8, 7],
[11, 3, 11, 14],
[16, 12, 14, 10],
[15, 6, 10, 5]])
With ``mode='reflect'`` (the default), outer values are reflected at the
edge of `input` to fill in missing values.
>>> b = np.array([[2, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
>>> ndimage.convolve(b, k, mode='reflect')
array([[5, 0, 0],
[3, 0, 0],
[1, 0, 0]])
This includes diagonally at the corners.
>>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
>>> ndimage.convolve(b, k)
array([[4, 2, 0],
[3, 2, 0],
[1, 1, 0]])
With ``mode='nearest'``, the single nearest value in to an edge in
`input` is repeated as many times as needed to match the overlapping
`weights`.
>>> c = np.array([[2, 0, 1],
... [1, 0, 0],
... [0, 0, 0]])
>>> k = np.array([[0, 1, 0],
... [0, 1, 0],
... [0, 1, 0],
... [0, 1, 0],
... [0, 1, 0]])
>>> ndimage.convolve(c, k, mode='nearest')
array([[7, 0, 3],
[5, 0, 2],
[3, 0, 1]])
"""
return _correlate_or_convolve(input, weights, output, mode, cval,
origin, True) | [
"def",
"convolve",
"(",
"input",
",",
"weights",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"'reflect'",
",",
"cval",
"=",
"0.0",
",",
"origin",
"=",
"0",
")",
":",
"return",
"_correlate_or_convolve",
"(",
"input",
",",
"weights",
",",
"output",
",",
"mode",
",",
"cval",
",",
"origin",
",",
"True",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/ndimage/filters.py#L643-L745 | |
pytorch/ELF | e851e786ced8d26cf470f08a6b9bf7e413fc63f7 | src_py/elf/utils_elf.py | python | Batch.setzero | (self) | Set all tensors in the batch to 0 | Set all tensors in the batch to 0 | [
"Set",
"all",
"tensors",
"in",
"the",
"batch",
"to",
"0"
] | def setzero(self):
''' Set all tensors in the batch to 0 '''
for _, v in self.batch.items():
v[:] = 0 | [
"def",
"setzero",
"(",
"self",
")",
":",
"for",
"_",
",",
"v",
"in",
"self",
".",
"batch",
".",
"items",
"(",
")",
":",
"v",
"[",
":",
"]",
"=",
"0"
] | https://github.com/pytorch/ELF/blob/e851e786ced8d26cf470f08a6b9bf7e413fc63f7/src_py/elf/utils_elf.py#L175-L178 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TUCh.__init__ | (self, *args) | __init__(TUCh self) -> TUCh
__init__(TUCh self, uchar const & _Val) -> TUCh
Parameters:
_Val: uchar const &
__init__(TUCh self, TSIn SIn) -> TUCh
Parameters:
SIn: TSIn & | __init__(TUCh self) -> TUCh
__init__(TUCh self, uchar const & _Val) -> TUCh | [
"__init__",
"(",
"TUCh",
"self",
")",
"-",
">",
"TUCh",
"__init__",
"(",
"TUCh",
"self",
"uchar",
"const",
"&",
"_Val",
")",
"-",
">",
"TUCh"
] | def __init__(self, *args):
"""
__init__(TUCh self) -> TUCh
__init__(TUCh self, uchar const & _Val) -> TUCh
Parameters:
_Val: uchar const &
__init__(TUCh self, TSIn SIn) -> TUCh
Parameters:
SIn: TSIn &
"""
_snap.TUCh_swiginit(self,_snap.new_TUCh(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_snap",
".",
"TUCh_swiginit",
"(",
"self",
",",
"_snap",
".",
"new_TUCh",
"(",
"*",
"args",
")",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L12732-L12746 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py | python | CWSCDReductionControl.load_mask_file | (self, mask_file_name, mask_tag) | return roi_range | load an XML mask file to a workspace and parse to ROI that can be mapped pixels in 2D notion
:param mask_file_name:
:param mask_tag
:return: 2-tuple (lower left corner (size = 2), upper right corner (size = 2))
both of them are in order of row and column number (y and x respectively) | load an XML mask file to a workspace and parse to ROI that can be mapped pixels in 2D notion
:param mask_file_name:
:param mask_tag
:return: 2-tuple (lower left corner (size = 2), upper right corner (size = 2))
both of them are in order of row and column number (y and x respectively) | [
"load",
"an",
"XML",
"mask",
"file",
"to",
"a",
"workspace",
"and",
"parse",
"to",
"ROI",
"that",
"can",
"be",
"mapped",
"pixels",
"in",
"2D",
"notion",
":",
"param",
"mask_file_name",
":",
":",
"param",
"mask_tag",
":",
"return",
":",
"2",
"-",
"tuple",
"(",
"lower",
"left",
"corner",
"(",
"size",
"=",
"2",
")",
"upper",
"right",
"corner",
"(",
"size",
"=",
"2",
"))",
"both",
"of",
"them",
"are",
"in",
"order",
"of",
"row",
"and",
"column",
"number",
"(",
"y",
"and",
"x",
"respectively",
")"
] | def load_mask_file(self, mask_file_name, mask_tag):
"""
load an XML mask file to a workspace and parse to ROI that can be mapped pixels in 2D notion
:param mask_file_name:
:param mask_tag
:return: 2-tuple (lower left corner (size = 2), upper right corner (size = 2))
both of them are in order of row and column number (y and x respectively)
"""
# load mask file
assert isinstance(mask_file_name, str), 'Mask file {0} shall be a string but not a {1}.' \
''.format(mask_file_name, type(mask_file_name))
assert isinstance(mask_tag, str), 'Mask tag {0} shall be a string but not a {1}.' \
''.format(mask_tag, type(mask_tag))
if os.path.exists(mask_file_name) is False:
raise RuntimeError('Mask file name {0} cannot be found.'.format(mask_tag))
# load
mantidsimple.LoadMask(Instrument='HB3A',
InputFile=mask_file_name,
OutputWorkspace=mask_tag)
# record
self.set_roi_workspace(roi_name=mask_tag, mask_ws_name=mask_tag)
# find out the range of the ROI in (Low left, upper right) mode
roi_range = process_mask.get_region_of_interest(mask_tag)
self.set_roi(mask_tag, roi_range[0], roi_range[1])
return roi_range | [
"def",
"load_mask_file",
"(",
"self",
",",
"mask_file_name",
",",
"mask_tag",
")",
":",
"# load mask file",
"assert",
"isinstance",
"(",
"mask_file_name",
",",
"str",
")",
",",
"'Mask file {0} shall be a string but not a {1}.'",
"''",
".",
"format",
"(",
"mask_file_name",
",",
"type",
"(",
"mask_file_name",
")",
")",
"assert",
"isinstance",
"(",
"mask_tag",
",",
"str",
")",
",",
"'Mask tag {0} shall be a string but not a {1}.'",
"''",
".",
"format",
"(",
"mask_tag",
",",
"type",
"(",
"mask_tag",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"mask_file_name",
")",
"is",
"False",
":",
"raise",
"RuntimeError",
"(",
"'Mask file name {0} cannot be found.'",
".",
"format",
"(",
"mask_tag",
")",
")",
"# load",
"mantidsimple",
".",
"LoadMask",
"(",
"Instrument",
"=",
"'HB3A'",
",",
"InputFile",
"=",
"mask_file_name",
",",
"OutputWorkspace",
"=",
"mask_tag",
")",
"# record",
"self",
".",
"set_roi_workspace",
"(",
"roi_name",
"=",
"mask_tag",
",",
"mask_ws_name",
"=",
"mask_tag",
")",
"# find out the range of the ROI in (Low left, upper right) mode",
"roi_range",
"=",
"process_mask",
".",
"get_region_of_interest",
"(",
"mask_tag",
")",
"self",
".",
"set_roi",
"(",
"mask_tag",
",",
"roi_range",
"[",
"0",
"]",
",",
"roi_range",
"[",
"1",
"]",
")",
"return",
"roi_range"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py#L2429-L2456 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeSummary.__eq__ | (self, *args) | return _lldb.SBTypeSummary___eq__(self, *args) | __eq__(self, SBTypeSummary rhs) -> bool | __eq__(self, SBTypeSummary rhs) -> bool | [
"__eq__",
"(",
"self",
"SBTypeSummary",
"rhs",
")",
"-",
">",
"bool"
] | def __eq__(self, *args):
"""__eq__(self, SBTypeSummary rhs) -> bool"""
return _lldb.SBTypeSummary___eq__(self, *args) | [
"def",
"__eq__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBTypeSummary___eq__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11479-L11481 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/activations.py | python | softmax | (x, axis=-1) | Softmax activation function.
Arguments:
x : Tensor.
axis: Integer, axis along which the softmax normalization is applied.
Returns:
Tensor, output of softmax transformation.
Raises:
ValueError: In case `dim(x) == 1`. | Softmax activation function. | [
"Softmax",
"activation",
"function",
"."
] | def softmax(x, axis=-1):
"""Softmax activation function.
Arguments:
x : Tensor.
axis: Integer, axis along which the softmax normalization is applied.
Returns:
Tensor, output of softmax transformation.
Raises:
ValueError: In case `dim(x) == 1`.
"""
ndim = K.ndim(x)
if ndim == 2:
return K.softmax(x)
elif ndim > 2:
e = K.exp(x - K.max(x, axis=axis, keepdims=True))
s = K.sum(e, axis=axis, keepdims=True)
return e / s
else:
raise ValueError('Cannot apply softmax to a tensor that is 1D') | [
"def",
"softmax",
"(",
"x",
",",
"axis",
"=",
"-",
"1",
")",
":",
"ndim",
"=",
"K",
".",
"ndim",
"(",
"x",
")",
"if",
"ndim",
"==",
"2",
":",
"return",
"K",
".",
"softmax",
"(",
"x",
")",
"elif",
"ndim",
">",
"2",
":",
"e",
"=",
"K",
".",
"exp",
"(",
"x",
"-",
"K",
".",
"max",
"(",
"x",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"True",
")",
")",
"s",
"=",
"K",
".",
"sum",
"(",
"e",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"True",
")",
"return",
"e",
"/",
"s",
"else",
":",
"raise",
"ValueError",
"(",
"'Cannot apply softmax to a tensor that is 1D'",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/activations.py#L29-L50 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/ssd/dataset/pascal_voc.py | python | PascalVoc._load_image_labels | (self) | return temp | preprocess all ground-truths
Returns:
----------
labels packed in [num_images x max_num_objects x 5] tensor | preprocess all ground-truths | [
"preprocess",
"all",
"ground",
"-",
"truths"
] | def _load_image_labels(self):
"""
preprocess all ground-truths
Returns:
----------
labels packed in [num_images x max_num_objects x 5] tensor
"""
temp = []
# load ground-truth from xml annotations
for idx in self.image_set_index:
label_file = self._label_path_from_index(idx)
tree = ET.parse(label_file)
root = tree.getroot()
size = root.find('size')
width = float(size.find('width').text)
height = float(size.find('height').text)
label = []
for obj in root.iter('object'):
difficult = int(obj.find('difficult').text)
# if not self.config['use_difficult'] and difficult == 1:
# continue
cls_name = obj.find('name').text
if cls_name not in self.classes:
continue
cls_id = self.classes.index(cls_name)
xml_box = obj.find('bndbox')
xmin = float(xml_box.find('xmin').text) / width
ymin = float(xml_box.find('ymin').text) / height
xmax = float(xml_box.find('xmax').text) / width
ymax = float(xml_box.find('ymax').text) / height
label.append([cls_id, xmin, ymin, xmax, ymax, difficult])
temp.append(np.array(label))
return temp | [
"def",
"_load_image_labels",
"(",
"self",
")",
":",
"temp",
"=",
"[",
"]",
"# load ground-truth from xml annotations",
"for",
"idx",
"in",
"self",
".",
"image_set_index",
":",
"label_file",
"=",
"self",
".",
"_label_path_from_index",
"(",
"idx",
")",
"tree",
"=",
"ET",
".",
"parse",
"(",
"label_file",
")",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"size",
"=",
"root",
".",
"find",
"(",
"'size'",
")",
"width",
"=",
"float",
"(",
"size",
".",
"find",
"(",
"'width'",
")",
".",
"text",
")",
"height",
"=",
"float",
"(",
"size",
".",
"find",
"(",
"'height'",
")",
".",
"text",
")",
"label",
"=",
"[",
"]",
"for",
"obj",
"in",
"root",
".",
"iter",
"(",
"'object'",
")",
":",
"difficult",
"=",
"int",
"(",
"obj",
".",
"find",
"(",
"'difficult'",
")",
".",
"text",
")",
"# if not self.config['use_difficult'] and difficult == 1:",
"# continue",
"cls_name",
"=",
"obj",
".",
"find",
"(",
"'name'",
")",
".",
"text",
"if",
"cls_name",
"not",
"in",
"self",
".",
"classes",
":",
"continue",
"cls_id",
"=",
"self",
".",
"classes",
".",
"index",
"(",
"cls_name",
")",
"xml_box",
"=",
"obj",
".",
"find",
"(",
"'bndbox'",
")",
"xmin",
"=",
"float",
"(",
"xml_box",
".",
"find",
"(",
"'xmin'",
")",
".",
"text",
")",
"/",
"width",
"ymin",
"=",
"float",
"(",
"xml_box",
".",
"find",
"(",
"'ymin'",
")",
".",
"text",
")",
"/",
"height",
"xmax",
"=",
"float",
"(",
"xml_box",
".",
"find",
"(",
"'xmax'",
")",
".",
"text",
")",
"/",
"width",
"ymax",
"=",
"float",
"(",
"xml_box",
".",
"find",
"(",
"'ymax'",
")",
".",
"text",
")",
"/",
"height",
"label",
".",
"append",
"(",
"[",
"cls_id",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"difficult",
"]",
")",
"temp",
".",
"append",
"(",
"np",
".",
"array",
"(",
"label",
")",
")",
"return",
"temp"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/dataset/pascal_voc.py#L150-L185 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | IndividualLayoutConstraint.ResetIfWin | (*args, **kwargs) | return _core_.IndividualLayoutConstraint_ResetIfWin(*args, **kwargs) | ResetIfWin(self, Window otherW) -> bool
Reset constraint if it mentions otherWin | ResetIfWin(self, Window otherW) -> bool | [
"ResetIfWin",
"(",
"self",
"Window",
"otherW",
")",
"-",
">",
"bool"
] | def ResetIfWin(*args, **kwargs):
"""
ResetIfWin(self, Window otherW) -> bool
Reset constraint if it mentions otherWin
"""
return _core_.IndividualLayoutConstraint_ResetIfWin(*args, **kwargs) | [
"def",
"ResetIfWin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"IndividualLayoutConstraint_ResetIfWin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L16276-L16282 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/functions/PrimStretchedExpFT.py | python | PrimStretchedExpFT.init | (self) | Declare parameters that participate in the fitting | Declare parameters that participate in the fitting | [
"Declare",
"parameters",
"that",
"participate",
"in",
"the",
"fitting"
] | def init(self):
"""Declare parameters that participate in the fitting"""
pass | [
"def",
"init",
"(",
"self",
")",
":",
"pass"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/functions/PrimStretchedExpFT.py#L30-L32 | ||
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/character/character_module.py | python | Trait.may_research_tech_classic | (self, tech) | return True | Return True if permitted to research ''tech''. This is called in the classic research algorithm. | Return True if permitted to research ''tech''. This is called in the classic research algorithm. | [
"Return",
"True",
"if",
"permitted",
"to",
"research",
"tech",
".",
"This",
"is",
"called",
"in",
"the",
"classic",
"research",
"algorithm",
"."
] | def may_research_tech_classic(self, tech): # pylint: disable=no-self-use,unused-argument
"""Return True if permitted to research ''tech''. This is called in the classic research algorithm."""
# TODO remove this tap when the classic research algorithm is removed.
return True | [
"def",
"may_research_tech_classic",
"(",
"self",
",",
"tech",
")",
":",
"# pylint: disable=no-self-use,unused-argument",
"# TODO remove this tap when the classic research algorithm is removed.",
"return",
"True"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/character/character_module.py#L267-L270 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/DICOM/DICOM.py | python | DICOMLoadingByDragAndDropEventFilter.eventFilter | (self, object, event) | return False | Custom event filter for Slicer Main Window.
Inputs: Object (QObject), Event (QEvent) | Custom event filter for Slicer Main Window. | [
"Custom",
"event",
"filter",
"for",
"Slicer",
"Main",
"Window",
"."
] | def eventFilter(self, object, event):
"""
Custom event filter for Slicer Main Window.
Inputs: Object (QObject), Event (QEvent)
"""
if event.type() == qt.QEvent.DragEnter:
self.dragEnterEvent(event)
return True
if event.type() == qt.QEvent.Drop:
self.dropEvent(event)
return True
return False | [
"def",
"eventFilter",
"(",
"self",
",",
"object",
",",
"event",
")",
":",
"if",
"event",
".",
"type",
"(",
")",
"==",
"qt",
".",
"QEvent",
".",
"DragEnter",
":",
"self",
".",
"dragEnterEvent",
"(",
"event",
")",
"return",
"True",
"if",
"event",
".",
"type",
"(",
")",
"==",
"qt",
".",
"QEvent",
".",
"Drop",
":",
"self",
".",
"dropEvent",
"(",
"event",
")",
"return",
"True",
"return",
"False"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/DICOM/DICOM.py#L450-L462 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PGCommonValue.GetEditableText | (*args, **kwargs) | return _propgrid.PGCommonValue_GetEditableText(*args, **kwargs) | GetEditableText(self) -> String | GetEditableText(self) -> String | [
"GetEditableText",
"(",
"self",
")",
"-",
">",
"String"
] | def GetEditableText(*args, **kwargs):
"""GetEditableText(self) -> String"""
return _propgrid.PGCommonValue_GetEditableText(*args, **kwargs) | [
"def",
"GetEditableText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGCommonValue_GetEditableText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L1858-L1860 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/utils.py | python | LRUCache.__getitem__ | (self, key) | Get an item from the cache. Moves the item up so that it has the
highest priority then.
Raise a `KeyError` if it does not exist. | Get an item from the cache. Moves the item up so that it has the
highest priority then. | [
"Get",
"an",
"item",
"from",
"the",
"cache",
".",
"Moves",
"the",
"item",
"up",
"so",
"that",
"it",
"has",
"the",
"highest",
"priority",
"then",
"."
] | def __getitem__(self, key):
"""Get an item from the cache. Moves the item up so that it has the
highest priority then.
Raise a `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
rv = self._mapping[key]
if self._queue[-1] != key:
try:
self._remove(key)
except ValueError:
# if something removed the key from the container
# when we read, ignore the ValueError that we would
# get otherwise.
pass
self._append(key)
return rv
finally:
self._wlock.release() | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"rv",
"=",
"self",
".",
"_mapping",
"[",
"key",
"]",
"if",
"self",
".",
"_queue",
"[",
"-",
"1",
"]",
"!=",
"key",
":",
"try",
":",
"self",
".",
"_remove",
"(",
"key",
")",
"except",
"ValueError",
":",
"# if something removed the key from the container",
"# when we read, ignore the ValueError that we would",
"# get otherwise.",
"pass",
"self",
".",
"_append",
"(",
"key",
")",
"return",
"rv",
"finally",
":",
"self",
".",
"_wlock",
".",
"release",
"(",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/utils.py#L392-L412 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/dataview.py | python | DataViewIndexListModel.GetItem | (*args, **kwargs) | return _dataview.DataViewIndexListModel_GetItem(*args, **kwargs) | GetItem(self, unsigned int row) -> DataViewItem
Returns the DataViewItem for the item at row. | GetItem(self, unsigned int row) -> DataViewItem | [
"GetItem",
"(",
"self",
"unsigned",
"int",
"row",
")",
"-",
">",
"DataViewItem"
] | def GetItem(*args, **kwargs):
"""
GetItem(self, unsigned int row) -> DataViewItem
Returns the DataViewItem for the item at row.
"""
return _dataview.DataViewIndexListModel_GetItem(*args, **kwargs) | [
"def",
"GetItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewIndexListModel_GetItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L926-L932 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PrintDialogData.SetCollate | (*args, **kwargs) | return _windows_.PrintDialogData_SetCollate(*args, **kwargs) | SetCollate(self, bool flag) | SetCollate(self, bool flag) | [
"SetCollate",
"(",
"self",
"bool",
"flag",
")"
] | def SetCollate(*args, **kwargs):
"""SetCollate(self, bool flag)"""
return _windows_.PrintDialogData_SetCollate(*args, **kwargs) | [
"def",
"SetCollate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintDialogData_SetCollate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L5114-L5116 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | diagonal | (a, k = 0, axis1=0, axis2=1) | diagonal(a,k=0,axis1=0, axis2=1) = the k'th diagonal of a | diagonal(a,k=0,axis1=0, axis2=1) = the k'th diagonal of a | [
"diagonal",
"(",
"a",
"k",
"=",
"0",
"axis1",
"=",
"0",
"axis2",
"=",
"1",
")",
"=",
"the",
"k",
"th",
"diagonal",
"of",
"a"
] | def diagonal(a, k = 0, axis1=0, axis2=1):
"""diagonal(a,k=0,axis1=0, axis2=1) = the k'th diagonal of a"""
d = fromnumeric.diagonal(filled(a), k, axis1, axis2)
m = getmask(a)
if m is nomask:
return masked_array(d, m)
else:
return masked_array(d, fromnumeric.diagonal(m, k, axis1, axis2)) | [
"def",
"diagonal",
"(",
"a",
",",
"k",
"=",
"0",
",",
"axis1",
"=",
"0",
",",
"axis2",
"=",
"1",
")",
":",
"d",
"=",
"fromnumeric",
".",
"diagonal",
"(",
"filled",
"(",
"a",
")",
",",
"k",
",",
"axis1",
",",
"axis2",
")",
"m",
"=",
"getmask",
"(",
"a",
")",
"if",
"m",
"is",
"nomask",
":",
"return",
"masked_array",
"(",
"d",
",",
"m",
")",
"else",
":",
"return",
"masked_array",
"(",
"d",
",",
"fromnumeric",
".",
"diagonal",
"(",
"m",
",",
"k",
",",
"axis1",
",",
"axis2",
")",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L2069-L2076 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Alignment/MuonAlignment/python/svgfig.py | python | SVG.tree | (self, depth_limit=None, sub=True, attr=True, text=True, tree_width=20, obj_width=80) | return "\n".join(output) | Print (actually, return a string of) the tree in a form useful for browsing.
If depth_limit == a number, stop recursion at that depth.
If sub == False, do not show sub-elements.
If attr == False, do not show attributes.
If text == False, do not show text/Unicode sub-elements.
tree_width is the number of characters reserved for printing tree indexes.
obj_width is the number of characters reserved for printing sub-elements/attributes. | Print (actually, return a string of) the tree in a form useful for browsing. | [
"Print",
"(",
"actually",
"return",
"a",
"string",
"of",
")",
"the",
"tree",
"in",
"a",
"form",
"useful",
"for",
"browsing",
"."
] | def tree(self, depth_limit=None, sub=True, attr=True, text=True, tree_width=20, obj_width=80):
"""Print (actually, return a string of) the tree in a form useful for browsing.
If depth_limit == a number, stop recursion at that depth.
If sub == False, do not show sub-elements.
If attr == False, do not show attributes.
If text == False, do not show text/Unicode sub-elements.
tree_width is the number of characters reserved for printing tree indexes.
obj_width is the number of characters reserved for printing sub-elements/attributes.
"""
output = []
line = "%s %s" % (("%%-%ds" % tree_width) % repr(None), ("%%-%ds" % obj_width) % (repr(self))[0:obj_width])
output.append(line)
for ti, s in self.depth_first(depth_limit):
show = False
if isinstance(ti[-1], (int, long)):
if isinstance(s, str): show = text
else: show = sub
else: show = attr
if show:
line = "%s %s" % (("%%-%ds" % tree_width) % repr(list(ti)), ("%%-%ds" % obj_width) % (" "*len(ti) + repr(s))[0:obj_width])
output.append(line)
return "\n".join(output) | [
"def",
"tree",
"(",
"self",
",",
"depth_limit",
"=",
"None",
",",
"sub",
"=",
"True",
",",
"attr",
"=",
"True",
",",
"text",
"=",
"True",
",",
"tree_width",
"=",
"20",
",",
"obj_width",
"=",
"80",
")",
":",
"output",
"=",
"[",
"]",
"line",
"=",
"\"%s %s\"",
"%",
"(",
"(",
"\"%%-%ds\"",
"%",
"tree_width",
")",
"%",
"repr",
"(",
"None",
")",
",",
"(",
"\"%%-%ds\"",
"%",
"obj_width",
")",
"%",
"(",
"repr",
"(",
"self",
")",
")",
"[",
"0",
":",
"obj_width",
"]",
")",
"output",
".",
"append",
"(",
"line",
")",
"for",
"ti",
",",
"s",
"in",
"self",
".",
"depth_first",
"(",
"depth_limit",
")",
":",
"show",
"=",
"False",
"if",
"isinstance",
"(",
"ti",
"[",
"-",
"1",
"]",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"show",
"=",
"text",
"else",
":",
"show",
"=",
"sub",
"else",
":",
"show",
"=",
"attr",
"if",
"show",
":",
"line",
"=",
"\"%s %s\"",
"%",
"(",
"(",
"\"%%-%ds\"",
"%",
"tree_width",
")",
"%",
"repr",
"(",
"list",
"(",
"ti",
")",
")",
",",
"(",
"\"%%-%ds\"",
"%",
"obj_width",
")",
"%",
"(",
"\" \"",
"*",
"len",
"(",
"ti",
")",
"+",
"repr",
"(",
"s",
")",
")",
"[",
"0",
":",
"obj_width",
"]",
")",
"output",
".",
"append",
"(",
"line",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"output",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MuonAlignment/python/svgfig.py#L291-L318 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/layer2.py | python | Layer2.get_item | (self, table, hash_key, range_key=None,
attributes_to_get=None, consistent_read=False,
item_class=Item) | return item | Retrieve an existing item from the table.
:type table: :class:`boto.dynamodb.table.Table`
:param table: The Table object from which the item is retrieved.
:type hash_key: int|long|float|str|unicode|Binary
:param hash_key: The HashKey of the requested item. The
type of the value must match the type defined in the
schema for the table.
:type range_key: int|long|float|str|unicode|Binary
:param range_key: The optional RangeKey of the requested item.
The type of the value must match the type defined in the
schema for the table.
:type attributes_to_get: list
:param attributes_to_get: A list of attribute names.
If supplied, only the specified attribute names will
be returned. Otherwise, all attributes will be returned.
:type consistent_read: bool
:param consistent_read: If True, a consistent read
request is issued. Otherwise, an eventually consistent
request is issued.
:type item_class: Class
:param item_class: Allows you to override the class used
to generate the items. This should be a subclass of
:class:`boto.dynamodb.item.Item` | Retrieve an existing item from the table. | [
"Retrieve",
"an",
"existing",
"item",
"from",
"the",
"table",
"."
] | def get_item(self, table, hash_key, range_key=None,
attributes_to_get=None, consistent_read=False,
item_class=Item):
"""
Retrieve an existing item from the table.
:type table: :class:`boto.dynamodb.table.Table`
:param table: The Table object from which the item is retrieved.
:type hash_key: int|long|float|str|unicode|Binary
:param hash_key: The HashKey of the requested item. The
type of the value must match the type defined in the
schema for the table.
:type range_key: int|long|float|str|unicode|Binary
:param range_key: The optional RangeKey of the requested item.
The type of the value must match the type defined in the
schema for the table.
:type attributes_to_get: list
:param attributes_to_get: A list of attribute names.
If supplied, only the specified attribute names will
be returned. Otherwise, all attributes will be returned.
:type consistent_read: bool
:param consistent_read: If True, a consistent read
request is issued. Otherwise, an eventually consistent
request is issued.
:type item_class: Class
:param item_class: Allows you to override the class used
to generate the items. This should be a subclass of
:class:`boto.dynamodb.item.Item`
"""
key = self.build_key_from_values(table.schema, hash_key, range_key)
response = self.layer1.get_item(table.name, key,
attributes_to_get, consistent_read,
object_hook=self.dynamizer.decode)
item = item_class(table, hash_key, range_key, response['Item'])
if 'ConsumedCapacityUnits' in response:
item.consumed_units = response['ConsumedCapacityUnits']
return item | [
"def",
"get_item",
"(",
"self",
",",
"table",
",",
"hash_key",
",",
"range_key",
"=",
"None",
",",
"attributes_to_get",
"=",
"None",
",",
"consistent_read",
"=",
"False",
",",
"item_class",
"=",
"Item",
")",
":",
"key",
"=",
"self",
".",
"build_key_from_values",
"(",
"table",
".",
"schema",
",",
"hash_key",
",",
"range_key",
")",
"response",
"=",
"self",
".",
"layer1",
".",
"get_item",
"(",
"table",
".",
"name",
",",
"key",
",",
"attributes_to_get",
",",
"consistent_read",
",",
"object_hook",
"=",
"self",
".",
"dynamizer",
".",
"decode",
")",
"item",
"=",
"item_class",
"(",
"table",
",",
"hash_key",
",",
"range_key",
",",
"response",
"[",
"'Item'",
"]",
")",
"if",
"'ConsumedCapacityUnits'",
"in",
"response",
":",
"item",
".",
"consumed_units",
"=",
"response",
"[",
"'ConsumedCapacityUnits'",
"]",
"return",
"item"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/layer2.py#L452-L493 | |
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/descriptor.py | python | Descriptor.CopyToProto | (self, proto) | Copies this to a descriptor_pb2.DescriptorProto.
Args:
proto: An empty descriptor_pb2.DescriptorProto. | Copies this to a descriptor_pb2.DescriptorProto. | [
"Copies",
"this",
"to",
"a",
"descriptor_pb2",
".",
"DescriptorProto",
"."
] | def CopyToProto(self, proto):
"""Copies this to a descriptor_pb2.DescriptorProto.
Args:
proto: An empty descriptor_pb2.DescriptorProto.
"""
# This function is overriden to give a better doc comment.
super(Descriptor, self).CopyToProto(proto) | [
"def",
"CopyToProto",
"(",
"self",
",",
"proto",
")",
":",
"# This function is overriden to give a better doc comment.",
"super",
"(",
"Descriptor",
",",
"self",
")",
".",
"CopyToProto",
"(",
"proto",
")"
] | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/descriptor.py#L253-L260 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatnotebook.py | python | PageContainer.GetEnabled | (self, page) | return self._pagesInfoVec[page].GetEnabled() | Returns whether a tab is enabled or not.
:param `page`: an integer specifying the page index. | Returns whether a tab is enabled or not. | [
"Returns",
"whether",
"a",
"tab",
"is",
"enabled",
"or",
"not",
"."
] | def GetEnabled(self, page):
"""
Returns whether a tab is enabled or not.
:param `page`: an integer specifying the page index.
"""
if page >= len(self._pagesInfoVec):
return True # Seems strange, but this is the default
return self._pagesInfoVec[page].GetEnabled() | [
"def",
"GetEnabled",
"(",
"self",
",",
"page",
")",
":",
"if",
"page",
">=",
"len",
"(",
"self",
".",
"_pagesInfoVec",
")",
":",
"return",
"True",
"# Seems strange, but this is the default",
"return",
"self",
".",
"_pagesInfoVec",
"[",
"page",
"]",
".",
"GetEnabled",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L6246-L6256 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/pylib/valgrind_tools.py | python | CreateTool | (tool_name, device) | Creates a tool with the specified tool name.
Args:
tool_name: Name of the tool to create.
device: A DeviceUtils instance.
Returns:
A tool for the specified tool_name. | Creates a tool with the specified tool name. | [
"Creates",
"a",
"tool",
"with",
"the",
"specified",
"tool",
"name",
"."
] | def CreateTool(tool_name, device):
"""Creates a tool with the specified tool name.
Args:
tool_name: Name of the tool to create.
device: A DeviceUtils instance.
Returns:
A tool for the specified tool_name.
"""
if not tool_name:
return base_tool.BaseTool()
ctor = TOOL_REGISTRY.get(tool_name)
if ctor:
return ctor(device)
else:
print 'Unknown tool %s, available tools: %s' % (
tool_name, ', '.join(sorted(TOOL_REGISTRY.keys())))
sys.exit(1) | [
"def",
"CreateTool",
"(",
"tool_name",
",",
"device",
")",
":",
"if",
"not",
"tool_name",
":",
"return",
"base_tool",
".",
"BaseTool",
"(",
")",
"ctor",
"=",
"TOOL_REGISTRY",
".",
"get",
"(",
"tool_name",
")",
"if",
"ctor",
":",
"return",
"ctor",
"(",
"device",
")",
"else",
":",
"print",
"'Unknown tool %s, available tools: %s'",
"%",
"(",
"tool_name",
",",
"', '",
".",
"join",
"(",
"sorted",
"(",
"TOOL_REGISTRY",
".",
"keys",
"(",
")",
")",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/valgrind_tools.py#L198-L216 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/ColorbarPlugin.py | python | ColorbarPlugin.onSetupWindow | (self, window) | Store the RenderWindow for adding and removing the colorbar | Store the RenderWindow for adding and removing the colorbar | [
"Store",
"the",
"RenderWindow",
"for",
"adding",
"and",
"removing",
"the",
"colorbar"
] | def onSetupWindow(self, window):
"""
Store the RenderWindow for adding and removing the colorbar
"""
self._window = window
self.updateColorbarOptions() | [
"def",
"onSetupWindow",
"(",
"self",
",",
"window",
")",
":",
"self",
".",
"_window",
"=",
"window",
"self",
".",
"updateColorbarOptions",
"(",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ColorbarPlugin.py#L143-L148 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/meta/__init__.py | python | test | (stream=sys.stdout, descriptions=True, verbosity=2, failfast=False, buffer=False) | Load and run the meta test suite. | Load and run the meta test suite. | [
"Load",
"and",
"run",
"the",
"meta",
"test",
"suite",
"."
] | def test(stream=sys.stdout, descriptions=True, verbosity=2, failfast=False, buffer=False):
'''
Load and run the meta test suite.
'''
import unittest as _unit
import os as _os
star_dir = _os.path.dirname(__file__)
test_suite = _unit.defaultTestLoader.discover(star_dir)
runner = _unit.TextTestRunner(stream, descriptions, verbosity, failfast, buffer)
runner.run(test_suite) | [
"def",
"test",
"(",
"stream",
"=",
"sys",
".",
"stdout",
",",
"descriptions",
"=",
"True",
",",
"verbosity",
"=",
"2",
",",
"failfast",
"=",
"False",
",",
"buffer",
"=",
"False",
")",
":",
"import",
"unittest",
"as",
"_unit",
"import",
"os",
"as",
"_os",
"star_dir",
"=",
"_os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"test_suite",
"=",
"_unit",
".",
"defaultTestLoader",
".",
"discover",
"(",
"star_dir",
")",
"runner",
"=",
"_unit",
".",
"TextTestRunner",
"(",
"stream",
",",
"descriptions",
",",
"verbosity",
",",
"failfast",
",",
"buffer",
")",
"runner",
".",
"run",
"(",
"test_suite",
")"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/meta/__init__.py#L17-L26 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozbuild/util.py | python | StrictOrderingOnAppendListWithFlagsFactory | (flags) | return StrictOrderingOnAppendListWithFlags | Returns a StrictOrderingOnAppendList-like object, with optional
flags on each item.
The flags are defined in the dict given as argument, where keys are
the flag names, and values the type used for the value of that flag.
Example:
FooList = StrictOrderingOnAppendListWithFlagsFactory({
'foo': bool, 'bar': unicode
})
foo = FooList(['a', 'b', 'c'])
foo['a'].foo = True
foo['b'].bar = 'bar' | Returns a StrictOrderingOnAppendList-like object, with optional
flags on each item. | [
"Returns",
"a",
"StrictOrderingOnAppendList",
"-",
"like",
"object",
"with",
"optional",
"flags",
"on",
"each",
"item",
"."
] | def StrictOrderingOnAppendListWithFlagsFactory(flags):
"""Returns a StrictOrderingOnAppendList-like object, with optional
flags on each item.
The flags are defined in the dict given as argument, where keys are
the flag names, and values the type used for the value of that flag.
Example:
FooList = StrictOrderingOnAppendListWithFlagsFactory({
'foo': bool, 'bar': unicode
})
foo = FooList(['a', 'b', 'c'])
foo['a'].foo = True
foo['b'].bar = 'bar'
"""
class StrictOrderingOnAppendListWithFlags(StrictOrderingOnAppendList):
def __init__(self, iterable=[]):
StrictOrderingOnAppendList.__init__(self, iterable)
self._flags_type = FlagsFactory(flags)
self._flags = dict()
def __getitem__(self, name):
if name not in self._flags:
if name not in self:
raise KeyError("'%s'" % name)
self._flags[name] = self._flags_type()
return self._flags[name]
def __setitem__(self, name, value):
raise TypeError("'%s' object does not support item assignment" %
self.__class__.__name__)
return StrictOrderingOnAppendListWithFlags | [
"def",
"StrictOrderingOnAppendListWithFlagsFactory",
"(",
"flags",
")",
":",
"class",
"StrictOrderingOnAppendListWithFlags",
"(",
"StrictOrderingOnAppendList",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"iterable",
"=",
"[",
"]",
")",
":",
"StrictOrderingOnAppendList",
".",
"__init__",
"(",
"self",
",",
"iterable",
")",
"self",
".",
"_flags_type",
"=",
"FlagsFactory",
"(",
"flags",
")",
"self",
".",
"_flags",
"=",
"dict",
"(",
")",
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_flags",
":",
"if",
"name",
"not",
"in",
"self",
":",
"raise",
"KeyError",
"(",
"\"'%s'\"",
"%",
"name",
")",
"self",
".",
"_flags",
"[",
"name",
"]",
"=",
"self",
".",
"_flags_type",
"(",
")",
"return",
"self",
".",
"_flags",
"[",
"name",
"]",
"def",
"__setitem__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' object does not support item assignment\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"return",
"StrictOrderingOnAppendListWithFlags"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/util.py#L406-L438 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/base/distributed_strategy.py | python | DistributedStrategy.sharding_configs | (self) | return get_msg_dict(self.strategy.sharding_configs) | Set sharding configurations.
**Note**:
sharding_segment_strategy(string, optional): strategy used to segment the program(forward & backward operations). two strategise are
available: "segment_broadcast_MB" and "segment_anchors". segment is a concept used in sharding to overlap computation and
communication. Default is segment_broadcast_MB.
segment_broadcast_MB(float, optional): segment by the parameters broadcast volume. sharding will introduce parameter broadcast operations into program, and
after every segment_broadcast_MB size parameter being broadcasted, the program will be cutted into one segment.
This configuration will affect the communication speed in sharding training, and should be an empirical value decided by your model size and network topology.
Only enable when sharding_segment_strategy = segment_broadcast_MB. Default is 32.0 .
segment_anchors(list): list of anchors used to segment the program, which allows a finner control of program segmentation.
this strategy is experimental by now. Only enable when sharding_segment_strategy = segment_anchors.
sharding_degree(int, optional): specific the number of gpus within each sharding parallelism group; and sharding will be turn off if sharding_degree=1. Default is 8.
gradient_merge_acc_step(int, optional): specific the accumulation steps in gradient merge; and gradient merge will be turn off if gradient_merge_acc_step=1. Default is 1.
optimize_offload(bool, optional): enable the optimizer offload which will offload the moment vars to Host memory in order to saving GPU memory for fitting larger model.
the moment var will be prefetch from and offloaded to Host memory during update stage. it is a stragtegy that trades off between training speed and GPU memory, and is recommened to be turn on only when gradient_merge_acc_step large, where
the number of time of update stage will be relatively small compared with forward&backward's. Default is False.
dp_degree(int, optional): specific the number of data parallelism group; when dp_degree >= 2, it will introduce dp_degree ways data parallelism as the outer parallelsim for the inner parallelsim. User is responsible to ensure global_world_size = mp_degree * sharding_degree * pp_degree * dp_degree. Default is 1.
mp_degree(int, optional): [Hybrid parallelism ONLY] specific the the number of gpus within each megatron parallelism group; and megatron parallelism will turn be off if mp_degree=1. Default is 1.
pp_degree(int, optional): [Hybrid parallelism ONLY] specific the the number of gpus within each pipeline parallelism group; and pipeline parallelism will turn be off if pp_degree=1. Default is 1.
pp_allreduce_in_optimize(bool, optional): [Hybrid parallelism ONLY] move the allreduce operations from backward stage to update(optimize) stage when pipeline parallelsim is on.
This configuration will affect the communication speed of Hybrid parallelism training depeneded on network topology. this strategy is experimental by now.. Default is False.
optimize_cast(bool, optional): [Hybrid parallelism ONLY] Move the cast op of AMP which cast fp32 param to fp16 param to optimizer. optimize_cast will persist fp16 param, it
will take more memory, but will be faster, trade space for time. Recommend to turn on only when using pipeline or gradient_merge_acc_step large.
Examples:
.. code-block:: python
# sharding-DP, 2 nodes with 8 gpus per node
import paddle.distributed.fleet as fleet
strategy = fleet.DistributedStrategy()
strategy.sharding = True
strategy.sharding_configs = {
"sharding_segment_strategy": "segment_broadcast_MB",
"segment_broadcast_MB": 32,
"sharding_degree": 8,
"dp_degree": 2,
"gradient_merge_acc_step": 4,
} | Set sharding configurations. | [
"Set",
"sharding",
"configurations",
"."
] | def sharding_configs(self):
"""
Set sharding configurations.
**Note**:
sharding_segment_strategy(string, optional): strategy used to segment the program(forward & backward operations). two strategise are
available: "segment_broadcast_MB" and "segment_anchors". segment is a concept used in sharding to overlap computation and
communication. Default is segment_broadcast_MB.
segment_broadcast_MB(float, optional): segment by the parameters broadcast volume. sharding will introduce parameter broadcast operations into program, and
after every segment_broadcast_MB size parameter being broadcasted, the program will be cutted into one segment.
This configuration will affect the communication speed in sharding training, and should be an empirical value decided by your model size and network topology.
Only enable when sharding_segment_strategy = segment_broadcast_MB. Default is 32.0 .
segment_anchors(list): list of anchors used to segment the program, which allows a finner control of program segmentation.
this strategy is experimental by now. Only enable when sharding_segment_strategy = segment_anchors.
sharding_degree(int, optional): specific the number of gpus within each sharding parallelism group; and sharding will be turn off if sharding_degree=1. Default is 8.
gradient_merge_acc_step(int, optional): specific the accumulation steps in gradient merge; and gradient merge will be turn off if gradient_merge_acc_step=1. Default is 1.
optimize_offload(bool, optional): enable the optimizer offload which will offload the moment vars to Host memory in order to saving GPU memory for fitting larger model.
the moment var will be prefetch from and offloaded to Host memory during update stage. it is a stragtegy that trades off between training speed and GPU memory, and is recommened to be turn on only when gradient_merge_acc_step large, where
the number of time of update stage will be relatively small compared with forward&backward's. Default is False.
dp_degree(int, optional): specific the number of data parallelism group; when dp_degree >= 2, it will introduce dp_degree ways data parallelism as the outer parallelsim for the inner parallelsim. User is responsible to ensure global_world_size = mp_degree * sharding_degree * pp_degree * dp_degree. Default is 1.
mp_degree(int, optional): [Hybrid parallelism ONLY] specific the the number of gpus within each megatron parallelism group; and megatron parallelism will turn be off if mp_degree=1. Default is 1.
pp_degree(int, optional): [Hybrid parallelism ONLY] specific the the number of gpus within each pipeline parallelism group; and pipeline parallelism will turn be off if pp_degree=1. Default is 1.
pp_allreduce_in_optimize(bool, optional): [Hybrid parallelism ONLY] move the allreduce operations from backward stage to update(optimize) stage when pipeline parallelsim is on.
This configuration will affect the communication speed of Hybrid parallelism training depeneded on network topology. this strategy is experimental by now.. Default is False.
optimize_cast(bool, optional): [Hybrid parallelism ONLY] Move the cast op of AMP which cast fp32 param to fp16 param to optimizer. optimize_cast will persist fp16 param, it
will take more memory, but will be faster, trade space for time. Recommend to turn on only when using pipeline or gradient_merge_acc_step large.
Examples:
.. code-block:: python
# sharding-DP, 2 nodes with 8 gpus per node
import paddle.distributed.fleet as fleet
strategy = fleet.DistributedStrategy()
strategy.sharding = True
strategy.sharding_configs = {
"sharding_segment_strategy": "segment_broadcast_MB",
"segment_broadcast_MB": 32,
"sharding_degree": 8,
"dp_degree": 2,
"gradient_merge_acc_step": 4,
}
"""
return get_msg_dict(self.strategy.sharding_configs) | [
"def",
"sharding_configs",
"(",
"self",
")",
":",
"return",
"get_msg_dict",
"(",
"self",
".",
"strategy",
".",
"sharding_configs",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/base/distributed_strategy.py#L973-L1027 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/utils/data_utils.py | python | get_index | (uid, i) | return _SHARED_SEQUENCES[uid][i] | Get the value from the Sequence `uid` at index `i`.
To allow multiple Sequences to be used at the same time, we use `uid` to
get a specific one. A single Sequence would cause the validation to
overwrite the training Sequence.
Args:
uid: int, Sequence identifier
i: index
Returns:
The value at index `i`. | Get the value from the Sequence `uid` at index `i`. | [
"Get",
"the",
"value",
"from",
"the",
"Sequence",
"uid",
"at",
"index",
"i",
"."
] | def get_index(uid, i):
"""Get the value from the Sequence `uid` at index `i`.
To allow multiple Sequences to be used at the same time, we use `uid` to
get a specific one. A single Sequence would cause the validation to
overwrite the training Sequence.
Args:
uid: int, Sequence identifier
i: index
Returns:
The value at index `i`.
"""
return _SHARED_SEQUENCES[uid][i] | [
"def",
"get_index",
"(",
"uid",
",",
"i",
")",
":",
"return",
"_SHARED_SEQUENCES",
"[",
"uid",
"]",
"[",
"i",
"]"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/data_utils.py#L534-L548 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | Function.InitFunction | (self) | Creates command args and calls the init function for the type handler.
Creates argument lists for command buffer commands, eg. self.cmd_args and
self.init_args.
Calls the type function initialization.
Override to create different kind of command buffer command argument lists. | Creates command args and calls the init function for the type handler. | [
"Creates",
"command",
"args",
"and",
"calls",
"the",
"init",
"function",
"for",
"the",
"type",
"handler",
"."
] | def InitFunction(self):
"""Creates command args and calls the init function for the type handler.
Creates argument lists for command buffer commands, eg. self.cmd_args and
self.init_args.
Calls the type function initialization.
Override to create different kind of command buffer command argument lists.
"""
self.cmd_args = []
for arg in self.args_for_cmds:
arg.AddCmdArgs(self.cmd_args)
self.init_args = []
for arg in self.args_for_cmds:
arg.AddInitArgs(self.init_args)
if self.return_arg:
self.init_args.append(self.return_arg)
self.type_handler.InitFunction(self) | [
"def",
"InitFunction",
"(",
"self",
")",
":",
"self",
".",
"cmd_args",
"=",
"[",
"]",
"for",
"arg",
"in",
"self",
".",
"args_for_cmds",
":",
"arg",
".",
"AddCmdArgs",
"(",
"self",
".",
"cmd_args",
")",
"self",
".",
"init_args",
"=",
"[",
"]",
"for",
"arg",
"in",
"self",
".",
"args_for_cmds",
":",
"arg",
".",
"AddInitArgs",
"(",
"self",
".",
"init_args",
")",
"if",
"self",
".",
"return_arg",
":",
"self",
".",
"init_args",
".",
"append",
"(",
"self",
".",
"return_arg",
")",
"self",
".",
"type_handler",
".",
"InitFunction",
"(",
"self",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9277-L9296 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/pickletools.py | python | read_unicodestringnl | (f) | return unicode(data, 'raw-unicode-escape') | r"""
>>> import StringIO
>>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
u'abc\uabcd' | r"""
>>> import StringIO
>>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
u'abc\uabcd' | [
"r",
">>>",
"import",
"StringIO",
">>>",
"read_unicodestringnl",
"(",
"StringIO",
".",
"StringIO",
"(",
"abc",
"\\",
"uabcd",
"\\",
"njunk",
"))",
"u",
"abc",
"\\",
"uabcd"
] | def read_unicodestringnl(f):
r"""
>>> import StringIO
>>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
u'abc\uabcd'
"""
data = f.readline()
if not data.endswith('\n'):
raise ValueError("no newline found when trying to read "
"unicodestringnl")
data = data[:-1] # lose the newline
return unicode(data, 'raw-unicode-escape') | [
"def",
"read_unicodestringnl",
"(",
"f",
")",
":",
"data",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"data",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"raise",
"ValueError",
"(",
"\"no newline found when trying to read \"",
"\"unicodestringnl\"",
")",
"data",
"=",
"data",
"[",
":",
"-",
"1",
"]",
"# lose the newline",
"return",
"unicode",
"(",
"data",
",",
"'raw-unicode-escape'",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pickletools.py#L420-L432 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | MaskedArray._get_imaginary | (self) | Get the imaginary part of a complex array. | Get the imaginary part of a complex array. | [
"Get",
"the",
"imaginary",
"part",
"of",
"a",
"complex",
"array",
"."
] | def _get_imaginary(self):
"Get the imaginary part of a complex array."
if self._mask is nomask:
return masked_array(self._data.imag, mask=nomask,
fill_value = self.fill_value())
else:
return masked_array(self._data.imag, mask=self._mask,
fill_value = self.fill_value()) | [
"def",
"_get_imaginary",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mask",
"is",
"nomask",
":",
"return",
"masked_array",
"(",
"self",
".",
"_data",
".",
"imag",
",",
"mask",
"=",
"nomask",
",",
"fill_value",
"=",
"self",
".",
"fill_value",
"(",
")",
")",
"else",
":",
"return",
"masked_array",
"(",
"self",
".",
"_data",
".",
"imag",
",",
"mask",
"=",
"self",
".",
"_mask",
",",
"fill_value",
"=",
"self",
".",
"fill_value",
"(",
")",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L702-L709 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/osr.py | python | SpatialReference.IsSameVertCS | (self, *args) | return _osr.SpatialReference_IsSameVertCS(self, *args) | r"""IsSameVertCS(SpatialReference self, SpatialReference rhs) -> int | r"""IsSameVertCS(SpatialReference self, SpatialReference rhs) -> int | [
"r",
"IsSameVertCS",
"(",
"SpatialReference",
"self",
"SpatialReference",
"rhs",
")",
"-",
">",
"int"
] | def IsSameVertCS(self, *args):
r"""IsSameVertCS(SpatialReference self, SpatialReference rhs) -> int"""
return _osr.SpatialReference_IsSameVertCS(self, *args) | [
"def",
"IsSameVertCS",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_osr",
".",
"SpatialReference_IsSameVertCS",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/osr.py#L342-L344 | |
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/compiler-rt/lib/asan/scripts/asan_symbolize.py | python | DarwinSymbolizer.symbolize | (self, addr, binary, offset) | Overrides Symbolizer.symbolize. | Overrides Symbolizer.symbolize. | [
"Overrides",
"Symbolizer",
".",
"symbolize",
"."
] | def symbolize(self, addr, binary, offset):
"""Overrides Symbolizer.symbolize."""
if self.binary != binary:
return None
if not os.path.exists(binary):
# If the binary doesn't exist atos will exit which will lead to IOError
# exceptions being raised later on so just don't try to symbolize.
return ['{} ({}:{}+{})'.format(addr, binary, self.arch, offset)]
atos_line = self.atos.convert('0x%x' % int(offset, 16))
while "got symbolicator for" in atos_line:
atos_line = self.atos.readline()
# A well-formed atos response looks like this:
# foo(type1, type2) (in object.name) (filename.cc:80)
# NOTE:
# * For C functions atos omits parentheses and argument types.
# * For C++ functions the function name (i.e., `foo` above) may contain
# templates which may contain parentheses.
match = re.match('^(.*) \(in (.*)\) \((.*:\d*)\)$', atos_line)
logging.debug('atos_line: %s', atos_line)
if match:
function_name = match.group(1)
file_name = fix_filename(match.group(3))
return ['%s in %s %s' % (addr, function_name, file_name)]
else:
return ['%s in %s' % (addr, atos_line)] | [
"def",
"symbolize",
"(",
"self",
",",
"addr",
",",
"binary",
",",
"offset",
")",
":",
"if",
"self",
".",
"binary",
"!=",
"binary",
":",
"return",
"None",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"binary",
")",
":",
"# If the binary doesn't exist atos will exit which will lead to IOError",
"# exceptions being raised later on so just don't try to symbolize.",
"return",
"[",
"'{} ({}:{}+{})'",
".",
"format",
"(",
"addr",
",",
"binary",
",",
"self",
".",
"arch",
",",
"offset",
")",
"]",
"atos_line",
"=",
"self",
".",
"atos",
".",
"convert",
"(",
"'0x%x'",
"%",
"int",
"(",
"offset",
",",
"16",
")",
")",
"while",
"\"got symbolicator for\"",
"in",
"atos_line",
":",
"atos_line",
"=",
"self",
".",
"atos",
".",
"readline",
"(",
")",
"# A well-formed atos response looks like this:",
"# foo(type1, type2) (in object.name) (filename.cc:80)",
"# NOTE:",
"# * For C functions atos omits parentheses and argument types.",
"# * For C++ functions the function name (i.e., `foo` above) may contain",
"# templates which may contain parentheses.",
"match",
"=",
"re",
".",
"match",
"(",
"'^(.*) \\(in (.*)\\) \\((.*:\\d*)\\)$'",
",",
"atos_line",
")",
"logging",
".",
"debug",
"(",
"'atos_line: %s'",
",",
"atos_line",
")",
"if",
"match",
":",
"function_name",
"=",
"match",
".",
"group",
"(",
"1",
")",
"file_name",
"=",
"fix_filename",
"(",
"match",
".",
"group",
"(",
"3",
")",
")",
"return",
"[",
"'%s in %s %s'",
"%",
"(",
"addr",
",",
"function_name",
",",
"file_name",
")",
"]",
"else",
":",
"return",
"[",
"'%s in %s'",
"%",
"(",
"addr",
",",
"atos_line",
")",
"]"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/asan/scripts/asan_symbolize.py#L265-L289 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathToolBitLibraryGui.py | python | ToolBitSelector.selectedOrAllTools | (self) | return tools | Iterate the selection and add individual tools
If a group is selected, iterate and add children | Iterate the selection and add individual tools
If a group is selected, iterate and add children | [
"Iterate",
"the",
"selection",
"and",
"add",
"individual",
"tools",
"If",
"a",
"group",
"is",
"selected",
"iterate",
"and",
"add",
"children"
] | def selectedOrAllTools(self):
"""
Iterate the selection and add individual tools
If a group is selected, iterate and add children
"""
itemsToProcess = []
for index in self.form.tools.selectedIndexes():
item = index.model().itemFromIndex(index)
if item.hasChildren():
for i in range(item.rowCount() - 1):
if item.child(i).column() == 0:
itemsToProcess.append(item.child(i))
elif item.column() == 0:
itemsToProcess.append(item)
tools = []
for item in itemsToProcess:
toolNr = int(item.data(PySide.QtCore.Qt.EditRole))
toolPath = item.data(_PathRole)
tools.append((toolNr, PathToolBit.Factory.CreateFrom(toolPath)))
return tools | [
"def",
"selectedOrAllTools",
"(",
"self",
")",
":",
"itemsToProcess",
"=",
"[",
"]",
"for",
"index",
"in",
"self",
".",
"form",
".",
"tools",
".",
"selectedIndexes",
"(",
")",
":",
"item",
"=",
"index",
".",
"model",
"(",
")",
".",
"itemFromIndex",
"(",
"index",
")",
"if",
"item",
".",
"hasChildren",
"(",
")",
":",
"for",
"i",
"in",
"range",
"(",
"item",
".",
"rowCount",
"(",
")",
"-",
"1",
")",
":",
"if",
"item",
".",
"child",
"(",
"i",
")",
".",
"column",
"(",
")",
"==",
"0",
":",
"itemsToProcess",
".",
"append",
"(",
"item",
".",
"child",
"(",
"i",
")",
")",
"elif",
"item",
".",
"column",
"(",
")",
"==",
"0",
":",
"itemsToProcess",
".",
"append",
"(",
"item",
")",
"tools",
"=",
"[",
"]",
"for",
"item",
"in",
"itemsToProcess",
":",
"toolNr",
"=",
"int",
"(",
"item",
".",
"data",
"(",
"PySide",
".",
"QtCore",
".",
"Qt",
".",
"EditRole",
")",
")",
"toolPath",
"=",
"item",
".",
"data",
"(",
"_PathRole",
")",
"tools",
".",
"append",
"(",
"(",
"toolNr",
",",
"PathToolBit",
".",
"Factory",
".",
"CreateFrom",
"(",
"toolPath",
")",
")",
")",
"return",
"tools"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathToolBitLibraryGui.py#L413-L436 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | GLGenerator.WriteGLES2ToPPAPIBridge | (self, filename) | Connects GLES2 helper library to PPB_OpenGLES2 interface | Connects GLES2 helper library to PPB_OpenGLES2 interface | [
"Connects",
"GLES2",
"helper",
"library",
"to",
"PPB_OpenGLES2",
"interface"
] | def WriteGLES2ToPPAPIBridge(self, filename):
"""Connects GLES2 helper library to PPB_OpenGLES2 interface"""
with CWriter(filename) as f:
f.write("#ifndef GL_GLEXT_PROTOTYPES\n")
f.write("#define GL_GLEXT_PROTOTYPES\n")
f.write("#endif\n")
f.write("#include <GLES2/gl2.h>\n")
f.write("#include <GLES2/gl2ext.h>\n")
f.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
for func in self.original_functions:
if not func.InAnyPepperExtension():
continue
interface = self.interface_info[func.GetInfo('pepper_interface') or '']
f.write("%s GL_APIENTRY gl%s(%s) {\n" %
(func.return_type, func.GetPepperName(),
func.MakeTypedPepperArgString("")))
return_str = "" if func.return_type == "void" else "return "
interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
original_arg = func.MakeOriginalArgString("")
context_arg = "glGetCurrentContextPPAPI()"
if len(original_arg):
arg = context_arg + ", " + original_arg
else:
arg = context_arg
if interface.GetName():
f.write(" const struct %s* ext = %s;\n" %
(interface.GetStructName(), interface_str))
f.write(" if (ext)\n")
f.write(" %sext->%s(%s);\n" %
(return_str, func.GetPepperName(), arg))
if return_str:
f.write(" %s0;\n" % return_str)
else:
f.write(" %s%s->%s(%s);\n" %
(return_str, interface_str, func.GetPepperName(), arg))
f.write("}\n\n")
self.generated_cpp_filenames.append(filename) | [
"def",
"WriteGLES2ToPPAPIBridge",
"(",
"self",
",",
"filename",
")",
":",
"with",
"CWriter",
"(",
"filename",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"#ifndef GL_GLEXT_PROTOTYPES\\n\"",
")",
"f",
".",
"write",
"(",
"\"#define GL_GLEXT_PROTOTYPES\\n\"",
")",
"f",
".",
"write",
"(",
"\"#endif\\n\"",
")",
"f",
".",
"write",
"(",
"\"#include <GLES2/gl2.h>\\n\"",
")",
"f",
".",
"write",
"(",
"\"#include <GLES2/gl2ext.h>\\n\"",
")",
"f",
".",
"write",
"(",
"\"#include \\\"ppapi/lib/gl/gles2/gl2ext_ppapi.h\\\"\\n\\n\"",
")",
"for",
"func",
"in",
"self",
".",
"original_functions",
":",
"if",
"not",
"func",
".",
"InAnyPepperExtension",
"(",
")",
":",
"continue",
"interface",
"=",
"self",
".",
"interface_info",
"[",
"func",
".",
"GetInfo",
"(",
"'pepper_interface'",
")",
"or",
"''",
"]",
"f",
".",
"write",
"(",
"\"%s GL_APIENTRY gl%s(%s) {\\n\"",
"%",
"(",
"func",
".",
"return_type",
",",
"func",
".",
"GetPepperName",
"(",
")",
",",
"func",
".",
"MakeTypedPepperArgString",
"(",
"\"\"",
")",
")",
")",
"return_str",
"=",
"\"\"",
"if",
"func",
".",
"return_type",
"==",
"\"void\"",
"else",
"\"return \"",
"interface_str",
"=",
"\"glGet%sInterfacePPAPI()\"",
"%",
"interface",
".",
"GetName",
"(",
")",
"original_arg",
"=",
"func",
".",
"MakeOriginalArgString",
"(",
"\"\"",
")",
"context_arg",
"=",
"\"glGetCurrentContextPPAPI()\"",
"if",
"len",
"(",
"original_arg",
")",
":",
"arg",
"=",
"context_arg",
"+",
"\", \"",
"+",
"original_arg",
"else",
":",
"arg",
"=",
"context_arg",
"if",
"interface",
".",
"GetName",
"(",
")",
":",
"f",
".",
"write",
"(",
"\" const struct %s* ext = %s;\\n\"",
"%",
"(",
"interface",
".",
"GetStructName",
"(",
")",
",",
"interface_str",
")",
")",
"f",
".",
"write",
"(",
"\" if (ext)\\n\"",
")",
"f",
".",
"write",
"(",
"\" %sext->%s(%s);\\n\"",
"%",
"(",
"return_str",
",",
"func",
".",
"GetPepperName",
"(",
")",
",",
"arg",
")",
")",
"if",
"return_str",
":",
"f",
".",
"write",
"(",
"\" %s0;\\n\"",
"%",
"return_str",
")",
"else",
":",
"f",
".",
"write",
"(",
"\" %s%s->%s(%s);\\n\"",
"%",
"(",
"return_str",
",",
"interface_str",
",",
"func",
".",
"GetPepperName",
"(",
")",
",",
"arg",
")",
")",
"f",
".",
"write",
"(",
"\"}\\n\\n\"",
")",
"self",
".",
"generated_cpp_filenames",
".",
"append",
"(",
"filename",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L11073-L11112 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/utils.py | python | _get_indent | (lines) | return indent | Determines the leading whitespace that could be removed from all the lines. | Determines the leading whitespace that could be removed from all the lines. | [
"Determines",
"the",
"leading",
"whitespace",
"that",
"could",
"be",
"removed",
"from",
"all",
"the",
"lines",
"."
] | def _get_indent(lines):
"""
Determines the leading whitespace that could be removed from all the lines.
"""
indent = sys.maxsize
for line in lines:
content = len(line.lstrip())
if content:
indent = min(indent, len(line) - content)
if indent == sys.maxsize:
indent = 0
return indent | [
"def",
"_get_indent",
"(",
"lines",
")",
":",
"indent",
"=",
"sys",
".",
"maxsize",
"for",
"line",
"in",
"lines",
":",
"content",
"=",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"if",
"content",
":",
"indent",
"=",
"min",
"(",
"indent",
",",
"len",
"(",
"line",
")",
"-",
"content",
")",
"if",
"indent",
"==",
"sys",
".",
"maxsize",
":",
"indent",
"=",
"0",
"return",
"indent"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/utils.py#L130-L141 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | SLHCUpgradeSimulations/Configuration/python/muonCustoms.py | python | digitizer_timing_pre3_median | (process) | return process | CSC digitizer customization
with bunchTimingOffsets tuned to center trigger stubs at bx6
when pretrigger with 3 layers and median stub timing are used | CSC digitizer customization
with bunchTimingOffsets tuned to center trigger stubs at bx6
when pretrigger with 3 layers and median stub timing are used | [
"CSC",
"digitizer",
"customization",
"with",
"bunchTimingOffsets",
"tuned",
"to",
"center",
"trigger",
"stubs",
"at",
"bx6",
"when",
"pretrigger",
"with",
"3",
"layers",
"and",
"median",
"stub",
"timing",
"are",
"used"
] | def digitizer_timing_pre3_median(process):
"""CSC digitizer customization
with bunchTimingOffsets tuned to center trigger stubs at bx6
when pretrigger with 3 layers and median stub timing are used
"""
## Make sure there's no bad chambers/channels
#process.simMuonCSCDigis.strips.readBadChambers = True
#process.simMuonCSCDigis.wires.readBadChannels = True
#process.simMuonCSCDigis.digitizeBadChambers = True
## Customised timing offsets so that ALCTs and CLCTs times are centered in signal BX.
## These offsets below were tuned for the case of 3 layer pretriggering
## and median stub timing algorithm.
process.simMuonCSCDigis.strips.bunchTimingOffsets = cms.vdouble(0.0,
37.53, 37.66, 55.4, 48.2, 54.45, 53.78, 53.38, 54.12, 51.98, 51.28)
process.simMuonCSCDigis.wires.bunchTimingOffsets = cms.vdouble(0.0,
22.88, 22.55, 29.28, 30.0, 30.0, 30.5, 31.0, 29.5, 29.1, 29.88)
return process | [
"def",
"digitizer_timing_pre3_median",
"(",
"process",
")",
":",
"## Make sure there's no bad chambers/channels",
"#process.simMuonCSCDigis.strips.readBadChambers = True",
"#process.simMuonCSCDigis.wires.readBadChannels = True",
"#process.simMuonCSCDigis.digitizeBadChambers = True",
"## Customised timing offsets so that ALCTs and CLCTs times are centered in signal BX. ",
"## These offsets below were tuned for the case of 3 layer pretriggering ",
"## and median stub timing algorithm.",
"process",
".",
"simMuonCSCDigis",
".",
"strips",
".",
"bunchTimingOffsets",
"=",
"cms",
".",
"vdouble",
"(",
"0.0",
",",
"37.53",
",",
"37.66",
",",
"55.4",
",",
"48.2",
",",
"54.45",
",",
"53.78",
",",
"53.38",
",",
"54.12",
",",
"51.98",
",",
"51.28",
")",
"process",
".",
"simMuonCSCDigis",
".",
"wires",
".",
"bunchTimingOffsets",
"=",
"cms",
".",
"vdouble",
"(",
"0.0",
",",
"22.88",
",",
"22.55",
",",
"29.28",
",",
"30.0",
",",
"30.0",
",",
"30.5",
",",
"31.0",
",",
"29.5",
",",
"29.1",
",",
"29.88",
")",
"return",
"process"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/SLHCUpgradeSimulations/Configuration/python/muonCustoms.py#L15-L33 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.walk_preorder | (self) | Depth-first preorder walk over the cursor and its descendants.
Yields cursors. | Depth-first preorder walk over the cursor and its descendants. | [
"Depth",
"-",
"first",
"preorder",
"walk",
"over",
"the",
"cursor",
"and",
"its",
"descendants",
"."
] | def walk_preorder(self):
"""Depth-first preorder walk over the cursor and its descendants.
Yields cursors.
"""
yield self
for child in self.get_children():
for descendant in child.walk_preorder():
yield descendant | [
"def",
"walk_preorder",
"(",
"self",
")",
":",
"yield",
"self",
"for",
"child",
"in",
"self",
".",
"get_children",
"(",
")",
":",
"for",
"descendant",
"in",
"child",
".",
"walk_preorder",
"(",
")",
":",
"yield",
"descendant"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1821-L1829 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/write_build_config.py | python | _ResolveGroups | (config_paths) | Returns a list of configs with all groups inlined. | Returns a list of configs with all groups inlined. | [
"Returns",
"a",
"list",
"of",
"configs",
"with",
"all",
"groups",
"inlined",
"."
] | def _ResolveGroups(config_paths):
"""Returns a list of configs with all groups inlined."""
ret = list(config_paths)
ret_set = set(config_paths)
while True:
group_paths = DepPathsOfType('group', ret)
if not group_paths:
return ret
for group_path in group_paths:
index = ret.index(group_path)
expanded_config_paths = []
for deps_config_path in GetDepConfig(group_path)['deps_configs']:
if not deps_config_path in ret_set:
expanded_config_paths.append(deps_config_path)
ret[index:index + 1] = expanded_config_paths
ret_set.update(expanded_config_paths) | [
"def",
"_ResolveGroups",
"(",
"config_paths",
")",
":",
"ret",
"=",
"list",
"(",
"config_paths",
")",
"ret_set",
"=",
"set",
"(",
"config_paths",
")",
"while",
"True",
":",
"group_paths",
"=",
"DepPathsOfType",
"(",
"'group'",
",",
"ret",
")",
"if",
"not",
"group_paths",
":",
"return",
"ret",
"for",
"group_path",
"in",
"group_paths",
":",
"index",
"=",
"ret",
".",
"index",
"(",
"group_path",
")",
"expanded_config_paths",
"=",
"[",
"]",
"for",
"deps_config_path",
"in",
"GetDepConfig",
"(",
"group_path",
")",
"[",
"'deps_configs'",
"]",
":",
"if",
"not",
"deps_config_path",
"in",
"ret_set",
":",
"expanded_config_paths",
".",
"append",
"(",
"deps_config_path",
")",
"ret",
"[",
"index",
":",
"index",
"+",
"1",
"]",
"=",
"expanded_config_paths",
"ret_set",
".",
"update",
"(",
"expanded_config_paths",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/write_build_config.py#L802-L817 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | ListEvent.SetEditCanceled | (*args, **kwargs) | return _controls_.ListEvent_SetEditCanceled(*args, **kwargs) | SetEditCanceled(self, bool editCancelled) | SetEditCanceled(self, bool editCancelled) | [
"SetEditCanceled",
"(",
"self",
"bool",
"editCancelled",
")"
] | def SetEditCanceled(*args, **kwargs):
"""SetEditCanceled(self, bool editCancelled)"""
return _controls_.ListEvent_SetEditCanceled(*args, **kwargs) | [
"def",
"SetEditCanceled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListEvent_SetEditCanceled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4362-L4364 | |
0vercl0k/rp | 5fe693c26d76b514efaedb4084f6e37d820db023 | src/third_party/fmt/support/docopt.py | python | Pattern.fix_repeating_arguments | (self) | return self | Fix elements that should accumulate/increment values. | Fix elements that should accumulate/increment values. | [
"Fix",
"elements",
"that",
"should",
"accumulate",
"/",
"increment",
"values",
"."
] | def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self | [
"def",
"fix_repeating_arguments",
"(",
"self",
")",
":",
"either",
"=",
"[",
"list",
"(",
"child",
".",
"children",
")",
"for",
"child",
"in",
"transform",
"(",
"self",
")",
".",
"children",
"]",
"for",
"case",
"in",
"either",
":",
"for",
"e",
"in",
"[",
"child",
"for",
"child",
"in",
"case",
"if",
"case",
".",
"count",
"(",
"child",
")",
">",
"1",
"]",
":",
"if",
"type",
"(",
"e",
")",
"is",
"Argument",
"or",
"type",
"(",
"e",
")",
"is",
"Option",
"and",
"e",
".",
"argcount",
":",
"if",
"e",
".",
"value",
"is",
"None",
":",
"e",
".",
"value",
"=",
"[",
"]",
"elif",
"type",
"(",
"e",
".",
"value",
")",
"is",
"not",
"list",
":",
"e",
".",
"value",
"=",
"e",
".",
"value",
".",
"split",
"(",
")",
"if",
"type",
"(",
"e",
")",
"is",
"Command",
"or",
"type",
"(",
"e",
")",
"is",
"Option",
"and",
"e",
".",
"argcount",
"==",
"0",
":",
"e",
".",
"value",
"=",
"0",
"return",
"self"
] | https://github.com/0vercl0k/rp/blob/5fe693c26d76b514efaedb4084f6e37d820db023/src/third_party/fmt/support/docopt.py#L57-L69 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/tools/grokdump.py | python | InspectionShell.do_disassemble | (self, args) | Unassemble memory in the region [address, address + size). If the
size is not specified, a default value of 32 bytes is used.
Synopsis: u 0x<address> 0x<size> | Unassemble memory in the region [address, address + size). If the
size is not specified, a default value of 32 bytes is used.
Synopsis: u 0x<address> 0x<size> | [
"Unassemble",
"memory",
"in",
"the",
"region",
"[",
"address",
"address",
"+",
"size",
")",
".",
"If",
"the",
"size",
"is",
"not",
"specified",
"a",
"default",
"value",
"of",
"32",
"bytes",
"is",
"used",
".",
"Synopsis",
":",
"u",
"0x<address",
">",
"0x<size",
">"
] | def do_disassemble(self, args):
"""
Unassemble memory in the region [address, address + size). If the
size is not specified, a default value of 32 bytes is used.
Synopsis: u 0x<address> 0x<size>
"""
if len(args) != 0:
args = args.split(' ')
self.u_start = self.ParseAddressExpr(args[0])
self.u_size = self.ParseAddressExpr(args[1]) if len(args) > 1 else 0x20
skip = False
else:
# Skip the first instruction if we reuse the last address.
skip = True
if not self.reader.IsValidAddress(self.u_start):
print "Address %s is not contained within the minidump!" % (
self.reader.FormatIntPtr(self.u_start))
return
lines = self.reader.GetDisasmLines(self.u_start, self.u_size)
for line in lines:
if skip:
skip = False
continue
print FormatDisasmLine(self.u_start, self.heap, line)
# Set the next start address = last line
self.u_start += lines[-1][0]
print | [
"def",
"do_disassemble",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"0",
":",
"args",
"=",
"args",
".",
"split",
"(",
"' '",
")",
"self",
".",
"u_start",
"=",
"self",
".",
"ParseAddressExpr",
"(",
"args",
"[",
"0",
"]",
")",
"self",
".",
"u_size",
"=",
"self",
".",
"ParseAddressExpr",
"(",
"args",
"[",
"1",
"]",
")",
"if",
"len",
"(",
"args",
")",
">",
"1",
"else",
"0x20",
"skip",
"=",
"False",
"else",
":",
"# Skip the first instruction if we reuse the last address.",
"skip",
"=",
"True",
"if",
"not",
"self",
".",
"reader",
".",
"IsValidAddress",
"(",
"self",
".",
"u_start",
")",
":",
"print",
"\"Address %s is not contained within the minidump!\"",
"%",
"(",
"self",
".",
"reader",
".",
"FormatIntPtr",
"(",
"self",
".",
"u_start",
")",
")",
"return",
"lines",
"=",
"self",
".",
"reader",
".",
"GetDisasmLines",
"(",
"self",
".",
"u_start",
",",
"self",
".",
"u_size",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"skip",
":",
"skip",
"=",
"False",
"continue",
"print",
"FormatDisasmLine",
"(",
"self",
".",
"u_start",
",",
"self",
".",
"heap",
",",
"line",
")",
"# Set the next start address = last line",
"self",
".",
"u_start",
"+=",
"lines",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"print"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/tools/grokdump.py#L3573-L3600 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/layers/base.py | python | Layer.add_loss | (self, losses, inputs=None) | Add loss tensor(s), potentially dependent on layer inputs.
Some losses (for instance, activity regularization losses) may be dependent
on the inputs passed when calling a layer. Hence, when reusing a same layer
on different inputs `a` and `b`, some entries in `layer.losses` may be
dependent on `a` and some on `b`. This method automatically keeps track
of dependencies.
The `get_losses_for` method allows to retrieve the losses relevant to a
specific set of inputs.
Arguments:
losses: Loss tensor, or list/tuple of tensors.
inputs: Optional input tensor(s) that the loss(es) depend on. Must
match the `inputs` argument passed to the `__call__` method at the time
the losses are created. If `None` is passed, the losses are assumed
to be unconditional, and will apply across all dataflows of the layer
(e.g. weight regularization losses).
Raises:
RuntimeError: If called in Eager mode. | Add loss tensor(s), potentially dependent on layer inputs. | [
"Add",
"loss",
"tensor",
"(",
"s",
")",
"potentially",
"dependent",
"on",
"layer",
"inputs",
"."
] | def add_loss(self, losses, inputs=None):
"""Add loss tensor(s), potentially dependent on layer inputs.
Some losses (for instance, activity regularization losses) may be dependent
on the inputs passed when calling a layer. Hence, when reusing a same layer
on different inputs `a` and `b`, some entries in `layer.losses` may be
dependent on `a` and some on `b`. This method automatically keeps track
of dependencies.
The `get_losses_for` method allows to retrieve the losses relevant to a
specific set of inputs.
Arguments:
losses: Loss tensor, or list/tuple of tensors.
inputs: Optional input tensor(s) that the loss(es) depend on. Must
match the `inputs` argument passed to the `__call__` method at the time
the losses are created. If `None` is passed, the losses are assumed
to be unconditional, and will apply across all dataflows of the layer
(e.g. weight regularization losses).
Raises:
RuntimeError: If called in Eager mode.
"""
if context.in_eager_mode():
raise RuntimeError('Layer.add_loss not supported in Eager mode.')
losses = _to_list(losses)
if not losses:
return
self._losses += losses
if inputs is not None:
inputs = nest.flatten(inputs)
if not inputs:
inputs = None
if inputs is not None:
# We compute an ID that uniquely identifies the list of tensors.
# This ID is order-sensitive.
inputs_hash = _object_list_uid(inputs)
else:
inputs_hash = None
if inputs_hash not in self._per_input_losses:
self._per_input_losses[inputs_hash] = []
self._per_input_losses[inputs_hash] += losses
_add_elements_to_collection(losses, ops.GraphKeys.REGULARIZATION_LOSSES) | [
"def",
"add_loss",
"(",
"self",
",",
"losses",
",",
"inputs",
"=",
"None",
")",
":",
"if",
"context",
".",
"in_eager_mode",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Layer.add_loss not supported in Eager mode.'",
")",
"losses",
"=",
"_to_list",
"(",
"losses",
")",
"if",
"not",
"losses",
":",
"return",
"self",
".",
"_losses",
"+=",
"losses",
"if",
"inputs",
"is",
"not",
"None",
":",
"inputs",
"=",
"nest",
".",
"flatten",
"(",
"inputs",
")",
"if",
"not",
"inputs",
":",
"inputs",
"=",
"None",
"if",
"inputs",
"is",
"not",
"None",
":",
"# We compute an ID that uniquely identifies the list of tensors.",
"# This ID is order-sensitive.",
"inputs_hash",
"=",
"_object_list_uid",
"(",
"inputs",
")",
"else",
":",
"inputs_hash",
"=",
"None",
"if",
"inputs_hash",
"not",
"in",
"self",
".",
"_per_input_losses",
":",
"self",
".",
"_per_input_losses",
"[",
"inputs_hash",
"]",
"=",
"[",
"]",
"self",
".",
"_per_input_losses",
"[",
"inputs_hash",
"]",
"+=",
"losses",
"_add_elements_to_collection",
"(",
"losses",
",",
"ops",
".",
"GraphKeys",
".",
"REGULARIZATION_LOSSES",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/layers/base.py#L291-L333 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/pipes.py | python | Template.open | (self, file, rw) | t.open(file, rw) returns a pipe or file object open for
reading or writing; the file is the other end of the pipeline. | t.open(file, rw) returns a pipe or file object open for
reading or writing; the file is the other end of the pipeline. | [
"t",
".",
"open",
"(",
"file",
"rw",
")",
"returns",
"a",
"pipe",
"or",
"file",
"object",
"open",
"for",
"reading",
"or",
"writing",
";",
"the",
"file",
"is",
"the",
"other",
"end",
"of",
"the",
"pipeline",
"."
] | def open(self, file, rw):
"""t.open(file, rw) returns a pipe or file object open for
reading or writing; the file is the other end of the pipeline."""
if rw == 'r':
return self.open_r(file)
if rw == 'w':
return self.open_w(file)
raise ValueError('Template.open: rw must be \'r\' or \'w\', not %r'
% (rw,)) | [
"def",
"open",
"(",
"self",
",",
"file",
",",
"rw",
")",
":",
"if",
"rw",
"==",
"'r'",
":",
"return",
"self",
".",
"open_r",
"(",
"file",
")",
"if",
"rw",
"==",
"'w'",
":",
"return",
"self",
".",
"open_w",
"(",
"file",
")",
"raise",
"ValueError",
"(",
"'Template.open: rw must be \\'r\\' or \\'w\\', not %r'",
"%",
"(",
"rw",
",",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pipes.py#L142-L150 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/neighbors/_base.py | python | _check_weights | (weights) | Check to make sure weights are valid | Check to make sure weights are valid | [
"Check",
"to",
"make",
"sure",
"weights",
"are",
"valid"
] | def _check_weights(weights):
"""Check to make sure weights are valid"""
if weights in (None, 'uniform', 'distance'):
return weights
elif callable(weights):
return weights
else:
raise ValueError("weights not recognized: should be 'uniform', "
"'distance', or a callable function") | [
"def",
"_check_weights",
"(",
"weights",
")",
":",
"if",
"weights",
"in",
"(",
"None",
",",
"'uniform'",
",",
"'distance'",
")",
":",
"return",
"weights",
"elif",
"callable",
"(",
"weights",
")",
":",
"return",
"weights",
"else",
":",
"raise",
"ValueError",
"(",
"\"weights not recognized: should be 'uniform', \"",
"\"'distance', or a callable function\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/neighbors/_base.py#L53-L61 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/customtreectrl.py | python | CustomTreeCtrl.Unselect | (self) | Unselects the current selection. | Unselects the current selection. | [
"Unselects",
"the",
"current",
"selection",
"."
] | def Unselect(self):
""" Unselects the current selection. """
if self._current:
self._current.SetHilight(False)
self.RefreshLine(self._current)
self._current = None
self._select_me = None | [
"def",
"Unselect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current",
":",
"self",
".",
"_current",
".",
"SetHilight",
"(",
"False",
")",
"self",
".",
"RefreshLine",
"(",
"self",
".",
"_current",
")",
"self",
".",
"_current",
"=",
"None",
"self",
".",
"_select_me",
"=",
"None"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L5499-L5507 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py | python | WinTool._GetEnv | (self, arch) | return dict(kvs) | Gets the saved environment from a file for a given architecture. | Gets the saved environment from a file for a given architecture. | [
"Gets",
"the",
"saved",
"environment",
"from",
"a",
"file",
"for",
"a",
"given",
"architecture",
"."
] | def _GetEnv(self, arch):
"""Gets the saved environment from a file for a given architecture."""
# The environment is saved as an "environment block" (see CreateProcess
# and msvs_emulation for details). We convert to a dict here.
# Drop last 2 NULs, one for list terminator, one for trailing vs. separator.
pairs = open(arch).read()[:-2].split('\0')
kvs = [item.split('=', 1) for item in pairs]
return dict(kvs) | [
"def",
"_GetEnv",
"(",
"self",
",",
"arch",
")",
":",
"# The environment is saved as an \"environment block\" (see CreateProcess",
"# and msvs_emulation for details). We convert to a dict here.",
"# Drop last 2 NULs, one for list terminator, one for trailing vs. separator.",
"pairs",
"=",
"open",
"(",
"arch",
")",
".",
"read",
"(",
")",
"[",
":",
"-",
"2",
"]",
".",
"split",
"(",
"'\\0'",
")",
"kvs",
"=",
"[",
"item",
".",
"split",
"(",
"'='",
",",
"1",
")",
"for",
"item",
"in",
"pairs",
"]",
"return",
"dict",
"(",
"kvs",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py#L76-L83 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/build/targets.py | python | ProjectTarget.add_constant | (self, name, value, path=0) | Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project. | Adds a new constant for this project. | [
"Adds",
"a",
"new",
"constant",
"for",
"this",
"project",
"."
] | def add_constant(self, name, value, path=0):
"""Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project.
"""
if path:
l = self.location_
if not l:
# Project corresponding to config files do not have
# 'location' attribute, but do have source location.
# It might be more reasonable to make every project have
# a location and use some other approach to prevent buildable
# targets in config files, but that's for later.
l = get('source-location')
value = os.path.join(l, value)
# Now make the value absolute path
value = os.path.join(os.getcwd(), value)
self.constants_[name] = value
bjam.call("set-variable", self.project_module(), name, value) | [
"def",
"add_constant",
"(",
"self",
",",
"name",
",",
"value",
",",
"path",
"=",
"0",
")",
":",
"if",
"path",
":",
"l",
"=",
"self",
".",
"location_",
"if",
"not",
"l",
":",
"# Project corresponding to config files do not have ",
"# 'location' attribute, but do have source location.",
"# It might be more reasonable to make every project have",
"# a location and use some other approach to prevent buildable",
"# targets in config files, but that's for later.",
"l",
"=",
"get",
"(",
"'source-location'",
")",
"value",
"=",
"os",
".",
"path",
".",
"join",
"(",
"l",
",",
"value",
")",
"# Now make the value absolute path",
"value",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"value",
")",
"self",
".",
"constants_",
"[",
"name",
"]",
"=",
"value",
"bjam",
".",
"call",
"(",
"\"set-variable\"",
",",
"self",
".",
"project_module",
"(",
")",
",",
"name",
",",
"value",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/targets.py#L571-L595 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/common/htmlutil.py | python | ScriptExtractor.handle_data | (self, data) | Internal handler for character data.
Args:
data: The character data from the HTML file. | Internal handler for character data. | [
"Internal",
"handler",
"for",
"character",
"data",
"."
] | def handle_data(self, data):
"""Internal handler for character data.
Args:
data: The character data from the HTML file.
"""
if self._in_script:
# If the last line contains whitespace only, i.e. is just there to
# properly align a </script> tag, strip the whitespace.
if data.rstrip(' \t') != data.rstrip(' \t\n\r\f'):
data = data.rstrip(' \t')
self._text += data
else:
self._AppendNewlines(data) | [
"def",
"handle_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_in_script",
":",
"# If the last line contains whitespace only, i.e. is just there to",
"# properly align a </script> tag, strip the whitespace.",
"if",
"data",
".",
"rstrip",
"(",
"' \\t'",
")",
"!=",
"data",
".",
"rstrip",
"(",
"' \\t\\n\\r\\f'",
")",
":",
"data",
"=",
"data",
".",
"rstrip",
"(",
"' \\t'",
")",
"self",
".",
"_text",
"+=",
"data",
"else",
":",
"self",
".",
"_AppendNewlines",
"(",
"data",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/common/htmlutil.py#L57-L70 | ||
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py | python | get_gpio_bylabel | (label) | return p.extra_value('GPIO', type=int, default=-1) | get GPIO(n) setting on a pin label, or -1 | get GPIO(n) setting on a pin label, or -1 | [
"get",
"GPIO",
"(",
"n",
")",
"setting",
"on",
"a",
"pin",
"label",
"or",
"-",
"1"
] | def get_gpio_bylabel(label):
'''get GPIO(n) setting on a pin label, or -1'''
p = bylabel.get(label)
if p is None:
return -1
return p.extra_value('GPIO', type=int, default=-1) | [
"def",
"get_gpio_bylabel",
"(",
"label",
")",
":",
"p",
"=",
"bylabel",
".",
"get",
"(",
"label",
")",
"if",
"p",
"is",
"None",
":",
"return",
"-",
"1",
"return",
"p",
".",
"extra_value",
"(",
"'GPIO'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"-",
"1",
")"
] | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py#L1502-L1507 | |
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/io/dm.py | python | FileDM.__del__ | (self) | Destructor which also closes the file | Destructor which also closes the file | [
"Destructor",
"which",
"also",
"closes",
"the",
"file"
] | def __del__(self):
"""Destructor which also closes the file
"""
if not self.fid.closed:
if self._v:
print('Closing input file: {}'.format(self.filename))
self.fid.close() | [
"def",
"__del__",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"fid",
".",
"closed",
":",
"if",
"self",
".",
"_v",
":",
"print",
"(",
"'Closing input file: {}'",
".",
"format",
"(",
"self",
".",
"filename",
")",
")",
"self",
".",
"fid",
".",
"close",
"(",
")"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/io/dm.py#L232-L239 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | PreSashWindow | (*args, **kwargs) | return val | PreSashWindow() -> SashWindow | PreSashWindow() -> SashWindow | [
"PreSashWindow",
"()",
"-",
">",
"SashWindow"
] | def PreSashWindow(*args, **kwargs):
"""PreSashWindow() -> SashWindow"""
val = _windows_.new_PreSashWindow(*args, **kwargs)
return val | [
"def",
"PreSashWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_windows_",
".",
"new_PreSashWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1888-L1891 | |
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | cpp/gdb_arrow.py | python | ScalarPrinter.type | (self) | return cast_to_concrete(deref(self.val['type']),
concrete_type) | The concrete DataTypeClass instance. | The concrete DataTypeClass instance. | [
"The",
"concrete",
"DataTypeClass",
"instance",
"."
] | def type(self):
"""
The concrete DataTypeClass instance.
"""
concrete_type = gdb.lookup_type(f"arrow::{self.type_name}")
return cast_to_concrete(deref(self.val['type']),
concrete_type) | [
"def",
"type",
"(",
"self",
")",
":",
"concrete_type",
"=",
"gdb",
".",
"lookup_type",
"(",
"f\"arrow::{self.type_name}\"",
")",
"return",
"cast_to_concrete",
"(",
"deref",
"(",
"self",
".",
"val",
"[",
"'type'",
"]",
")",
",",
"concrete_type",
")"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/cpp/gdb_arrow.py#L1240-L1246 | |
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | python/caffe/coord_map.py | python | crop_params | (fn) | return (axis, offset) | Extract the crop layer parameters with defaults. | Extract the crop layer parameters with defaults. | [
"Extract",
"the",
"crop",
"layer",
"parameters",
"with",
"defaults",
"."
] | def crop_params(fn):
"""
Extract the crop layer parameters with defaults.
"""
params = fn.params.get('crop_param', fn.params)
axis = params.get('axis', 2) # default to spatial crop for N, C, H, W
offset = np.array(params.get('offset', 0), ndmin=1)
return (axis, offset) | [
"def",
"crop_params",
"(",
"fn",
")",
":",
"params",
"=",
"fn",
".",
"params",
".",
"get",
"(",
"'crop_param'",
",",
"fn",
".",
"params",
")",
"axis",
"=",
"params",
".",
"get",
"(",
"'axis'",
",",
"2",
")",
"# default to spatial crop for N, C, H, W",
"offset",
"=",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'offset'",
",",
"0",
")",
",",
"ndmin",
"=",
"1",
")",
"return",
"(",
"axis",
",",
"offset",
")"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/python/caffe/coord_map.py#L40-L47 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/numbers.py | python | Real.__complex__ | (self) | return complex(float(self)) | complex(self) == complex(float(self), 0) | complex(self) == complex(float(self), 0) | [
"complex",
"(",
"self",
")",
"==",
"complex",
"(",
"float",
"(",
"self",
")",
"0",
")"
] | def __complex__(self):
"""complex(self) == complex(float(self), 0)"""
return complex(float(self)) | [
"def",
"__complex__",
"(",
"self",
")",
":",
"return",
"complex",
"(",
"float",
"(",
"self",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/numbers.py#L246-L248 | |
gnina/gnina | b9ae032f52fc7a8153987bde09c0efa3620d8bb6 | caffe/python/caffe/io.py | python | load_image | (filename, color=True) | return img | Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale. | Load an image converting from grayscale or alpha as needed. | [
"Load",
"an",
"image",
"converting",
"from",
"grayscale",
"or",
"alpha",
"as",
"needed",
"."
] | def load_image(filename, color=True):
"""
Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
"""
img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
if color:
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img | [
"def",
"load_image",
"(",
"filename",
",",
"color",
"=",
"True",
")",
":",
"img",
"=",
"skimage",
".",
"img_as_float",
"(",
"skimage",
".",
"io",
".",
"imread",
"(",
"filename",
",",
"as_grey",
"=",
"not",
"color",
")",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"if",
"img",
".",
"ndim",
"==",
"2",
":",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
"np",
".",
"newaxis",
"]",
"if",
"color",
":",
"img",
"=",
"np",
".",
"tile",
"(",
"img",
",",
"(",
"1",
",",
"1",
",",
"3",
")",
")",
"elif",
"img",
".",
"shape",
"[",
"2",
"]",
"==",
"4",
":",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"return",
"img"
] | https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/python/caffe/io.py#L294-L318 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBExpressionOptions.GetAutoApplyFixIts | (self) | return _lldb.SBExpressionOptions_GetAutoApplyFixIts(self) | GetAutoApplyFixIts(SBExpressionOptions self) -> bool
Gets whether to auto-apply fix-it hints to an expression. | GetAutoApplyFixIts(SBExpressionOptions self) -> bool | [
"GetAutoApplyFixIts",
"(",
"SBExpressionOptions",
"self",
")",
"-",
">",
"bool"
] | def GetAutoApplyFixIts(self):
"""
GetAutoApplyFixIts(SBExpressionOptions self) -> bool
Gets whether to auto-apply fix-it hints to an expression.
"""
return _lldb.SBExpressionOptions_GetAutoApplyFixIts(self) | [
"def",
"GetAutoApplyFixIts",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBExpressionOptions_GetAutoApplyFixIts",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L5140-L5146 | |
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/chull.py | python | Hull.AddOne | (self,p) | return True | AddOne is passed a vertex. It first determines all faces visible from
that point. If none are visible then the point is marked as not
onhull. Next is a loop over edges. If both faces adjacent to an edge
are visible, then the edge is marked for deletion. If just one of the
adjacent faces is visible then a new face is constructed. | AddOne is passed a vertex. It first determines all faces visible from
that point. If none are visible then the point is marked as not
onhull. Next is a loop over edges. If both faces adjacent to an edge
are visible, then the edge is marked for deletion. If just one of the
adjacent faces is visible then a new face is constructed. | [
"AddOne",
"is",
"passed",
"a",
"vertex",
".",
"It",
"first",
"determines",
"all",
"faces",
"visible",
"from",
"that",
"point",
".",
"If",
"none",
"are",
"visible",
"then",
"the",
"point",
"is",
"marked",
"as",
"not",
"onhull",
".",
"Next",
"is",
"a",
"loop",
"over",
"edges",
".",
"If",
"both",
"faces",
"adjacent",
"to",
"an",
"edge",
"are",
"visible",
"then",
"the",
"edge",
"is",
"marked",
"for",
"deletion",
".",
"If",
"just",
"one",
"of",
"the",
"adjacent",
"faces",
"is",
"visible",
"then",
"a",
"new",
"face",
"is",
"constructed",
"."
] | def AddOne(self,p):
"""
AddOne is passed a vertex. It first determines all faces visible from
that point. If none are visible then the point is marked as not
onhull. Next is a loop over edges. If both faces adjacent to an edge
are visible, then the edge is marked for deletion. If just one of the
adjacent faces is visible then a new face is constructed.
"""
vis = False;
# Mark faces visible from p.
for f in self.faces:
vol = Hull.VolumeSign( f, p )
if vol < 0 : f.visible = VISIBLE
vis = True;
# If no faces are visible from p, then p is inside the hull
if not vis:
p.onhull = not ONHULL
return False
# Mark edges in interior of visible region for deletion.
# Erect a newface based on each border edge
for e in self.edges:
if e.adjface[0].visible and e.adjface[1].visible:
# e interior: mark for deletion
e.delete = REMOVED;
elif e.adjface[0].visible or e.adjface[1].visible:
# e border: make a new face
e.newface = self.MakeConeFace( e, p )
if ddebug : print(self.debug('addone'))
return True | [
"def",
"AddOne",
"(",
"self",
",",
"p",
")",
":",
"vis",
"=",
"False",
"# Mark faces visible from p.",
"for",
"f",
"in",
"self",
".",
"faces",
":",
"vol",
"=",
"Hull",
".",
"VolumeSign",
"(",
"f",
",",
"p",
")",
"if",
"vol",
"<",
"0",
":",
"f",
".",
"visible",
"=",
"VISIBLE",
"vis",
"=",
"True",
"# If no faces are visible from p, then p is inside the hull",
"if",
"not",
"vis",
":",
"p",
".",
"onhull",
"=",
"not",
"ONHULL",
"return",
"False",
"# Mark edges in interior of visible region for deletion.",
"# Erect a newface based on each border edge",
"for",
"e",
"in",
"self",
".",
"edges",
":",
"if",
"e",
".",
"adjface",
"[",
"0",
"]",
".",
"visible",
"and",
"e",
".",
"adjface",
"[",
"1",
"]",
".",
"visible",
":",
"# e interior: mark for deletion",
"e",
".",
"delete",
"=",
"REMOVED",
"elif",
"e",
".",
"adjface",
"[",
"0",
"]",
".",
"visible",
"or",
"e",
".",
"adjface",
"[",
"1",
"]",
".",
"visible",
":",
"# e border: make a new face",
"e",
".",
"newface",
"=",
"self",
".",
"MakeConeFace",
"(",
"e",
",",
"p",
")",
"if",
"ddebug",
":",
"print",
"(",
"self",
".",
"debug",
"(",
"'addone'",
")",
")",
"return",
"True"
] | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/chull.py#L322-L356 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_4_0_2.py | python | MiroInterpreter.do_mythtv_import_opml | (self, filename) | Import an OPML file | Import an OPML file | [
"Import",
"an",
"OPML",
"file"
] | def do_mythtv_import_opml(self, filename):
"""Import an OPML file"""
try:
messages.ImportFeeds(filename).send_to_backend()
logging.info(u"Import of OPML file (%s) sent to Miro" % (filename))
except Exception, e:
logging.info(u"Import of OPML file (%s) failed, error (%s)" % (filename, e)) | [
"def",
"do_mythtv_import_opml",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"messages",
".",
"ImportFeeds",
"(",
"filename",
")",
".",
"send_to_backend",
"(",
")",
"logging",
".",
"info",
"(",
"u\"Import of OPML file (%s) sent to Miro\"",
"%",
"(",
"filename",
")",
")",
"except",
"Exception",
",",
"e",
":",
"logging",
".",
"info",
"(",
"u\"Import of OPML file (%s) failed, error (%s)\"",
"%",
"(",
"filename",
",",
"e",
")",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_4_0_2.py#L233-L239 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/netrc.py | python | netrc.authenticators | (self, host) | Return a (user, account, password) tuple for given host. | Return a (user, account, password) tuple for given host. | [
"Return",
"a",
"(",
"user",
"account",
"password",
")",
"tuple",
"for",
"given",
"host",
"."
] | def authenticators(self, host):
"""Return a (user, account, password) tuple for given host."""
if host in self.hosts:
return self.hosts[host]
elif 'default' in self.hosts:
return self.hosts['default']
else:
return None | [
"def",
"authenticators",
"(",
"self",
",",
"host",
")",
":",
"if",
"host",
"in",
"self",
".",
"hosts",
":",
"return",
"self",
".",
"hosts",
"[",
"host",
"]",
"elif",
"'default'",
"in",
"self",
".",
"hosts",
":",
"return",
"self",
".",
"hosts",
"[",
"'default'",
"]",
"else",
":",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/netrc.py#L113-L120 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/socketserver.py | python | BaseServer.process_request | (self, request, client_address) | Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn. | Call finish_request. | [
"Call",
"finish_request",
"."
] | def process_request(self, request, client_address):
"""Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn.
"""
self.finish_request(request, client_address)
self.shutdown_request(request) | [
"def",
"process_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"self",
".",
"finish_request",
"(",
"request",
",",
"client_address",
")",
"self",
".",
"shutdown_request",
"(",
"request",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/socketserver.py#L341-L348 | ||
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/__init__.py | python | Range.__init__ | (self, inf, sup = True) | Create a numeric range with the given boundaries
inf -- the inferior boundary.
sup -- the superior boundary. If unspecified, equals the
inferior boundary. If None, there is no upper bound
to the range (it includes any number superior or
equal to inf).
>>> 4 in Range(5)
False
>>> 5 in Range(5)
True
>>> 6 in Range(5)
False
>>> 4 in Range(5, 7)
False
>>> 5 in Range(5, 7)
True
>>> 6 in Range(5, 7)
True
>>> 7 in Range(5, 7)
True
>>> 8 in Range(5, 7)
False
>>> 42 in Range(5, None)
True | Create a numeric range with the given boundaries | [
"Create",
"a",
"numeric",
"range",
"with",
"the",
"given",
"boundaries"
] | def __init__(self, inf, sup = True):
"""Create a numeric range with the given boundaries
inf -- the inferior boundary.
sup -- the superior boundary. If unspecified, equals the
inferior boundary. If None, there is no upper bound
to the range (it includes any number superior or
equal to inf).
>>> 4 in Range(5)
False
>>> 5 in Range(5)
True
>>> 6 in Range(5)
False
>>> 4 in Range(5, 7)
False
>>> 5 in Range(5, 7)
True
>>> 6 in Range(5, 7)
True
>>> 7 in Range(5, 7)
True
>>> 8 in Range(5, 7)
False
>>> 42 in Range(5, None)
True
"""
if isinstance(inf, Range):
assert sup is True
sup = inf.sup()
inf = inf.inf()
assert inf is not None
self.__inf = inf
if sup is True:
sup = inf
self.__sup = sup | [
"def",
"__init__",
"(",
"self",
",",
"inf",
",",
"sup",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"inf",
",",
"Range",
")",
":",
"assert",
"sup",
"is",
"True",
"sup",
"=",
"inf",
".",
"sup",
"(",
")",
"inf",
"=",
"inf",
".",
"inf",
"(",
")",
"assert",
"inf",
"is",
"not",
"None",
"self",
".",
"__inf",
"=",
"inf",
"if",
"sup",
"is",
"True",
":",
"sup",
"=",
"inf",
"self",
".",
"__sup",
"=",
"sup"
] | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L3699-L3736 | ||
hszhao/PSPNet | cf7e5a99ba37e46118026e96be5821a9bc63bde0 | scripts/cpp_lint.py | python | _CppLintState.SetFilters | (self, filters) | Sets the 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.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" | Sets the error-message filters. | [
"Sets",
"the",
"error",
"-",
"message",
"filters",
"."
] | def SetFilters(self, filters):
"""Sets the 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.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
self.filters.append(clean_filt)
for filt in self.filters:
if not (filt.startswith('+') or filt.startswith('-')):
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt) | [
"def",
"SetFilters",
"(",
"self",
",",
"filters",
")",
":",
"# Default filters always have less priority than the flag ones.",
"self",
".",
"filters",
"=",
"_DEFAULT_FILTERS",
"[",
":",
"]",
"for",
"filt",
"in",
"filters",
".",
"split",
"(",
"','",
")",
":",
"clean_filt",
"=",
"filt",
".",
"strip",
"(",
")",
"if",
"clean_filt",
":",
"self",
".",
"filters",
".",
"append",
"(",
"clean_filt",
")",
"for",
"filt",
"in",
"self",
".",
"filters",
":",
"if",
"not",
"(",
"filt",
".",
"startswith",
"(",
"'+'",
")",
"or",
"filt",
".",
"startswith",
"(",
"'-'",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Every filter in --filters must start with + or -'",
"' (%s does not)'",
"%",
"filt",
")"
] | https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L717-L740 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | shell/impala_client.py | python | ImpalaClient.get_query_id_str | (self, last_query_handle) | Return the standard string representation of an Impala query ID, e.g.
'd74d8ce632c9d4d0:75c5a51100000000 | Return the standard string representation of an Impala query ID, e.g.
'd74d8ce632c9d4d0:75c5a51100000000 | [
"Return",
"the",
"standard",
"string",
"representation",
"of",
"an",
"Impala",
"query",
"ID",
"e",
".",
"g",
".",
"d74d8ce632c9d4d0",
":",
"75c5a51100000000"
] | def get_query_id_str(self, last_query_handle):
"""Return the standard string representation of an Impala query ID, e.g.
'd74d8ce632c9d4d0:75c5a51100000000'"""
raise NotImplementedError() | [
"def",
"get_query_id_str",
"(",
"self",
",",
"last_query_handle",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/impala_client.py#L244-L247 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStrV.LastLast | (self, *args) | return _snap.TStrV_LastLast(self, *args) | LastLast(TStrV self) -> TStr
LastLast(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > * | LastLast(TStrV self) -> TStr
LastLast(TStrV self) -> TStr | [
"LastLast",
"(",
"TStrV",
"self",
")",
"-",
">",
"TStr",
"LastLast",
"(",
"TStrV",
"self",
")",
"-",
">",
"TStr"
] | def LastLast(self, *args):
"""
LastLast(TStrV self) -> TStr
LastLast(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_LastLast(self, *args) | [
"def",
"LastLast",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStrV_LastLast",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19406-L19415 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/png/png.py | python | Writer.write | (self, outfile, rows) | Write a PNG image to the output file. `rows` should be
an iterable that yields each row in boxed row flat pixel format.
The rows should be the rows of the original image, so there
should be ``self.height`` rows of ``self.width * self.planes`` values.
If `interlace` is specified (when creating the instance), then
an interlaced PNG file will be written. Supply the rows in the
normal image order; the interlacing is carried out internally.
.. note ::
Interlacing will require the entire image to be in working memory. | Write a PNG image to the output file. `rows` should be
an iterable that yields each row in boxed row flat pixel format.
The rows should be the rows of the original image, so there
should be ``self.height`` rows of ``self.width * self.planes`` values.
If `interlace` is specified (when creating the instance), then
an interlaced PNG file will be written. Supply the rows in the
normal image order; the interlacing is carried out internally.
.. note :: | [
"Write",
"a",
"PNG",
"image",
"to",
"the",
"output",
"file",
".",
"rows",
"should",
"be",
"an",
"iterable",
"that",
"yields",
"each",
"row",
"in",
"boxed",
"row",
"flat",
"pixel",
"format",
".",
"The",
"rows",
"should",
"be",
"the",
"rows",
"of",
"the",
"original",
"image",
"so",
"there",
"should",
"be",
"self",
".",
"height",
"rows",
"of",
"self",
".",
"width",
"*",
"self",
".",
"planes",
"values",
".",
"If",
"interlace",
"is",
"specified",
"(",
"when",
"creating",
"the",
"instance",
")",
"then",
"an",
"interlaced",
"PNG",
"file",
"will",
"be",
"written",
".",
"Supply",
"the",
"rows",
"in",
"the",
"normal",
"image",
"order",
";",
"the",
"interlacing",
"is",
"carried",
"out",
"internally",
".",
"..",
"note",
"::"
] | def write(self, outfile, rows):
"""Write a PNG image to the output file. `rows` should be
an iterable that yields each row in boxed row flat pixel format.
The rows should be the rows of the original image, so there
should be ``self.height`` rows of ``self.width * self.planes`` values.
If `interlace` is specified (when creating the instance), then
an interlaced PNG file will be written. Supply the rows in the
normal image order; the interlacing is carried out internally.
.. note ::
Interlacing will require the entire image to be in working memory.
"""
if self.interlace:
fmt = 'BH'[self.bitdepth > 8]
a = array(fmt, itertools.chain(*rows))
return self.write_array(outfile, a)
else:
nrows = self.write_passes(outfile, rows)
if nrows != self.height:
raise ValueError(
"rows supplied (%d) does not match height (%d)" %
(nrows, self.height)) | [
"def",
"write",
"(",
"self",
",",
"outfile",
",",
"rows",
")",
":",
"if",
"self",
".",
"interlace",
":",
"fmt",
"=",
"'BH'",
"[",
"self",
".",
"bitdepth",
">",
"8",
"]",
"a",
"=",
"array",
"(",
"fmt",
",",
"itertools",
".",
"chain",
"(",
"*",
"rows",
")",
")",
"return",
"self",
".",
"write_array",
"(",
"outfile",
",",
"a",
")",
"else",
":",
"nrows",
"=",
"self",
".",
"write_passes",
"(",
"outfile",
",",
"rows",
")",
"if",
"nrows",
"!=",
"self",
".",
"height",
":",
"raise",
"ValueError",
"(",
"\"rows supplied (%d) does not match height (%d)\"",
"%",
"(",
"nrows",
",",
"self",
".",
"height",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/png/png.py#L626-L649 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | PreTreeListCtrl | (*args, **kwargs) | return val | PreTreeListCtrl() -> TreeListCtrl | PreTreeListCtrl() -> TreeListCtrl | [
"PreTreeListCtrl",
"()",
"-",
">",
"TreeListCtrl"
] | def PreTreeListCtrl(*args, **kwargs):
"""PreTreeListCtrl() -> TreeListCtrl"""
val = _gizmos.new_PreTreeListCtrl(*args, **kwargs)
return val | [
"def",
"PreTreeListCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_gizmos",
".",
"new_PreTreeListCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L965-L968 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/distutils/cygwinccompiler.py | python | CygwinCCompiler.object_filenames | (self, source_filenames, strip_dir=0, output_dir='') | return obj_names | Adds supports for rc and res files. | Adds supports for rc and res files. | [
"Adds",
"supports",
"for",
"rc",
"and",
"res",
"files",
"."
] | def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
"""Adds supports for rc and res files."""
if output_dir is None:
output_dir = ''
obj_names = []
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
base, ext = os.path.splitext(os.path.normcase(src_name))
if ext not in (self.src_extensions + ['.rc','.res']):
raise UnknownFileError("unknown file type '%s' (from '%s')" % \
(ext, src_name))
if strip_dir:
base = os.path.basename (base)
if ext in ('.res', '.rc'):
# these need to be compiled to object files
obj_names.append (os.path.join(output_dir,
base + ext + self.obj_extension))
else:
obj_names.append (os.path.join(output_dir,
base + self.obj_extension))
return obj_names | [
"def",
"object_filenames",
"(",
"self",
",",
"source_filenames",
",",
"strip_dir",
"=",
"0",
",",
"output_dir",
"=",
"''",
")",
":",
"if",
"output_dir",
"is",
"None",
":",
"output_dir",
"=",
"''",
"obj_names",
"=",
"[",
"]",
"for",
"src_name",
"in",
"source_filenames",
":",
"# use normcase to make sure '.rc' is really '.rc' and not '.RC'",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"normcase",
"(",
"src_name",
")",
")",
"if",
"ext",
"not",
"in",
"(",
"self",
".",
"src_extensions",
"+",
"[",
"'.rc'",
",",
"'.res'",
"]",
")",
":",
"raise",
"UnknownFileError",
"(",
"\"unknown file type '%s' (from '%s')\"",
"%",
"(",
"ext",
",",
"src_name",
")",
")",
"if",
"strip_dir",
":",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"base",
")",
"if",
"ext",
"in",
"(",
"'.res'",
",",
"'.rc'",
")",
":",
"# these need to be compiled to object files",
"obj_names",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"base",
"+",
"ext",
"+",
"self",
".",
"obj_extension",
")",
")",
"else",
":",
"obj_names",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"base",
"+",
"self",
".",
"obj_extension",
")",
")",
"return",
"obj_names"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/cygwinccompiler.py#L252-L272 | |
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/type.py | python | base | (type) | return __types[type]['base'] | Returns a base type for the given type or nothing in case the given type is
not derived. | Returns a base type for the given type or nothing in case the given type is
not derived. | [
"Returns",
"a",
"base",
"type",
"for",
"the",
"given",
"type",
"or",
"nothing",
"in",
"case",
"the",
"given",
"type",
"is",
"not",
"derived",
"."
] | def base(type):
"""Returns a base type for the given type or nothing in case the given type is
not derived."""
assert isinstance(type, basestring)
return __types[type]['base'] | [
"def",
"base",
"(",
"type",
")",
":",
"assert",
"isinstance",
"(",
"type",
",",
"basestring",
")",
"return",
"__types",
"[",
"type",
"]",
"[",
"'base'",
"]"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/type.py#L175-L179 | |
alibaba/MNN | c4d9566171d589c3ded23aa18ffb197016995a12 | 3rd_party/flatbuffers/conanfile.py | python | FlatbuffersConan.source | (self) | Wrap the original CMake file to call conan_basic_setup | Wrap the original CMake file to call conan_basic_setup | [
"Wrap",
"the",
"original",
"CMake",
"file",
"to",
"call",
"conan_basic_setup"
] | def source(self):
"""Wrap the original CMake file to call conan_basic_setup
"""
shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt")
shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt") | [
"def",
"source",
"(",
"self",
")",
":",
"shutil",
".",
"move",
"(",
"\"CMakeLists.txt\"",
",",
"\"CMakeListsOriginal.txt\"",
")",
"shutil",
".",
"move",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"conan\"",
",",
"\"CMakeLists.txt\"",
")",
",",
"\"CMakeLists.txt\"",
")"
] | https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/3rd_party/flatbuffers/conanfile.py#L26-L30 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/monitors.py | python | BaseMonitor.end | (self, session=None) | Callback at the end of training/evaluation.
Args:
session: A `tf.Session` object that can be used to run ops.
Raises:
ValueError: if we've not begun a run. | Callback at the end of training/evaluation. | [
"Callback",
"at",
"the",
"end",
"of",
"training",
"/",
"evaluation",
"."
] | def end(self, session=None):
"""Callback at the end of training/evaluation.
Args:
session: A `tf.Session` object that can be used to run ops.
Raises:
ValueError: if we've not begun a run.
"""
_ = session
if not self._begun:
raise ValueError("end called without begin.")
self._max_steps = None
self._begun = False | [
"def",
"end",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"_",
"=",
"session",
"if",
"not",
"self",
".",
"_begun",
":",
"raise",
"ValueError",
"(",
"\"end called without begin.\"",
")",
"self",
".",
"_max_steps",
"=",
"None",
"self",
".",
"_begun",
"=",
"False"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/monitors.py#L174-L187 | ||
raspberrypi/tools | 13474ee775d0c5ec8a7da4fb0a9fa84187abfc87 | arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/command/explore.py | python | ArrayExplorer.explore_expr | (expr, value, is_child) | return True | Function to explore array values.
See Explorer.explore_expr for more information. | Function to explore array values.
See Explorer.explore_expr for more information. | [
"Function",
"to",
"explore",
"array",
"values",
".",
"See",
"Explorer",
".",
"explore_expr",
"for",
"more",
"information",
"."
] | def explore_expr(expr, value, is_child):
"""Function to explore array values.
See Explorer.explore_expr for more information.
"""
target_type = value.type.target()
print ("'%s' is an array of '%s'." % (expr, str(target_type)))
index = 0
try:
index = int(raw_input("Enter the index of the element you want to "
"explore in '%s': " % expr))
except ValueError:
if is_child:
Explorer.return_to_parent_value()
return False
element = None
try:
element = value[index]
str(element)
except gdb.MemoryError:
print ("Cannot read value at index %d." % index)
raw_input("Press enter to continue... ")
return True
Explorer.explore_expr("%s[%d]" % (Explorer.guard_expr(expr), index),
element, True)
return True | [
"def",
"explore_expr",
"(",
"expr",
",",
"value",
",",
"is_child",
")",
":",
"target_type",
"=",
"value",
".",
"type",
".",
"target",
"(",
")",
"print",
"(",
"\"'%s' is an array of '%s'.\"",
"%",
"(",
"expr",
",",
"str",
"(",
"target_type",
")",
")",
")",
"index",
"=",
"0",
"try",
":",
"index",
"=",
"int",
"(",
"raw_input",
"(",
"\"Enter the index of the element you want to \"",
"\"explore in '%s': \"",
"%",
"expr",
")",
")",
"except",
"ValueError",
":",
"if",
"is_child",
":",
"Explorer",
".",
"return_to_parent_value",
"(",
")",
"return",
"False",
"element",
"=",
"None",
"try",
":",
"element",
"=",
"value",
"[",
"index",
"]",
"str",
"(",
"element",
")",
"except",
"gdb",
".",
"MemoryError",
":",
"print",
"(",
"\"Cannot read value at index %d.\"",
"%",
"index",
")",
"raw_input",
"(",
"\"Press enter to continue... \"",
")",
"return",
"True",
"Explorer",
".",
"explore_expr",
"(",
"\"%s[%d]\"",
"%",
"(",
"Explorer",
".",
"guard_expr",
"(",
"expr",
")",
",",
"index",
")",
",",
"element",
",",
"True",
")",
"return",
"True"
] | https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/command/explore.py#L326-L352 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | remoting/host/installer/build-installer-archive.py | python | remapSrcFile | (dst_root, src_roots, src_file) | return dst_file | Calculates destination file path and creates directory.
Any matching |src_roots| prefix is stripped from |src_file| before
appending to |dst_root|.
For example, given:
dst_root = '/output'
src_roots = ['host/installer/mac']
src_file = 'host/installer/mac/Scripts/keystone_install.sh'
The final calculated path is:
'/output/Scripts/keystone_install.sh'
The |src_file| must match one of the |src_roots| prefixes. If there are no
matches, then an error is reported.
If multiple |src_roots| match, then only the first match is applied. Because
of this, if you have roots that share a common prefix, the longest string
should be first in this array.
Args:
dst_root: Target directory where files are copied.
src_roots: Array of path prefixes which will be stripped of |src_file|
(if they match) before appending it to the |dst_root|.
src_file: Source file to be copied.
Returns:
Full path to destination file in |dst_root|. | Calculates destination file path and creates directory. | [
"Calculates",
"destination",
"file",
"path",
"and",
"creates",
"directory",
"."
] | def remapSrcFile(dst_root, src_roots, src_file):
"""Calculates destination file path and creates directory.
Any matching |src_roots| prefix is stripped from |src_file| before
appending to |dst_root|.
For example, given:
dst_root = '/output'
src_roots = ['host/installer/mac']
src_file = 'host/installer/mac/Scripts/keystone_install.sh'
The final calculated path is:
'/output/Scripts/keystone_install.sh'
The |src_file| must match one of the |src_roots| prefixes. If there are no
matches, then an error is reported.
If multiple |src_roots| match, then only the first match is applied. Because
of this, if you have roots that share a common prefix, the longest string
should be first in this array.
Args:
dst_root: Target directory where files are copied.
src_roots: Array of path prefixes which will be stripped of |src_file|
(if they match) before appending it to the |dst_root|.
src_file: Source file to be copied.
Returns:
Full path to destination file in |dst_root|.
"""
# Strip of directory prefix.
found_root = False
for root in src_roots:
if src_file.startswith(root):
src_file = src_file[len(root):]
found_root = True
break
if not found_root:
error('Unable to match prefix for %s' % src_file)
dst_file = os.path.join(dst_root, src_file)
# Make sure target directory exists.
dst_dir = os.path.dirname(dst_file)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir, 0775)
return dst_file | [
"def",
"remapSrcFile",
"(",
"dst_root",
",",
"src_roots",
",",
"src_file",
")",
":",
"# Strip of directory prefix.",
"found_root",
"=",
"False",
"for",
"root",
"in",
"src_roots",
":",
"if",
"src_file",
".",
"startswith",
"(",
"root",
")",
":",
"src_file",
"=",
"src_file",
"[",
"len",
"(",
"root",
")",
":",
"]",
"found_root",
"=",
"True",
"break",
"if",
"not",
"found_root",
":",
"error",
"(",
"'Unable to match prefix for %s'",
"%",
"src_file",
")",
"dst_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst_root",
",",
"src_file",
")",
"# Make sure target directory exists.",
"dst_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dst_file",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"dst_dir",
",",
"0775",
")",
"return",
"dst_file"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/remoting/host/installer/build-installer-archive.py#L74-L118 | |
dartsim/dart | 495c82120c836005f2d136d4a50c8cc997fb879b | setup.py | python | CMakeBuild.run | (self) | Build using CMake from the specified build directory. | Build using CMake from the specified build directory. | [
"Build",
"using",
"CMake",
"from",
"the",
"specified",
"build",
"directory",
"."
] | def run(self):
""" Build using CMake from the specified build directory. """
try:
out = subprocess.check_output(['cmake', '--version'])
except OSError:
raise RuntimeError(
"CMake must be installed to build the following extensions: " +
", ".join(e.name for e in self.extensions))
if platform.system() == "Windows":
cmake_version = LooseVersion(
re.search(r'version\s*([\d.]+)', out.decode()).group(1))
if cmake_version < '3.10.2':
raise RuntimeError("CMake >= 3.10.2 is required on Windows")
distutils.log.set_verbosity(distutils.log.DEBUG) # Set DEBUG level
for ext in self.extensions:
self.build_extension(ext) | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'cmake'",
",",
"'--version'",
"]",
")",
"except",
"OSError",
":",
"raise",
"RuntimeError",
"(",
"\"CMake must be installed to build the following extensions: \"",
"+",
"\", \"",
".",
"join",
"(",
"e",
".",
"name",
"for",
"e",
"in",
"self",
".",
"extensions",
")",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Windows\"",
":",
"cmake_version",
"=",
"LooseVersion",
"(",
"re",
".",
"search",
"(",
"r'version\\s*([\\d.]+)'",
",",
"out",
".",
"decode",
"(",
")",
")",
".",
"group",
"(",
"1",
")",
")",
"if",
"cmake_version",
"<",
"'3.10.2'",
":",
"raise",
"RuntimeError",
"(",
"\"CMake >= 3.10.2 is required on Windows\"",
")",
"distutils",
".",
"log",
".",
"set_verbosity",
"(",
"distutils",
".",
"log",
".",
"DEBUG",
")",
"# Set DEBUG level",
"for",
"ext",
"in",
"self",
".",
"extensions",
":",
"self",
".",
"build_extension",
"(",
"ext",
")"
] | https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/setup.py#L35-L53 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/ColorbarPlugin.py | python | ColorbarPlugin._setLimitHelper | (mode, qobject) | return None | Helper for setting min/max to a user defined value. | Helper for setting min/max to a user defined value. | [
"Helper",
"for",
"setting",
"min",
"/",
"max",
"to",
"a",
"user",
"defined",
"value",
"."
] | def _setLimitHelper(mode, qobject):
"""
Helper for setting min/max to a user defined value.
"""
if mode.isChecked():
qobject.setEnabled(True)
qobject.setStyleSheet('color:#000000')
try:
value = float(qobject.text())
return value
except ValueError:
qobject.setStyleSheet('color:#ff0000')
return None | [
"def",
"_setLimitHelper",
"(",
"mode",
",",
"qobject",
")",
":",
"if",
"mode",
".",
"isChecked",
"(",
")",
":",
"qobject",
".",
"setEnabled",
"(",
"True",
")",
"qobject",
".",
"setStyleSheet",
"(",
"'color:#000000'",
")",
"try",
":",
"value",
"=",
"float",
"(",
"qobject",
".",
"text",
"(",
")",
")",
"return",
"value",
"except",
"ValueError",
":",
"qobject",
".",
"setStyleSheet",
"(",
"'color:#ff0000'",
")",
"return",
"None"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ColorbarPlugin.py#L227-L239 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/qre_anneal.py | python | Solver.exploitability | (self, params, payoff_matrices) | return exp.qre_exploitability(params, payoff_matrices, self.temperature) | Compute and return tsallis entropy regularized exploitability.
Args:
params: tuple of params (dist, y), see ate.gradients
payoff_matrices: dictionary with keys as tuples of agents (i, j) and
values of (2 x A x A) np.arrays, payoffs for each joint action. keys
are sorted and arrays should be indexed in the same order
Returns:
float, exploitability of current dist | Compute and return tsallis entropy regularized exploitability. | [
"Compute",
"and",
"return",
"tsallis",
"entropy",
"regularized",
"exploitability",
"."
] | def exploitability(self, params, payoff_matrices):
"""Compute and return tsallis entropy regularized exploitability.
Args:
params: tuple of params (dist, y), see ate.gradients
payoff_matrices: dictionary with keys as tuples of agents (i, j) and
values of (2 x A x A) np.arrays, payoffs for each joint action. keys
are sorted and arrays should be indexed in the same order
Returns:
float, exploitability of current dist
"""
return exp.qre_exploitability(params, payoff_matrices, self.temperature) | [
"def",
"exploitability",
"(",
"self",
",",
"params",
",",
"payoff_matrices",
")",
":",
"return",
"exp",
".",
"qre_exploitability",
"(",
"params",
",",
"payoff_matrices",
",",
"self",
".",
"temperature",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/qre_anneal.py#L101-L112 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/PostprocessorViewer/plugins/FigurePlugin.py | python | FigurePlugin.repr | (self) | return output, imports | Return the matplotlib script for reproducing the figure and axes. | Return the matplotlib script for reproducing the figure and axes. | [
"Return",
"the",
"matplotlib",
"script",
"for",
"reproducing",
"the",
"figure",
"and",
"axes",
"."
] | def repr(self):
"""
Return the matplotlib script for reproducing the figure and axes.
"""
imports = ['import matplotlib.pyplot as plt']
output = []
output += ["# Create Figure and Axes"]
output += ["figure = plt.figure(facecolor='white')"]
output += ['axes0 = figure.add_subplot(111)']
if self._axes2.has_data():
output += ['axes1 = axes0.twinx()']
return output, imports | [
"def",
"repr",
"(",
"self",
")",
":",
"imports",
"=",
"[",
"'import matplotlib.pyplot as plt'",
"]",
"output",
"=",
"[",
"]",
"output",
"+=",
"[",
"\"# Create Figure and Axes\"",
"]",
"output",
"+=",
"[",
"\"figure = plt.figure(facecolor='white')\"",
"]",
"output",
"+=",
"[",
"'axes0 = figure.add_subplot(111)'",
"]",
"if",
"self",
".",
"_axes2",
".",
"has_data",
"(",
")",
":",
"output",
"+=",
"[",
"'axes1 = axes0.twinx()'",
"]",
"return",
"output",
",",
"imports"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/PostprocessorViewer/plugins/FigurePlugin.py#L98-L113 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py | python | PackageIndex.process_index | (self, url, page) | Process the contents of a PyPI page | Process the contents of a PyPI page | [
"Process",
"the",
"contents",
"of",
"a",
"PyPI",
"page"
] | def process_index(self, url, page):
"""Process the contents of a PyPI page"""
def scan(link):
# Process a URL to see if it's for a package page
if link.startswith(self.index_url):
parts = list(map(
urllib.parse.unquote, link[len(self.index_url):].split('/')
))
if len(parts) == 2 and '#' not in parts[1]:
# it's a package page, sanitize and index it
pkg = safe_name(parts[0])
ver = safe_version(parts[1])
self.package_pages.setdefault(pkg.lower(), {})[link] = True
return to_filename(pkg), to_filename(ver)
return None, None
# process an index page into the package-page index
for match in HREF.finditer(page):
try:
scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
except ValueError:
pass
pkg, ver = scan(url) # ensure this page is in the page index
if pkg:
# process individual package page
for new_url in find_external_links(url, page):
# Process the found URL
base, frag = egg_info_for_url(new_url)
if base.endswith('.py') and not frag:
if ver:
new_url += '#egg=%s-%s' % (pkg, ver)
else:
self.need_version_info(url)
self.scan_url(new_url)
return PYPI_MD5.sub(
lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page
)
else:
return "" | [
"def",
"process_index",
"(",
"self",
",",
"url",
",",
"page",
")",
":",
"def",
"scan",
"(",
"link",
")",
":",
"# Process a URL to see if it's for a package page",
"if",
"link",
".",
"startswith",
"(",
"self",
".",
"index_url",
")",
":",
"parts",
"=",
"list",
"(",
"map",
"(",
"urllib",
".",
"parse",
".",
"unquote",
",",
"link",
"[",
"len",
"(",
"self",
".",
"index_url",
")",
":",
"]",
".",
"split",
"(",
"'/'",
")",
")",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
"and",
"'#'",
"not",
"in",
"parts",
"[",
"1",
"]",
":",
"# it's a package page, sanitize and index it",
"pkg",
"=",
"safe_name",
"(",
"parts",
"[",
"0",
"]",
")",
"ver",
"=",
"safe_version",
"(",
"parts",
"[",
"1",
"]",
")",
"self",
".",
"package_pages",
".",
"setdefault",
"(",
"pkg",
".",
"lower",
"(",
")",
",",
"{",
"}",
")",
"[",
"link",
"]",
"=",
"True",
"return",
"to_filename",
"(",
"pkg",
")",
",",
"to_filename",
"(",
"ver",
")",
"return",
"None",
",",
"None",
"# process an index page into the package-page index",
"for",
"match",
"in",
"HREF",
".",
"finditer",
"(",
"page",
")",
":",
"try",
":",
"scan",
"(",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"url",
",",
"htmldecode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
")",
"except",
"ValueError",
":",
"pass",
"pkg",
",",
"ver",
"=",
"scan",
"(",
"url",
")",
"# ensure this page is in the page index",
"if",
"pkg",
":",
"# process individual package page",
"for",
"new_url",
"in",
"find_external_links",
"(",
"url",
",",
"page",
")",
":",
"# Process the found URL",
"base",
",",
"frag",
"=",
"egg_info_for_url",
"(",
"new_url",
")",
"if",
"base",
".",
"endswith",
"(",
"'.py'",
")",
"and",
"not",
"frag",
":",
"if",
"ver",
":",
"new_url",
"+=",
"'#egg=%s-%s'",
"%",
"(",
"pkg",
",",
"ver",
")",
"else",
":",
"self",
".",
"need_version_info",
"(",
"url",
")",
"self",
".",
"scan_url",
"(",
"new_url",
")",
"return",
"PYPI_MD5",
".",
"sub",
"(",
"lambda",
"m",
":",
"'<a href=\"%s#md5=%s\">%s</a>'",
"%",
"m",
".",
"group",
"(",
"1",
",",
"3",
",",
"2",
")",
",",
"page",
")",
"else",
":",
"return",
"\"\""
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py#L431-L472 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py | python | TensorHandle._get_device_name | (handle) | return pydev.canonical_name(handle_str.split(";")[-1]) | The device name encoded in the handle. | The device name encoded in the handle. | [
"The",
"device",
"name",
"encoded",
"in",
"the",
"handle",
"."
] | def _get_device_name(handle):
"""The device name encoded in the handle."""
handle_str = compat.as_str_any(handle)
return pydev.canonical_name(handle_str.split(";")[-1]) | [
"def",
"_get_device_name",
"(",
"handle",
")",
":",
"handle_str",
"=",
"compat",
".",
"as_str_any",
"(",
"handle",
")",
"return",
"pydev",
".",
"canonical_name",
"(",
"handle_str",
".",
"split",
"(",
"\";\"",
")",
"[",
"-",
"1",
"]",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py#L122-L125 | |
KLayout/klayout | d764adb1016f74d3e9cc8059cb183f5fc29b2a25 | src/pymod/distutils_src/klayout/db/pcell_declaration_helper.py | python | _PCellDeclarationHelper.get_values | (self) | return v | gets the temporary parameter values | gets the temporary parameter values | [
"gets",
"the",
"temporary",
"parameter",
"values"
] | def get_values(self):
"""
gets the temporary parameter values
"""
v = self._param_values
self._param_values = None
return v | [
"def",
"get_values",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"_param_values",
"self",
".",
"_param_values",
"=",
"None",
"return",
"v"
] | https://github.com/KLayout/klayout/blob/d764adb1016f74d3e9cc8059cb183f5fc29b2a25/src/pymod/distutils_src/klayout/db/pcell_declaration_helper.py#L131-L137 | |
ros-planning/navigation2 | 70e7948afb45350e45c96b683518c1e6ba3f6010 | nav2_smac_planner/lattice_primitives/helper.py | python | normalize_angle | (angle) | return (angle + np.pi) % (2 * np.pi) - np.pi | Normalize the angle to between [-pi, pi).
Args:
angle: float
The angle to normalize in radians
Returns
-------
The normalized angle in the range [-pi,pi) | Normalize the angle to between [-pi, pi). | [
"Normalize",
"the",
"angle",
"to",
"between",
"[",
"-",
"pi",
"pi",
")",
"."
] | def normalize_angle(angle):
"""
Normalize the angle to between [-pi, pi).
Args:
angle: float
The angle to normalize in radians
Returns
-------
The normalized angle in the range [-pi,pi)
"""
return (angle + np.pi) % (2 * np.pi) - np.pi | [
"def",
"normalize_angle",
"(",
"angle",
")",
":",
"return",
"(",
"angle",
"+",
"np",
".",
"pi",
")",
"%",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"-",
"np",
".",
"pi"
] | https://github.com/ros-planning/navigation2/blob/70e7948afb45350e45c96b683518c1e6ba3f6010/nav2_smac_planner/lattice_primitives/helper.py#L18-L31 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pyio.py | python | IOBase._checkClosed | (self, msg=None) | Internal: raise a ValueError if file is closed | Internal: raise a ValueError if file is closed | [
"Internal",
":",
"raise",
"a",
"ValueError",
"if",
"file",
"is",
"closed"
] | def _checkClosed(self, msg=None):
"""Internal: raise a ValueError if file is closed
"""
if self.closed:
raise ValueError("I/O operation on closed file."
if msg is None else msg) | [
"def",
"_checkClosed",
"(",
"self",
",",
"msg",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file.\"",
"if",
"msg",
"is",
"None",
"else",
"msg",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pyio.py#L439-L444 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/meta.py | python | TrackingCodeGenerator.write | (self, x) | Don't write. | Don't write. | [
"Don",
"t",
"write",
"."
] | def write(self, x):
"""Don't write.""" | [
"def",
"write",
"(",
"self",
",",
"x",
")",
":"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/meta.py#L25-L26 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBDebugger.GetPrompt | (self) | return _lldb.SBDebugger_GetPrompt(self) | GetPrompt(self) -> str | GetPrompt(self) -> str | [
"GetPrompt",
"(",
"self",
")",
"-",
">",
"str"
] | def GetPrompt(self):
"""GetPrompt(self) -> str"""
return _lldb.SBDebugger_GetPrompt(self) | [
"def",
"GetPrompt",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_GetPrompt",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3456-L3458 | |
OKCoin/websocket | 50c806cf1e9a84984c6cf2efd94a937738cfc35c | python/websocket/_socket.py | python | setdefaulttimeout | (timeout) | Set the global timeout setting to connect.
timeout: default socket timeout time. This value is second. | Set the global timeout setting to connect. | [
"Set",
"the",
"global",
"timeout",
"setting",
"to",
"connect",
"."
] | def setdefaulttimeout(timeout):
"""
Set the global timeout setting to connect.
timeout: default socket timeout time. This value is second.
"""
global _default_timeout
_default_timeout = timeout | [
"def",
"setdefaulttimeout",
"(",
"timeout",
")",
":",
"global",
"_default_timeout",
"_default_timeout",
"=",
"timeout"
] | https://github.com/OKCoin/websocket/blob/50c806cf1e9a84984c6cf2efd94a937738cfc35c/python/websocket/_socket.py#L55-L62 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/numpy_ext.py | python | transpose | (a) | return b | numpy.transpose() with address check. | numpy.transpose() with address check. | [
"numpy",
".",
"transpose",
"()",
"with",
"address",
"check",
"."
] | def transpose(a):
"""numpy.transpose() with address check.
"""
b = a.transpose()
assert_addr(a, b)
return b | [
"def",
"transpose",
"(",
"a",
")",
":",
"b",
"=",
"a",
".",
"transpose",
"(",
")",
"assert_addr",
"(",
"a",
",",
"b",
")",
"return",
"b"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/numpy_ext.py#L82-L87 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/configparser.py | python | RawConfigParser.read_file | (self, f, source=None) | Like read() but the argument must be a file-like object.
The `f' argument must be iterable, returning one line at a time.
Optional second argument is the `source' specifying the name of the
file being read. If not given, it is taken from f.name. If `f' has no
`name' attribute, `<???>' is used. | Like read() but the argument must be a file-like object. | [
"Like",
"read",
"()",
"but",
"the",
"argument",
"must",
"be",
"a",
"file",
"-",
"like",
"object",
"."
] | def read_file(self, f, source=None):
"""Like read() but the argument must be a file-like object.
The `f' argument must be iterable, returning one line at a time.
Optional second argument is the `source' specifying the name of the
file being read. If not given, it is taken from f.name. If `f' has no
`name' attribute, `<???>' is used.
"""
if source is None:
try:
source = f.name
except AttributeError:
source = '<???>'
self._read(f, source) | [
"def",
"read_file",
"(",
"self",
",",
"f",
",",
"source",
"=",
"None",
")",
":",
"if",
"source",
"is",
"None",
":",
"try",
":",
"source",
"=",
"f",
".",
"name",
"except",
"AttributeError",
":",
"source",
"=",
"'<???>'",
"self",
".",
"_read",
"(",
"f",
",",
"source",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/configparser.py#L705-L718 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/dbgen/hashtools.py | python | check_hashes | (nuc_data) | return check_list | This function checks the hash of all the nodes in nodelist against the
built-in ones
Parameters
----------
nuc_data : str
path to the nuc_data.h5 file | This function checks the hash of all the nodes in nodelist against the
built-in ones | [
"This",
"function",
"checks",
"the",
"hash",
"of",
"all",
"the",
"nodes",
"in",
"nodelist",
"against",
"the",
"built",
"-",
"in",
"ones"
] | def check_hashes(nuc_data):
"""
This function checks the hash of all the nodes in nodelist against the
built-in ones
Parameters
----------
nuc_data : str
path to the nuc_data.h5 file
"""
check_list = []
for item in data.data_checksums:
res = (calc_hash(item, nuc_data) == data.data_checksums[item])
if res is False:
print("Expected hash: " + str(data.data_checksums[item]))
print("I got:" + str(calc_hash(item, nuc_data)))
check_list.append([item, res])
return check_list | [
"def",
"check_hashes",
"(",
"nuc_data",
")",
":",
"check_list",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
".",
"data_checksums",
":",
"res",
"=",
"(",
"calc_hash",
"(",
"item",
",",
"nuc_data",
")",
"==",
"data",
".",
"data_checksums",
"[",
"item",
"]",
")",
"if",
"res",
"is",
"False",
":",
"print",
"(",
"\"Expected hash: \"",
"+",
"str",
"(",
"data",
".",
"data_checksums",
"[",
"item",
"]",
")",
")",
"print",
"(",
"\"I got:\"",
"+",
"str",
"(",
"calc_hash",
"(",
"item",
",",
"nuc_data",
")",
")",
")",
"check_list",
".",
"append",
"(",
"[",
"item",
",",
"res",
"]",
")",
"return",
"check_list"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/dbgen/hashtools.py#L20-L38 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py | python | FitFunctionOptionsView.plot_guess_start_x | (self) | return float(self.plot_guess_start_x_line_edit.text()) | Returns the guess start X. | Returns the guess start X. | [
"Returns",
"the",
"guess",
"start",
"X",
"."
] | def plot_guess_start_x(self) -> float:
"""Returns the guess start X."""
return float(self.plot_guess_start_x_line_edit.text()) | [
"def",
"plot_guess_start_x",
"(",
"self",
")",
"->",
"float",
":",
"return",
"float",
"(",
"self",
".",
"plot_guess_start_x_line_edit",
".",
"text",
"(",
")",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py#L277-L279 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/email/message.py | python | Message.set_payload | (self, payload, charset=None) | Set the payload to the given value.
Optional charset sets the message's default character set. See
set_charset() for details. | Set the payload to the given value. | [
"Set",
"the",
"payload",
"to",
"the",
"given",
"value",
"."
] | def set_payload(self, payload, charset=None):
"""Set the payload to the given value.
Optional charset sets the message's default character set. See
set_charset() for details.
"""
self._payload = payload
if charset is not None:
self.set_charset(charset) | [
"def",
"set_payload",
"(",
"self",
",",
"payload",
",",
"charset",
"=",
"None",
")",
":",
"self",
".",
"_payload",
"=",
"payload",
"if",
"charset",
"is",
"not",
"None",
":",
"self",
".",
"set_charset",
"(",
"charset",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/email/message.py#L218-L226 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/common/extensions/docs/server2/reference_resolver.py | python | ReferenceResolver.ResolveAllLinks | (self, text, relative_to='', namespace=None) | return ''.join(formatted_text) | This method will resolve all $ref links in |text| using namespace
|namespace| if not None. Any links that cannot be resolved will be replaced
using the default link format that |SafeGetLink| uses.
The links will be generated relative to |relative_to|. | This method will resolve all $ref links in |text| using namespace
|namespace| if not None. Any links that cannot be resolved will be replaced
using the default link format that |SafeGetLink| uses.
The links will be generated relative to |relative_to|. | [
"This",
"method",
"will",
"resolve",
"all",
"$ref",
"links",
"in",
"|text|",
"using",
"namespace",
"|namespace|",
"if",
"not",
"None",
".",
"Any",
"links",
"that",
"cannot",
"be",
"resolved",
"will",
"be",
"replaced",
"using",
"the",
"default",
"link",
"format",
"that",
"|SafeGetLink|",
"uses",
".",
"The",
"links",
"will",
"be",
"generated",
"relative",
"to",
"|relative_to|",
"."
] | def ResolveAllLinks(self, text, relative_to='', namespace=None):
"""This method will resolve all $ref links in |text| using namespace
|namespace| if not None. Any links that cannot be resolved will be replaced
using the default link format that |SafeGetLink| uses.
The links will be generated relative to |relative_to|.
"""
if text is None or '$ref:' not in text:
return text
# requestPath should be of the form (apps|extensions)/...../page.html.
# link_prefix should that the target will point to
# (apps|extensions)/target.html. Note multiplying a string by a negative
# number gives the empty string.
link_prefix = '../' * (relative_to.count('/') - 1)
split_text = text.split('$ref:')
# |split_text| is an array of text chunks that all start with the
# argument to '$ref:'.
formatted_text = [split_text[0]]
for ref_and_rest in split_text[1:]:
title = None
if ref_and_rest.startswith('[') and ']' in ref_and_rest:
# Text was '$ref:[foo.bar maybe title] other stuff'.
ref_with_title, rest = ref_and_rest[1:].split(']', 1)
ref_with_title = ref_with_title.split(None, 1)
if len(ref_with_title) == 1:
# Text was '$ref:[foo.bar] other stuff'.
ref = ref_with_title[0]
else:
# Text was '$ref:[foo.bar title] other stuff'.
ref, title = ref_with_title
else:
# Text was '$ref:foo.bar other stuff'.
match = self._bare_ref.match(ref_and_rest)
if match is None:
ref = ''
rest = ref_and_rest
else:
ref = match.group()
rest = ref_and_rest[match.end():]
ref_dict = self.SafeGetLink(ref, namespace=namespace, title=title)
formatted_text.append('<a href="%s%s">%s</a>%s' %
(link_prefix, ref_dict['href'], ref_dict['text'], rest))
return ''.join(formatted_text) | [
"def",
"ResolveAllLinks",
"(",
"self",
",",
"text",
",",
"relative_to",
"=",
"''",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"text",
"is",
"None",
"or",
"'$ref:'",
"not",
"in",
"text",
":",
"return",
"text",
"# requestPath should be of the form (apps|extensions)/...../page.html.",
"# link_prefix should that the target will point to",
"# (apps|extensions)/target.html. Note multiplying a string by a negative",
"# number gives the empty string.",
"link_prefix",
"=",
"'../'",
"*",
"(",
"relative_to",
".",
"count",
"(",
"'/'",
")",
"-",
"1",
")",
"split_text",
"=",
"text",
".",
"split",
"(",
"'$ref:'",
")",
"# |split_text| is an array of text chunks that all start with the",
"# argument to '$ref:'.",
"formatted_text",
"=",
"[",
"split_text",
"[",
"0",
"]",
"]",
"for",
"ref_and_rest",
"in",
"split_text",
"[",
"1",
":",
"]",
":",
"title",
"=",
"None",
"if",
"ref_and_rest",
".",
"startswith",
"(",
"'['",
")",
"and",
"']'",
"in",
"ref_and_rest",
":",
"# Text was '$ref:[foo.bar maybe title] other stuff'.",
"ref_with_title",
",",
"rest",
"=",
"ref_and_rest",
"[",
"1",
":",
"]",
".",
"split",
"(",
"']'",
",",
"1",
")",
"ref_with_title",
"=",
"ref_with_title",
".",
"split",
"(",
"None",
",",
"1",
")",
"if",
"len",
"(",
"ref_with_title",
")",
"==",
"1",
":",
"# Text was '$ref:[foo.bar] other stuff'.",
"ref",
"=",
"ref_with_title",
"[",
"0",
"]",
"else",
":",
"# Text was '$ref:[foo.bar title] other stuff'.",
"ref",
",",
"title",
"=",
"ref_with_title",
"else",
":",
"# Text was '$ref:foo.bar other stuff'.",
"match",
"=",
"self",
".",
"_bare_ref",
".",
"match",
"(",
"ref_and_rest",
")",
"if",
"match",
"is",
"None",
":",
"ref",
"=",
"''",
"rest",
"=",
"ref_and_rest",
"else",
":",
"ref",
"=",
"match",
".",
"group",
"(",
")",
"rest",
"=",
"ref_and_rest",
"[",
"match",
".",
"end",
"(",
")",
":",
"]",
"ref_dict",
"=",
"self",
".",
"SafeGetLink",
"(",
"ref",
",",
"namespace",
"=",
"namespace",
",",
"title",
"=",
"title",
")",
"formatted_text",
".",
"append",
"(",
"'<a href=\"%s%s\">%s</a>%s'",
"%",
"(",
"link_prefix",
",",
"ref_dict",
"[",
"'href'",
"]",
",",
"ref_dict",
"[",
"'text'",
"]",
",",
"rest",
")",
")",
"return",
"''",
".",
"join",
"(",
"formatted_text",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/reference_resolver.py#L172-L215 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | syzygy/build/create_zip.py | python | _SwitchSubdir | (dummy_option, dummy_option_string, value, parser) | A callback used by the option parser.
Switches the currently active ZIP archive path, and appends any outstanding
positional arguments to the list of files for the previously active
ZIP archive path. | A callback used by the option parser. | [
"A",
"callback",
"used",
"by",
"the",
"option",
"parser",
"."
] | def _SwitchSubdir(dummy_option, dummy_option_string, value, parser):
"""A callback used by the option parser.
Switches the currently active ZIP archive path, and appends any outstanding
positional arguments to the list of files for the previously active
ZIP archive path.
"""
# When this is called by the '--files' callback there is no value passed
# to the option. Thus, we use a value of '', which indicates the root
# directory.
if not value:
value = ''
# Extend the previously active sub-directory file list with those
# arguments that have been parsed since it was set.
files = parser.values.files
if isinstance(parser.values.subdir, basestring):
destroot = parser.values.subdir
srcroot = None
else:
destroot = parser.values.subdir[0]
srcroot = parser.values.subdir[1]
subdir = files.setdefault(destroot, {})
subdir_root = subdir.setdefault(srcroot, [])
subdir_root.extend(parser.largs)
# Remove these arguments from the list of processed arguments.
del parser.largs[:len(parser.largs)]
# Update the currently active sub-directory. Further arguments that are
# parsed will append to this sub-directory's file list.
parser.values.subdir = value | [
"def",
"_SwitchSubdir",
"(",
"dummy_option",
",",
"dummy_option_string",
",",
"value",
",",
"parser",
")",
":",
"# When this is called by the '--files' callback there is no value passed",
"# to the option. Thus, we use a value of '', which indicates the root",
"# directory.",
"if",
"not",
"value",
":",
"value",
"=",
"''",
"# Extend the previously active sub-directory file list with those",
"# arguments that have been parsed since it was set.",
"files",
"=",
"parser",
".",
"values",
".",
"files",
"if",
"isinstance",
"(",
"parser",
".",
"values",
".",
"subdir",
",",
"basestring",
")",
":",
"destroot",
"=",
"parser",
".",
"values",
".",
"subdir",
"srcroot",
"=",
"None",
"else",
":",
"destroot",
"=",
"parser",
".",
"values",
".",
"subdir",
"[",
"0",
"]",
"srcroot",
"=",
"parser",
".",
"values",
".",
"subdir",
"[",
"1",
"]",
"subdir",
"=",
"files",
".",
"setdefault",
"(",
"destroot",
",",
"{",
"}",
")",
"subdir_root",
"=",
"subdir",
".",
"setdefault",
"(",
"srcroot",
",",
"[",
"]",
")",
"subdir_root",
".",
"extend",
"(",
"parser",
".",
"largs",
")",
"# Remove these arguments from the list of processed arguments.",
"del",
"parser",
".",
"largs",
"[",
":",
"len",
"(",
"parser",
".",
"largs",
")",
"]",
"# Update the currently active sub-directory. Further arguments that are",
"# parsed will append to this sub-directory's file list.",
"parser",
".",
"values",
".",
"subdir",
"=",
"value"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/syzygy/build/create_zip.py#L95-L127 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/platform.py | python | uname | () | return _uname_cache | Fairly portable uname interface. Returns a tuple
of strings (system, node, release, version, machine, processor)
identifying the underlying platform.
Note that unlike the os.uname function this also returns
possible processor information as an additional tuple entry.
Entries which cannot be determined are set to ''. | Fairly portable uname interface. Returns a tuple
of strings (system, node, release, version, machine, processor)
identifying the underlying platform. | [
"Fairly",
"portable",
"uname",
"interface",
".",
"Returns",
"a",
"tuple",
"of",
"strings",
"(",
"system",
"node",
"release",
"version",
"machine",
"processor",
")",
"identifying",
"the",
"underlying",
"platform",
"."
] | def uname():
""" Fairly portable uname interface. Returns a tuple
of strings (system, node, release, version, machine, processor)
identifying the underlying platform.
Note that unlike the os.uname function this also returns
possible processor information as an additional tuple entry.
Entries which cannot be determined are set to ''.
"""
global _uname_cache
no_os_uname = 0
if _uname_cache is not None:
return _uname_cache
processor = ''
# Get some infos from the builtin os.uname API...
try:
system, node, release, version, machine = os.uname()
except AttributeError:
no_os_uname = 1
if no_os_uname or not list(filter(None, (system, node, release, version, machine))):
# Hmm, no there is either no uname or uname has returned
#'unknowns'... we'll have to poke around the system then.
if no_os_uname:
system = sys.platform
release = ''
version = ''
node = _node()
machine = ''
use_syscmd_ver = 1
# Try win32_ver() on win32 platforms
if system == 'win32':
release, version, csd, ptype = win32_ver()
if release and version:
use_syscmd_ver = 0
# Try to use the PROCESSOR_* environment variables
# available on Win XP and later; see
# http://support.microsoft.com/kb/888731 and
# http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
if not machine:
# WOW64 processes mask the native architecture
if "PROCESSOR_ARCHITEW6432" in os.environ:
machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
else:
machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
if not processor:
processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
# Try the 'ver' system command available on some
# platforms
if use_syscmd_ver:
system, release, version = _syscmd_ver(system)
# Normalize system to what win32_ver() normally returns
# (_syscmd_ver() tends to return the vendor name as well)
if system == 'Microsoft Windows':
system = 'Windows'
elif system == 'Microsoft' and release == 'Windows':
# Under Windows Vista and Windows Server 2008,
# Microsoft changed the output of the ver command. The
# release is no longer printed. This causes the
# system and release to be misidentified.
system = 'Windows'
if '6.0' == version[:3]:
release = 'Vista'
else:
release = ''
# In case we still don't know anything useful, we'll try to
# help ourselves
if system in ('win32', 'win16'):
if not version:
if system == 'win32':
version = '32bit'
else:
version = '16bit'
system = 'Windows'
elif system[:4] == 'java':
release, vendor, vminfo, osinfo = java_ver()
system = 'Java'
version = ', '.join(vminfo)
if not version:
version = vendor
# System specific extensions
if system == 'OpenVMS':
# OpenVMS seems to have release and version mixed up
if not release or release == '0':
release = version
version = ''
# Get processor information
try:
import vms_lib
except ImportError:
pass
else:
csid, cpu_number = vms_lib.getsyi('SYI$_CPU', 0)
if (cpu_number >= 128):
processor = 'Alpha'
else:
processor = 'VAX'
if not processor:
# Get processor information from the uname system command
processor = _syscmd_uname('-p', '')
#If any unknowns still exist, replace them with ''s, which are more portable
if system == 'unknown':
system = ''
if node == 'unknown':
node = ''
if release == 'unknown':
release = ''
if version == 'unknown':
version = ''
if machine == 'unknown':
machine = ''
if processor == 'unknown':
processor = ''
# normalize name
if system == 'Microsoft' and release == 'Windows':
system = 'Windows'
release = 'Vista'
_uname_cache = uname_result(system, node, release, version,
machine, processor)
return _uname_cache | [
"def",
"uname",
"(",
")",
":",
"global",
"_uname_cache",
"no_os_uname",
"=",
"0",
"if",
"_uname_cache",
"is",
"not",
"None",
":",
"return",
"_uname_cache",
"processor",
"=",
"''",
"# Get some infos from the builtin os.uname API...",
"try",
":",
"system",
",",
"node",
",",
"release",
",",
"version",
",",
"machine",
"=",
"os",
".",
"uname",
"(",
")",
"except",
"AttributeError",
":",
"no_os_uname",
"=",
"1",
"if",
"no_os_uname",
"or",
"not",
"list",
"(",
"filter",
"(",
"None",
",",
"(",
"system",
",",
"node",
",",
"release",
",",
"version",
",",
"machine",
")",
")",
")",
":",
"# Hmm, no there is either no uname or uname has returned",
"#'unknowns'... we'll have to poke around the system then.",
"if",
"no_os_uname",
":",
"system",
"=",
"sys",
".",
"platform",
"release",
"=",
"''",
"version",
"=",
"''",
"node",
"=",
"_node",
"(",
")",
"machine",
"=",
"''",
"use_syscmd_ver",
"=",
"1",
"# Try win32_ver() on win32 platforms",
"if",
"system",
"==",
"'win32'",
":",
"release",
",",
"version",
",",
"csd",
",",
"ptype",
"=",
"win32_ver",
"(",
")",
"if",
"release",
"and",
"version",
":",
"use_syscmd_ver",
"=",
"0",
"# Try to use the PROCESSOR_* environment variables",
"# available on Win XP and later; see",
"# http://support.microsoft.com/kb/888731 and",
"# http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM",
"if",
"not",
"machine",
":",
"# WOW64 processes mask the native architecture",
"if",
"\"PROCESSOR_ARCHITEW6432\"",
"in",
"os",
".",
"environ",
":",
"machine",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PROCESSOR_ARCHITEW6432\"",
",",
"''",
")",
"else",
":",
"machine",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PROCESSOR_ARCHITECTURE'",
",",
"''",
")",
"if",
"not",
"processor",
":",
"processor",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PROCESSOR_IDENTIFIER'",
",",
"machine",
")",
"# Try the 'ver' system command available on some",
"# platforms",
"if",
"use_syscmd_ver",
":",
"system",
",",
"release",
",",
"version",
"=",
"_syscmd_ver",
"(",
"system",
")",
"# Normalize system to what win32_ver() normally returns",
"# (_syscmd_ver() tends to return the vendor name as well)",
"if",
"system",
"==",
"'Microsoft Windows'",
":",
"system",
"=",
"'Windows'",
"elif",
"system",
"==",
"'Microsoft'",
"and",
"release",
"==",
"'Windows'",
":",
"# Under Windows Vista and Windows Server 2008,",
"# Microsoft changed the output of the ver command. The",
"# release is no longer printed. This causes the",
"# system and release to be misidentified.",
"system",
"=",
"'Windows'",
"if",
"'6.0'",
"==",
"version",
"[",
":",
"3",
"]",
":",
"release",
"=",
"'Vista'",
"else",
":",
"release",
"=",
"''",
"# In case we still don't know anything useful, we'll try to",
"# help ourselves",
"if",
"system",
"in",
"(",
"'win32'",
",",
"'win16'",
")",
":",
"if",
"not",
"version",
":",
"if",
"system",
"==",
"'win32'",
":",
"version",
"=",
"'32bit'",
"else",
":",
"version",
"=",
"'16bit'",
"system",
"=",
"'Windows'",
"elif",
"system",
"[",
":",
"4",
"]",
"==",
"'java'",
":",
"release",
",",
"vendor",
",",
"vminfo",
",",
"osinfo",
"=",
"java_ver",
"(",
")",
"system",
"=",
"'Java'",
"version",
"=",
"', '",
".",
"join",
"(",
"vminfo",
")",
"if",
"not",
"version",
":",
"version",
"=",
"vendor",
"# System specific extensions",
"if",
"system",
"==",
"'OpenVMS'",
":",
"# OpenVMS seems to have release and version mixed up",
"if",
"not",
"release",
"or",
"release",
"==",
"'0'",
":",
"release",
"=",
"version",
"version",
"=",
"''",
"# Get processor information",
"try",
":",
"import",
"vms_lib",
"except",
"ImportError",
":",
"pass",
"else",
":",
"csid",
",",
"cpu_number",
"=",
"vms_lib",
".",
"getsyi",
"(",
"'SYI$_CPU'",
",",
"0",
")",
"if",
"(",
"cpu_number",
">=",
"128",
")",
":",
"processor",
"=",
"'Alpha'",
"else",
":",
"processor",
"=",
"'VAX'",
"if",
"not",
"processor",
":",
"# Get processor information from the uname system command",
"processor",
"=",
"_syscmd_uname",
"(",
"'-p'",
",",
"''",
")",
"#If any unknowns still exist, replace them with ''s, which are more portable",
"if",
"system",
"==",
"'unknown'",
":",
"system",
"=",
"''",
"if",
"node",
"==",
"'unknown'",
":",
"node",
"=",
"''",
"if",
"release",
"==",
"'unknown'",
":",
"release",
"=",
"''",
"if",
"version",
"==",
"'unknown'",
":",
"version",
"=",
"''",
"if",
"machine",
"==",
"'unknown'",
":",
"machine",
"=",
"''",
"if",
"processor",
"==",
"'unknown'",
":",
"processor",
"=",
"''",
"# normalize name",
"if",
"system",
"==",
"'Microsoft'",
"and",
"release",
"==",
"'Windows'",
":",
"system",
"=",
"'Windows'",
"release",
"=",
"'Vista'",
"_uname_cache",
"=",
"uname_result",
"(",
"system",
",",
"node",
",",
"release",
",",
"version",
",",
"machine",
",",
"processor",
")",
"return",
"_uname_cache"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/platform.py#L923-L1057 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | AuiPaneInfo.Right | (*args, **kwargs) | return _aui.AuiPaneInfo_Right(*args, **kwargs) | Right(self) -> AuiPaneInfo | Right(self) -> AuiPaneInfo | [
"Right",
"(",
"self",
")",
"-",
">",
"AuiPaneInfo"
] | def Right(*args, **kwargs):
"""Right(self) -> AuiPaneInfo"""
return _aui.AuiPaneInfo_Right(*args, **kwargs) | [
"def",
"Right",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_Right",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L353-L355 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.add_common_quantization_nodes | (self, namespace_prefix) | return reshape_dims_name, reduction_dims_name | Builds constant nodes needed for quantization of inputs. | Builds constant nodes needed for quantization of inputs. | [
"Builds",
"constant",
"nodes",
"needed",
"for",
"quantization",
"of",
"inputs",
"."
] | def add_common_quantization_nodes(self, namespace_prefix):
"""Builds constant nodes needed for quantization of inputs."""
reshape_dims_name = namespace_prefix + "_reshape_dims"
reduction_dims_name = namespace_prefix + "_reduction_dims"
reshape_dims_node = create_constant_node(reshape_dims_name, -1, tf.int32,
[1])
self.add_output_graph_node(reshape_dims_node)
reduction_dims_node = create_constant_node(reduction_dims_name, 0, tf.int32,
[1])
self.add_output_graph_node(reduction_dims_node)
return reshape_dims_name, reduction_dims_name | [
"def",
"add_common_quantization_nodes",
"(",
"self",
",",
"namespace_prefix",
")",
":",
"reshape_dims_name",
"=",
"namespace_prefix",
"+",
"\"_reshape_dims\"",
"reduction_dims_name",
"=",
"namespace_prefix",
"+",
"\"_reduction_dims\"",
"reshape_dims_node",
"=",
"create_constant_node",
"(",
"reshape_dims_name",
",",
"-",
"1",
",",
"tf",
".",
"int32",
",",
"[",
"1",
"]",
")",
"self",
".",
"add_output_graph_node",
"(",
"reshape_dims_node",
")",
"reduction_dims_node",
"=",
"create_constant_node",
"(",
"reduction_dims_name",
",",
"0",
",",
"tf",
".",
"int32",
",",
"[",
"1",
"]",
")",
"self",
".",
"add_output_graph_node",
"(",
"reduction_dims_node",
")",
"return",
"reshape_dims_name",
",",
"reduction_dims_name"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L500-L511 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | GLGenerator.Log | (self, msg) | Prints something if verbose is true. | Prints something if verbose is true. | [
"Prints",
"something",
"if",
"verbose",
"is",
"true",
"."
] | def Log(self, msg):
"""Prints something if verbose is true."""
if self.verbose:
print msg | [
"def",
"Log",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"msg"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5635-L5638 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py | python | GetMacBundleResources | (product_dir, xcode_settings, resources) | Yields (output, resource) pairs for every resource in |resources|.
Only call this for mac bundle targets.
Args:
product_dir: Path to the directory containing the output bundle,
relative to the build directory.
xcode_settings: The XcodeSettings of the current target.
resources: A list of bundle resources, relative to the build directory. | Yields (output, resource) pairs for every resource in |resources|.
Only call this for mac bundle targets. | [
"Yields",
"(",
"output",
"resource",
")",
"pairs",
"for",
"every",
"resource",
"in",
"|resources|",
".",
"Only",
"call",
"this",
"for",
"mac",
"bundle",
"targets",
"."
] | def GetMacBundleResources(product_dir, xcode_settings, resources):
"""Yields (output, resource) pairs for every resource in |resources|.
Only call this for mac bundle targets.
Args:
product_dir: Path to the directory containing the output bundle,
relative to the build directory.
xcode_settings: The XcodeSettings of the current target.
resources: A list of bundle resources, relative to the build directory.
"""
dest = os.path.join(product_dir,
xcode_settings.GetBundleResourceFolder())
for res in resources:
output = dest
# The make generator doesn't support it, so forbid it everywhere
# to keep the generators more interchangable.
assert ' ' not in res, (
"Spaces in resource filenames not supported (%s)" % res)
# Split into (path,file).
res_parts = os.path.split(res)
# Now split the path into (prefix,maybe.lproj).
lproj_parts = os.path.split(res_parts[0])
# If the resource lives in a .lproj bundle, add that to the destination.
if lproj_parts[1].endswith('.lproj'):
output = os.path.join(output, lproj_parts[1])
output = os.path.join(output, res_parts[1])
# Compiled XIB files are referred to by .nib.
if output.endswith('.xib'):
output = output[0:-3] + 'nib'
yield output, res | [
"def",
"GetMacBundleResources",
"(",
"product_dir",
",",
"xcode_settings",
",",
"resources",
")",
":",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"product_dir",
",",
"xcode_settings",
".",
"GetBundleResourceFolder",
"(",
")",
")",
"for",
"res",
"in",
"resources",
":",
"output",
"=",
"dest",
"# The make generator doesn't support it, so forbid it everywhere",
"# to keep the generators more interchangable.",
"assert",
"' '",
"not",
"in",
"res",
",",
"(",
"\"Spaces in resource filenames not supported (%s)\"",
"%",
"res",
")",
"# Split into (path,file).",
"res_parts",
"=",
"os",
".",
"path",
".",
"split",
"(",
"res",
")",
"# Now split the path into (prefix,maybe.lproj).",
"lproj_parts",
"=",
"os",
".",
"path",
".",
"split",
"(",
"res_parts",
"[",
"0",
"]",
")",
"# If the resource lives in a .lproj bundle, add that to the destination.",
"if",
"lproj_parts",
"[",
"1",
"]",
".",
"endswith",
"(",
"'.lproj'",
")",
":",
"output",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output",
",",
"lproj_parts",
"[",
"1",
"]",
")",
"output",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output",
",",
"res_parts",
"[",
"1",
"]",
")",
"# Compiled XIB files are referred to by .nib.",
"if",
"output",
".",
"endswith",
"(",
"'.xib'",
")",
":",
"output",
"=",
"output",
"[",
"0",
":",
"-",
"3",
"]",
"+",
"'nib'",
"yield",
"output",
",",
"res"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py#L824-L858 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/design-an-ordered-stream.py | python | OrderedStream.__init__ | (self, n) | :type n: int | :type n: int | [
":",
"type",
"n",
":",
"int"
] | def __init__(self, n):
"""
:type n: int
"""
self.__i = 0
self.__values = [None]*n | [
"def",
"__init__",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"__i",
"=",
"0",
"self",
".",
"__values",
"=",
"[",
"None",
"]",
"*",
"n"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/design-an-ordered-stream.py#L6-L11 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/mozjs/extract/js/src/builtin/intl/make_intl_data.py | python | icuTzDataVersion | (icuTzDir) | return version | Read the ICU time zone version from `icuTzDir`/zoneinfo64.txt. | Read the ICU time zone version from `icuTzDir`/zoneinfo64.txt. | [
"Read",
"the",
"ICU",
"time",
"zone",
"version",
"from",
"icuTzDir",
"/",
"zoneinfo64",
".",
"txt",
"."
] | def icuTzDataVersion(icuTzDir):
""" Read the ICU time zone version from `icuTzDir`/zoneinfo64.txt. """
def searchInFile(pattern, f):
p = re.compile(pattern)
for line in flines(f, "utf-8-sig"):
m = p.search(line)
if m:
return m.group(1)
return None
zoneinfo = os.path.join(icuTzDir, "zoneinfo64.txt")
if not os.path.isfile(zoneinfo):
raise RuntimeError("file not found: %s" % zoneinfo)
version = searchInFile("^//\s+tz version:\s+([0-9]{4}[a-z])$", zoneinfo)
if version is None:
raise RuntimeError("%s does not contain a valid tzdata version string" % zoneinfo)
return version | [
"def",
"icuTzDataVersion",
"(",
"icuTzDir",
")",
":",
"def",
"searchInFile",
"(",
"pattern",
",",
"f",
")",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"for",
"line",
"in",
"flines",
"(",
"f",
",",
"\"utf-8-sig\"",
")",
":",
"m",
"=",
"p",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"return",
"m",
".",
"group",
"(",
"1",
")",
"return",
"None",
"zoneinfo",
"=",
"os",
".",
"path",
".",
"join",
"(",
"icuTzDir",
",",
"\"zoneinfo64.txt\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"zoneinfo",
")",
":",
"raise",
"RuntimeError",
"(",
"\"file not found: %s\"",
"%",
"zoneinfo",
")",
"version",
"=",
"searchInFile",
"(",
"\"^//\\s+tz version:\\s+([0-9]{4}[a-z])$\"",
",",
"zoneinfo",
")",
"if",
"version",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"%s does not contain a valid tzdata version string\"",
"%",
"zoneinfo",
")",
"return",
"version"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/mozjs/extract/js/src/builtin/intl/make_intl_data.py#L621-L637 | |
raymondlu/super-animation-samples | 04234269112ff0dc32447f27a761dbbb00b8ba17 | samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | File.time | (self) | return conf.lib.clang_getFileTime(self) | Return the last modification time of the file. | Return the last modification time of the file. | [
"Return",
"the",
"last",
"modification",
"time",
"of",
"the",
"file",
"."
] | def time(self):
"""Return the last modification time of the file."""
return conf.lib.clang_getFileTime(self) | [
"def",
"time",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getFileTime",
"(",
"self",
")"
] | https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2497-L2499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.