nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/utils/unpacking.py | python | has_leading_dir | (paths) | return True | Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive) | Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive) | [
"Returns",
"true",
"if",
"all",
"the",
"paths",
"have",
"the",
"same",
"leading",
"path",
"name",
"(",
"i",
".",
"e",
".",
"everything",
"is",
"in",
"one",
"subdirectory",
"in",
"an",
"archive",
")"
] | def has_leading_dir(paths):
# type: (Iterable[str]) -> bool
"""Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive)"""
common_prefix = None
for path in paths:
prefix, rest = split_leading_dir(path)
if not prefix:
return False
elif common_prefix is None:
common_prefix = prefix
elif prefix != common_prefix:
return False
return True | [
"def",
"has_leading_dir",
"(",
"paths",
")",
":",
"# type: (Iterable[str]) -> bool",
"common_prefix",
"=",
"None",
"for",
"path",
"in",
"paths",
":",
"prefix",
",",
"rest",
"=",
"split_leading_dir",
"(",
"path",
")",
"if",
"not",
"prefix",
":",
"return",
"Fals... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/utils/unpacking.py#L69-L82 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/calendar.py | python | CalendarEvent.GetWeekDay | (*args, **kwargs) | return _calendar.CalendarEvent_GetWeekDay(*args, **kwargs) | GetWeekDay(self) -> int | GetWeekDay(self) -> int | [
"GetWeekDay",
"(",
"self",
")",
"-",
">",
"int"
] | def GetWeekDay(*args, **kwargs):
"""GetWeekDay(self) -> int"""
return _calendar.CalendarEvent_GetWeekDay(*args, **kwargs) | [
"def",
"GetWeekDay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"CalendarEvent_GetWeekDay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/calendar.py#L202-L204 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/preprocessing/data.py | python | scale | (X, axis=0, with_mean=True, with_std=True, copy=True) | return X | Standardize a dataset along any axis
Center to the mean and component wise scale to unit variance.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
X : {array-like, sparse matrix}
The data to center and scale.
axis : int (0 by default)
axis used to compute the means and standard deviations along. If 0,
independently standardize each feature, otherwise (if 1) standardize
each sample.
with_mean : boolean, True by default
If True, center the data before scaling.
with_std : boolean, True by default
If True, scale the data to unit variance (or equivalently,
unit standard deviation).
copy : boolean, optional, default True
set to False to perform inplace row normalization and avoid a
copy (if the input is already a numpy array or a scipy.sparse
CSC matrix and if axis is 1).
Notes
-----
This implementation will refuse to center scipy.sparse matrices
since it would make them non-sparse and would potentially crash the
program with memory exhaustion problems.
Instead the caller is expected to either set explicitly
`with_mean=False` (in that case, only variance scaling will be
performed on the features of the CSC matrix) or to call `X.toarray()`
if he/she expects the materialized dense array to fit in memory.
To avoid memory copy the caller should pass a CSC matrix.
See also
--------
StandardScaler: Performs scaling to unit variance using the``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). | Standardize a dataset along any axis | [
"Standardize",
"a",
"dataset",
"along",
"any",
"axis"
] | def scale(X, axis=0, with_mean=True, with_std=True, copy=True):
"""Standardize a dataset along any axis
Center to the mean and component wise scale to unit variance.
Read more in the :ref:`User Guide <preprocessing_scaler>`.
Parameters
----------
X : {array-like, sparse matrix}
The data to center and scale.
axis : int (0 by default)
axis used to compute the means and standard deviations along. If 0,
independently standardize each feature, otherwise (if 1) standardize
each sample.
with_mean : boolean, True by default
If True, center the data before scaling.
with_std : boolean, True by default
If True, scale the data to unit variance (or equivalently,
unit standard deviation).
copy : boolean, optional, default True
set to False to perform inplace row normalization and avoid a
copy (if the input is already a numpy array or a scipy.sparse
CSC matrix and if axis is 1).
Notes
-----
This implementation will refuse to center scipy.sparse matrices
since it would make them non-sparse and would potentially crash the
program with memory exhaustion problems.
Instead the caller is expected to either set explicitly
`with_mean=False` (in that case, only variance scaling will be
performed on the features of the CSC matrix) or to call `X.toarray()`
if he/she expects the materialized dense array to fit in memory.
To avoid memory copy the caller should pass a CSC matrix.
See also
--------
StandardScaler: Performs scaling to unit variance using the``Transformer`` API
(e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`).
""" # noqa
X = check_array(X, accept_sparse='csc', copy=copy, ensure_2d=False,
warn_on_dtype=True, estimator='the scale function',
dtype=FLOAT_DTYPES)
if sparse.issparse(X):
if with_mean:
raise ValueError(
"Cannot center sparse matrices: pass `with_mean=False` instead"
" See docstring for motivation and alternatives.")
if axis != 0:
raise ValueError("Can only scale sparse matrix on axis=0, "
" got axis=%d" % axis)
if with_std:
_, var = mean_variance_axis(X, axis=0)
var = _handle_zeros_in_scale(var, copy=False)
inplace_column_scale(X, 1 / np.sqrt(var))
else:
X = np.asarray(X)
if with_mean:
mean_ = np.mean(X, axis)
if with_std:
scale_ = np.std(X, axis)
# Xr is a view on the original array that enables easy use of
# broadcasting on the axis in which we are interested in
Xr = np.rollaxis(X, axis)
if with_mean:
Xr -= mean_
mean_1 = Xr.mean(axis=0)
# Verify that mean_1 is 'close to zero'. If X contains very
# large values, mean_1 can also be very large, due to a lack of
# precision of mean_. In this case, a pre-scaling of the
# concerned feature is efficient, for instance by its mean or
# maximum.
if not np.allclose(mean_1, 0):
warnings.warn("Numerical issues were encountered "
"when centering the data "
"and might not be solved. Dataset may "
"contain too large values. You may need "
"to prescale your features.")
Xr -= mean_1
if with_std:
scale_ = _handle_zeros_in_scale(scale_, copy=False)
Xr /= scale_
if with_mean:
mean_2 = Xr.mean(axis=0)
# If mean_2 is not 'close to zero', it comes from the fact that
# scale_ is very small so that mean_2 = mean_1/scale_ > 0, even
# if mean_1 was close to zero. The problem is thus essentially
# due to the lack of precision of mean_. A solution is then to
# subtract the mean again:
if not np.allclose(mean_2, 0):
warnings.warn("Numerical issues were encountered "
"when scaling the data "
"and might not be solved. The standard "
"deviation of the data is probably "
"very close to 0. ")
Xr -= mean_2
return X | [
"def",
"scale",
"(",
"X",
",",
"axis",
"=",
"0",
",",
"with_mean",
"=",
"True",
",",
"with_std",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"# noqa",
"X",
"=",
"check_array",
"(",
"X",
",",
"accept_sparse",
"=",
"'csc'",
",",
"copy",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/preprocessing/data.py#L80-L183 | |
numworks/epsilon | 8952d2f8b1de1c3f064eec8ffcea804c5594ba4c | build/device/usb/backend/__init__.py | python | IBackend.open_device | (self, dev) | r"""Open the device for data exchange.
This method opens the device identified by the dev parameter for communication.
This method must be called before calling any communication related method, such
as transfer methods.
It returns a handle identifying the communication instance. This handle must be
passed to the communication methods. | r"""Open the device for data exchange. | [
"r",
"Open",
"the",
"device",
"for",
"data",
"exchange",
"."
] | def open_device(self, dev):
r"""Open the device for data exchange.
This method opens the device identified by the dev parameter for communication.
This method must be called before calling any communication related method, such
as transfer methods.
It returns a handle identifying the communication instance. This handle must be
passed to the communication methods.
"""
_not_implemented(self.open_device) | [
"def",
"open_device",
"(",
"self",
",",
"dev",
")",
":",
"_not_implemented",
"(",
"self",
".",
"open_device",
")"
] | https://github.com/numworks/epsilon/blob/8952d2f8b1de1c3f064eec8ffcea804c5594ba4c/build/device/usb/backend/__init__.py#L168-L178 | ||
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32comext/axscript/client/framework.py | python | EventSink.GetSourceTypeInfo | (self, typeinfo) | Gets the typeinfo for the Source Events for the passed typeinfo | Gets the typeinfo for the Source Events for the passed typeinfo | [
"Gets",
"the",
"typeinfo",
"for",
"the",
"Source",
"Events",
"for",
"the",
"passed",
"typeinfo"
] | def GetSourceTypeInfo(self, typeinfo):
"""Gets the typeinfo for the Source Events for the passed typeinfo"""
attr = typeinfo.GetTypeAttr()
cFuncs = attr[6]
typeKind = attr[5]
if typeKind not in [pythoncom.TKIND_COCLASS, pythoncom.TKIND_INTERFACE]:
RaiseAssert(
winerror.E_UNEXPECTED, "The typeKind of the object is unexpected"
)
cImplType = attr[8]
for i in range(cImplType):
# Look for the [source, default] interface on the coclass
# that isn't marked as restricted.
flags = typeinfo.GetImplTypeFlags(i)
flagsNeeded = (
pythoncom.IMPLTYPEFLAG_FDEFAULT | pythoncom.IMPLTYPEFLAG_FSOURCE
)
if (flags & (flagsNeeded | pythoncom.IMPLTYPEFLAG_FRESTRICTED)) == (
flagsNeeded
):
# Get the handle to the implemented interface.
href = typeinfo.GetRefTypeOfImplType(i)
return typeinfo.GetRefTypeInfo(href) | [
"def",
"GetSourceTypeInfo",
"(",
"self",
",",
"typeinfo",
")",
":",
"attr",
"=",
"typeinfo",
".",
"GetTypeAttr",
"(",
")",
"cFuncs",
"=",
"attr",
"[",
"6",
"]",
"typeKind",
"=",
"attr",
"[",
"5",
"]",
"if",
"typeKind",
"not",
"in",
"[",
"pythoncom",
... | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32comext/axscript/client/framework.py#L213-L235 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | ClientDC.__init__ | (self, *args, **kwargs) | __init__(self, Window win) -> ClientDC
Constructor. Pass the window on which you wish to paint. | __init__(self, Window win) -> ClientDC | [
"__init__",
"(",
"self",
"Window",
"win",
")",
"-",
">",
"ClientDC"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window win) -> ClientDC
Constructor. Pass the window on which you wish to paint.
"""
_gdi_.ClientDC_swiginit(self,_gdi_.new_ClientDC(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"ClientDC_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_ClientDC",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L5094-L5100 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | NativePixelData_Accessor.MoveTo | (*args, **kwargs) | return _gdi_.NativePixelData_Accessor_MoveTo(*args, **kwargs) | MoveTo(self, NativePixelData data, int x, int y) | MoveTo(self, NativePixelData data, int x, int y) | [
"MoveTo",
"(",
"self",
"NativePixelData",
"data",
"int",
"x",
"int",
"y",
")"
] | def MoveTo(*args, **kwargs):
"""MoveTo(self, NativePixelData data, int x, int y)"""
return _gdi_.NativePixelData_Accessor_MoveTo(*args, **kwargs) | [
"def",
"MoveTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"NativePixelData_Accessor_MoveTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L1112-L1114 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | ExFileObject.__iter__ | (self) | Get an iterator over the file's lines. | Get an iterator over the file's lines. | [
"Get",
"an",
"iterator",
"over",
"the",
"file",
"s",
"lines",
"."
] | def __iter__(self):
"""Get an iterator over the file's lines.
"""
while True:
line = self.readline()
if not line:
break
yield line | [
"def",
"__iter__",
"(",
"self",
")",
":",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"yield",
"line"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1819-L1833 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/elementwise/logistic.py | python | logistic.numeric | (self, values) | return np.logaddexp(0, values[0]) | Evaluates e^x elementwise, adds 1, and takes the log. | Evaluates e^x elementwise, adds 1, and takes the log. | [
"Evaluates",
"e^x",
"elementwise",
"adds",
"1",
"and",
"takes",
"the",
"log",
"."
] | def numeric(self, values):
"""Evaluates e^x elementwise, adds 1, and takes the log.
"""
return np.logaddexp(0, values[0]) | [
"def",
"numeric",
"(",
"self",
",",
"values",
")",
":",
"return",
"np",
".",
"logaddexp",
"(",
"0",
",",
"values",
"[",
"0",
"]",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/logistic.py#L35-L38 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | examples/python/dict_utils.py | python | LookupDictionary.get_first_key_for_value | (self, value, fail_value=None) | return fail_value | return the first key of this dictionary given the value | return the first key of this dictionary given the value | [
"return",
"the",
"first",
"key",
"of",
"this",
"dictionary",
"given",
"the",
"value"
] | def get_first_key_for_value(self, value, fail_value=None):
"""return the first key of this dictionary given the value"""
list_result = [item[0] for item in self.items() if item[1] == value]
if len(list_result) > 0:
return list_result[0]
return fail_value | [
"def",
"get_first_key_for_value",
"(",
"self",
",",
"value",
",",
"fail_value",
"=",
"None",
")",
":",
"list_result",
"=",
"[",
"item",
"[",
"0",
"]",
"for",
"item",
"in",
"self",
".",
"items",
"(",
")",
"if",
"item",
"[",
"1",
"]",
"==",
"value",
... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/examples/python/dict_utils.py#L18-L23 | |
arkenthera/electron-vibrancy | 383153ef9ccb23a6c7517150d6bb0794dff3115e | scripts/cpplint.py | python | IsInitializerList | (clean_lines, linenum) | return False | Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise. | Check if current line is inside constructor initializer list. | [
"Check",
"if",
"current",
"line",
"is",
"inside",
"constructor",
"initializer",
"list",
"."
] | def IsInitializerList(clean_lines, linenum):
"""Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise.
"""
for i in xrange(linenum, 1, -1):
line = clean_lines.elided[i]
if i == linenum:
remove_function_body = Match(r'^(.*)\{\s*$', line)
if remove_function_body:
line = remove_function_body.group(1)
if Search(r'\s:\s*\w+[({]', line):
# A lone colon tend to indicate the start of a constructor
# initializer list. It could also be a ternary operator, which
# also tend to appear in constructor initializer lists as
# opposed to parameter lists.
return True
if Search(r'\}\s*,\s*$', line):
# A closing brace followed by a comma is probably the end of a
# brace-initialized member in constructor initializer list.
return True
if Search(r'[{};]\s*$', line):
# Found one of the following:
# - A closing brace or semicolon, probably the end of the previous
# function.
# - An opening brace, probably the start of current class or namespace.
#
# Current line is probably not inside an initializer list since
# we saw one of those things without seeing the starting colon.
return False
# Got to the beginning of the file without seeing the start of
# constructor initializer list.
return False | [
"def",
"IsInitializerList",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"1",
",",
"-",
"1",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
"if",
"i",
"==",
"linenum",
":",
"rem... | https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L4529-L4568 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/dummy_thread.py | python | exit | () | Dummy implementation of thread.exit(). | Dummy implementation of thread.exit(). | [
"Dummy",
"implementation",
"of",
"thread",
".",
"exit",
"()",
"."
] | def exit():
"""Dummy implementation of thread.exit()."""
raise SystemExit | [
"def",
"exit",
"(",
")",
":",
"raise",
"SystemExit"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/dummy_thread.py#L58-L60 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/namespace.py | python | namespace_t.free_operator | (
self,
name=None,
function=None,
symbol=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None) | return (
self._find_single(
scopedef.scopedef_t._impl_matchers[namespace_t.free_operator],
name=self._build_operator_name(name, function, symbol),
symbol=symbol,
function=self._build_operator_function(name, function),
decl_type=self._impl_decl_types[namespace_t.free_operator],
return_type=return_type,
arg_types=arg_types,
header_dir=header_dir,
header_file=header_file,
recursive=recursive)
) | Returns reference to free operator declaration that matches
a defined criteria. | Returns reference to free operator declaration that matches
a defined criteria. | [
"Returns",
"reference",
"to",
"free",
"operator",
"declaration",
"that",
"matches",
"a",
"defined",
"criteria",
"."
] | def free_operator(
self,
name=None,
function=None,
symbol=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None):
"""
Returns reference to free operator declaration that matches
a defined criteria.
"""
return (
self._find_single(
scopedef.scopedef_t._impl_matchers[namespace_t.free_operator],
name=self._build_operator_name(name, function, symbol),
symbol=symbol,
function=self._build_operator_function(name, function),
decl_type=self._impl_decl_types[namespace_t.free_operator],
return_type=return_type,
arg_types=arg_types,
header_dir=header_dir,
header_file=header_file,
recursive=recursive)
) | [
"def",
"free_operator",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"symbol",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",... | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/namespace.py#L203-L230 | |
merryhime/dynarmic | a8cbfd9af4f3f3cdad6efcd067e76edec76c1338 | externals/vixl/vixl/tools/verify_assembler_traces.py | python | ConvertToLLVMFormat | (vixl_instruction, triple) | Take an string representing an instruction and convert it to assembly syntax
for LLVM. VIXL's test generation framework will print instruction
representations as a space seperated list. The first element is the mnemonic
and the following elements are operands. | Take an string representing an instruction and convert it to assembly syntax
for LLVM. VIXL's test generation framework will print instruction
representations as a space seperated list. The first element is the mnemonic
and the following elements are operands. | [
"Take",
"an",
"string",
"representing",
"an",
"instruction",
"and",
"convert",
"it",
"to",
"assembly",
"syntax",
"for",
"LLVM",
".",
"VIXL",
"s",
"test",
"generation",
"framework",
"will",
"print",
"instruction",
"representations",
"as",
"a",
"space",
"seperated... | def ConvertToLLVMFormat(vixl_instruction, triple):
"""
Take an string representing an instruction and convert it to assembly syntax
for LLVM. VIXL's test generation framework will print instruction
representations as a space seperated list. The first element is the mnemonic
and the following elements are operands.
"""
def DtUntypedToLLVM(matches):
dt = ""
if matches[1] == "untyped8":
dt = "8"
elif matches[1] == "untyped16":
dt = "16"
elif matches[1] == "untyped32":
dt = "32"
else:
raise Exception()
return "{}.{} {}, {}, {}".format(matches[0], dt, matches[2], matches[3], matches[4])
# Dictionnary of patterns. The key is an identifier used in
# `llvm_mc_instruction_converters` below. The value needs to be a capturing
# regular expression.
pattern_matchers = {
# Allow an optional underscore in case this an "and" instruction.
"mnemonic": "(\w+?)_?",
"condition":
"(al|eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le)",
"register":
"(r0|r1|r2|r3|r4|r5|r6|r7|r8|r9|r10|r11|r12|r13|r14|r15|pc|sp|lr)",
"immediate": "(0x[0-9a-f]+|[0-9]+)",
"shift": "(lsl|lsr|asr|ror)",
"dregister": "(d[0-9]|d[12][0-9]|d3[01])",
"dt": "(s8|s16|s32|s64|u8|u16|u32|u64|f16|f32|f64|i8|i16|i32|i64|p8|p64)",
"dt_untyped": "(untyped8|untyped16|untyped32)"
}
# List of converters. Each of them represents an instruction form and what to
# convert it to. This list needs to be complete; an exception is raised if we
# couldn't find a converter for the instruction.
#
# The first part of each tuple is a pattern to match. It's simply a regular
# expression. Additionally, each identifier in curly braces is replaced by the
# corresponding pattern from `pattern_matchers`.
#
# The second part of the tuple is a string that describes what the result will
# look like. Empty curly braces are replaced by matches, in order.
llvm_mc_instruction_converters = [
("it {condition}", "it {}"),
("{mnemonic} {condition} {register} {immediate}",
"{}{} {}, #{}"),
("{mnemonic} {condition} {register} {register} {immediate}",
"{}{} {}, {}, #{}"),
("{mnemonic} {condition} {register} {register}",
"{}{} {}, {}"),
("{mnemonic} {condition} {register} {register} {register}",
"{}{} {}, {}, {}"),
("{mnemonic} {register} {register} {register}",
"{} {}, {}, {}"),
("{mnemonic} {condition} {register} {register} {immediate}",
"{}{} {}, {}, #{}"),
("{mnemonic} {condition} {register} {register} {register} {shift} "
"{immediate}",
"{}{} {}, {}, {}, {} #{}"),
("{mnemonic} {condition} {register} {register} {register} {shift} "
"{register}",
"{}{} {}, {}, {}, {} {}"),
("{mnemonic} {condition} {register} {register} {shift} {immediate}",
"{}{} {}, {}, {} #{}"),
("{mnemonic} {condition} {register} {register} {shift} {register}",
"{}{} {}, {}, {} {}"),
("{mnemonic} {condition} {register} {register} plus {immediate} offset",
"{}{} {}, [{}, #{}]"),
("{mnemonic} {condition} {register} {register} minus {immediate} offset",
"{}{} {}, [{}, #-{}]"),
("{mnemonic} {condition} {register} {register} plus {immediate} postindex",
"{}{} {}, [{}], #{}"),
("{mnemonic} {condition} {register} {register} minus {immediate} "
"postindex",
"{}{} {}, [{}], #-{}"),
("{mnemonic} {condition} {register} {register} plus {immediate} preindex",
"{}{} {}, [{}, #{}]!"),
("{mnemonic} {condition} {register} {register} minus {immediate} "
"preindex",
"{}{} {}, [{}, #-{}]!"),
("{mnemonic} {condition} {register} {register} plus {register} offset",
"{}{} {}, [{}, {}]"),
("{mnemonic} {condition} {register} {register} minus {register} offset",
"{}{} {}, [{}, -{}]"),
("{mnemonic} {condition} {register} {register} plus {register} postindex",
"{}{} {}, [{}], {}"),
("{mnemonic} {condition} {register} {register} minus {register} "
"postindex",
"{}{} {}, [{}], -{}"),
("{mnemonic} {condition} {register} {register} plus {register} preindex",
"{}{} {}, [{}, {}]!"),
("{mnemonic} {condition} {register} {register} minus {register} preindex",
"{}{} {}, [{}, -{}]!"),
("{mnemonic} {condition} {register} {register} plus {register} {shift} "
"{immediate} offset",
"{}{} {}, [{}, {}, {} #{}]"),
("{mnemonic} {condition} {register} {register} minus {register} {shift} "
"{immediate} offset",
"{}{} {}, [{}, -{}, {} #{}]"),
("{mnemonic} {condition} {register} {register} plus {register} {shift} "
"{immediate} postindex",
"{}{} {}, [{}], {}, {} #{}"),
("{mnemonic} {condition} {register} {register} minus {register} {shift} "
"{immediate} postindex",
"{}{} {}, [{}], -{}, {} #{}"),
("{mnemonic} {condition} {register} {register} plus {register} {shift} "
"{immediate} preindex",
"{}{} {}, [{}, {}, {} #{}]!"),
("{mnemonic} {condition} {register} {register} minus {register} {shift} "
"{immediate} preindex",
"{}{} {}, [{}, -{}, {} #{}]!"),
("{mnemonic} {dt} {dregister} {dregister} {dregister}",
"{}.{} {}, {}, {}"),
("{mnemonic} {dt_untyped} {dregister} {dregister} {dregister}", DtUntypedToLLVM)
]
# Work around issues in LLVM 3.8.
if triple == "thumbv8":
def ConvertMovRdImm(matches):
"""
LLVM chooses the T3 encoding for `mov <rd>, #<immediate>` when the
immediate fits both into a modified immediate (T2 encoding) and 16
bits (T3 encoding). Adding the `.W` modifier forces the T2 encoding to
be used.
"""
# The immediate is the second capture in "mov al {register} {immediate}".
imm = int(matches[1], 16)
if imm <= 0xffff:
lsb = imm & -imm
if (imm >> 8) < lsb:
return "mov.w {}, #{}".format(*matches)
# Fall back to a LLVM making the right decision.
return "mov {}, #{}".format(*matches)
llvm_mc_instruction_converters[:0] = [
# The ARM ARM specifies that if <Rn> is PC in either an ADD or SUB
# instruction with an immediate, the assembler should use the ADR
# encoding. LLVM does not know about this subtlety. We get around this
# by manually translating the instruction to their ADR form.
("add al {register} pc {immediate}", "adr {}, #{}"),
("sub al {register} pc {immediate}", "adr {}, #-{}"),
# LLVM is (rightfully) being helpful by swapping register operands so
# that the 16 bit encoding of the following instructions is used.
# However, VIXL does not do this. These rules specifically add the `.w`
# modifier to force LLVM to use the 32 bit encoding if the last register
# is identical to first one. But at the same time, we should still use
# the narrow encoding if all registers are the same.
("adcs al {register} (\\1) (\\1)", "adcs.n {}, {}, {}"),
("adcs al {register} {register} (\\1)", "adcs.w {}, {}, {}"),
("orrs al {register} (\\1) (\\1)", "orrs.n {}, {}, {}"),
("orrs al {register} {register} (\\1)", "orrs.w {}, {}, {}"),
("eors al {register} (\\1) (\\1)", "eors.n {}, {}, {}"),
("eors al {register} {register} (\\1)", "eors.w {}, {}, {}"),
("ands al {register} (\\1) (\\1)", "ands.n {}, {}, {}"),
("ands al {register} {register} (\\1)", "ands.w {}, {}, {}"),
# Solve the same issue as for the previous rules, however, we need to
# take into account that ADD instructions with the stack pointer have
# additional 16 bit forms.
("add al {register} (\\1) (\\1)", "add.n {}, {}, {}"),
("add al {register} (\\1) r13", "add.w {}, {}, sp"),
("add al {register} r13 (\\1)", "add.n {}, sp, {}"),
("add al {register} {register} (\\1)", "add.w {}, {}, {}"),
("mov al {register} {immediate}", ConvertMovRdImm)
]
# Our test generator framework uses mnemonics starting with a capital letters.
# We need everythin to be lower case for LLVM.
vixl_instruction = vixl_instruction.lower()
llvm_instruction = []
# VIXL may have generated more than one instruction seperated by ';'
# (an IT instruction for example).
for instruction in vixl_instruction.split(';'):
# Strip out extra white spaces.
instruction = instruction.strip()
# Try all converters in the list.
for pattern, result in llvm_mc_instruction_converters:
# Build the regular expression for this converter.
instruction_matcher = "^" + pattern.format(**pattern_matchers) + "$"
match = re.match(instruction_matcher, instruction)
if match:
# If we have a match, the object will contain a tuple of substrings.
if isinstance(result, types.FunctionType):
# `result` is a function, call it produce the instruction.
llvm_instruction.append(result(match.groups()))
else:
# `result` is a string, use it as the format string.
assert(isinstance(result, str))
llvm_instruction.append(result.format(*match.groups()))
break
if llvm_instruction:
return "\n".join(llvm_instruction)
# No converters worked so raise an exception.
raise Exception("Unsupported instruction {}.".format(instruction)) | [
"def",
"ConvertToLLVMFormat",
"(",
"vixl_instruction",
",",
"triple",
")",
":",
"def",
"DtUntypedToLLVM",
"(",
"matches",
")",
":",
"dt",
"=",
"\"\"",
"if",
"matches",
"[",
"1",
"]",
"==",
"\"untyped8\"",
":",
"dt",
"=",
"\"8\"",
"elif",
"matches",
"[",
... | https://github.com/merryhime/dynarmic/blob/a8cbfd9af4f3f3cdad6efcd067e76edec76c1338/externals/vixl/vixl/tools/verify_assembler_traces.py#L135-L337 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridPopulator.SetState | (*args, **kwargs) | return _propgrid.PropertyGridPopulator_SetState(*args, **kwargs) | SetState(self, state) | SetState(self, state) | [
"SetState",
"(",
"self",
"state",
")"
] | def SetState(*args, **kwargs):
"""SetState(self, state)"""
return _propgrid.PropertyGridPopulator_SetState(*args, **kwargs) | [
"def",
"SetState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridPopulator_SetState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L2578-L2580 | |
google/mozc | 7329757e1ad30e327c1ae823a8302c79482d6b9c | src/build_tools/zlib_util.py | python | _Write | (buf, filename) | Writes a buffer to a file in binary mode. | Writes a buffer to a file in binary mode. | [
"Writes",
"a",
"buffer",
"to",
"a",
"file",
"in",
"binary",
"mode",
"."
] | def _Write(buf, filename):
"""Writes a buffer to a file in binary mode."""
with open(filename, 'wb') as f:
f.write(buf) | [
"def",
"_Write",
"(",
"buf",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"buf",
")"
] | https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/build_tools/zlib_util.py#L45-L48 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | CheckBox.Create | (*args, **kwargs) | return _controls_.CheckBox_Create(*args, **kwargs) | Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=CheckBoxNameStr) -> bool
Actually create the GUI CheckBox for 2-phase creation. | Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=CheckBoxNameStr) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"String",
"label",
"=",
"EmptyString",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
"Validator",
"validator",
"=",
"DefaultValida... | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, Validator validator=DefaultValidator,
String name=CheckBoxNameStr) -> bool
Actually create the GUI CheckBox for 2-phase creation.
"""
return _controls_.CheckBox_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"CheckBox_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L356-L365 | |
bundy-dns/bundy | 3d41934996b82b0cd2fe22dd74d2abc1daba835d | src/lib/python/bundy/ddns/session.py | python | UpdateSession.__validate_error | (self, reason) | Used as error callback below. | Used as error callback below. | [
"Used",
"as",
"error",
"callback",
"below",
"."
] | def __validate_error(self, reason):
'''
Used as error callback below.
'''
logger.error(LIBDDNS_ZONE_INVALID_ERROR, self.__zname, self.__zclass,
reason) | [
"def",
"__validate_error",
"(",
"self",
",",
"reason",
")",
":",
"logger",
".",
"error",
"(",
"LIBDDNS_ZONE_INVALID_ERROR",
",",
"self",
".",
"__zname",
",",
"self",
".",
"__zclass",
",",
"reason",
")"
] | https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/ddns/session.py#L819-L824 | ||
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | hasher-matcher-actioner/hmalib/scripts/populate_config_db.py | python | load_defaults | (_args) | Load a hardcoded set of defaults which are useful in testing | Load a hardcoded set of defaults which are useful in testing | [
"Load",
"a",
"hardcoded",
"set",
"of",
"defaults",
"which",
"are",
"useful",
"in",
"testing"
] | def load_defaults(_args):
"""
Load a hardcoded set of defaults which are useful in testing
"""
# Could also put the default on the class, but seems too fancy
configs = [
ThreatExchangeConfig(
name="303636684709969",
fetcher_active=True,
privacy_group_name="Test Config 1",
write_back=True,
in_use=True,
description="test description",
matcher_active=True,
),
ThreatExchangeConfig(
name="258601789084078",
fetcher_active=True,
privacy_group_name="Test Config 2",
write_back=True,
in_use=True,
description="test description",
matcher_active=True,
),
WebhookPostActionPerformer(
name="EnqueueForReview",
url="https://webhook.site/ff7ebc37-514a-439e-9a03-46f86989e195",
headers='{"Connection":"keep-alive"}',
# monitoring page:
# https://webhook.site/#!/ff7ebc37-514a-439e-9a03-46f86989e195
),
WebhookPostActionPerformer(
name="EnqueueMiniCastleForReview",
url="https://webhook.site/01cef721-bdcc-4681-8430-679c75659867",
headers='{"Connection":"keep-alive"}',
# monitoring page:
# https://webhook.site/#!/01cef721-bdcc-4681-8430-679c75659867
),
WebhookPostActionPerformer(
name="EnqueueSailboatForReview",
url="https://webhook.site/fa5c5ad5-f5cc-4692-bf03-a03a4ae3f714",
headers='{"Connection":"keep-alive"}',
# monitoring page:
# https://webhook.site/#!/fa5c5ad5-f5cc-4692-bf03-a03a4ae3f714
),
ActionRule(
name="Enqueue Mini-Castle for Review",
action_label=ActionLabel("EnqueueMiniCastleForReview"),
must_have_labels=set(
[
BankIDClassificationLabel("303636684709969"),
ClassificationLabel("true_positive"),
]
),
must_not_have_labels=set(
[BankedContentIDClassificationLabel("3364504410306721")]
),
),
ActionRule(
name="Enqueue Sailboat for Review",
action_label=ActionLabel("EnqueueSailboatForReview"),
must_have_labels=set(
[
BankIDClassificationLabel("303636684709969"),
ClassificationLabel("true_positive"),
BankedContentIDClassificationLabel("3364504410306721"),
]
),
must_not_have_labels=set(),
),
]
for config in configs:
# Someday maybe can do filtering or something, I dunno
# Add try catch block to avoid test failure
try:
hmaconfig.create_config(config)
except ClientError as e:
if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
print(
"Can't insert duplicated config, " + e.response["Error"]["Message"],
)
else:
raise
print(config) | [
"def",
"load_defaults",
"(",
"_args",
")",
":",
"# Could also put the default on the class, but seems too fancy",
"configs",
"=",
"[",
"ThreatExchangeConfig",
"(",
"name",
"=",
"\"303636684709969\"",
",",
"fetcher_active",
"=",
"True",
",",
"privacy_group_name",
"=",
"\"T... | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/scripts/populate_config_db.py#L69-L156 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/distributions/python/ops/negative_binomial.py | python | NegativeBinomial.logits | (self) | return self._logits | Log-odds of a `1` outcome (vs `0`). | Log-odds of a `1` outcome (vs `0`). | [
"Log",
"-",
"odds",
"of",
"a",
"1",
"outcome",
"(",
"vs",
"0",
")",
"."
] | def logits(self):
"""Log-odds of a `1` outcome (vs `0`)."""
return self._logits | [
"def",
"logits",
"(",
"self",
")",
":",
"return",
"self",
".",
"_logits"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/negative_binomial.py#L116-L118 | |
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/text_format.py | python | Tokenizer.ParseError | (self, message) | return ParseError(message, self._line + 1, self._column + 1) | Creates and *returns* a ParseError for the current token. | Creates and *returns* a ParseError for the current token. | [
"Creates",
"and",
"*",
"returns",
"*",
"a",
"ParseError",
"for",
"the",
"current",
"token",
"."
] | def ParseError(self, message):
"""Creates and *returns* a ParseError for the current token."""
return ParseError(message, self._line + 1, self._column + 1) | [
"def",
"ParseError",
"(",
"self",
",",
"message",
")",
":",
"return",
"ParseError",
"(",
"message",
",",
"self",
".",
"_line",
"+",
"1",
",",
"self",
".",
"_column",
"+",
"1",
")"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/text_format.py#L1219-L1221 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/third_party/Python/module/six/six.py | python | add_metaclass | (metaclass) | return wrapper | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | [
"Class",
"decorator",
"for",
"creating",
"a",
"class",
"with",
"a",
"metaclass",
"."
] | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/six/six.py#L831-L844 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextObject.SetPosition | (*args, **kwargs) | return _richtext.RichTextObject_SetPosition(*args, **kwargs) | SetPosition(self, Point pos) | SetPosition(self, Point pos) | [
"SetPosition",
"(",
"self",
"Point",
"pos",
")"
] | def SetPosition(*args, **kwargs):
"""SetPosition(self, Point pos)"""
return _richtext.RichTextObject_SetPosition(*args, **kwargs) | [
"def",
"SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextObject_SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1297-L1299 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/trajectory.py | python | GeodesicHermiteTrajectory.eval | (self,t,endBehavior='halt') | return res[:len(res)//2] | Evaluates the configuration at time t | Evaluates the configuration at time t | [
"Evaluates",
"the",
"configuration",
"at",
"time",
"t"
] | def eval(self,t,endBehavior='halt'):
"""Evaluates the configuration at time t"""
self._skip_deriv = True
res = Trajectory.eval_state(self,t,endBehavior)
self._skip_deriv = False
return res[:len(res)//2] | [
"def",
"eval",
"(",
"self",
",",
"t",
",",
"endBehavior",
"=",
"'halt'",
")",
":",
"self",
".",
"_skip_deriv",
"=",
"True",
"res",
"=",
"Trajectory",
".",
"eval_state",
"(",
"self",
",",
"t",
",",
"endBehavior",
")",
"self",
".",
"_skip_deriv",
"=",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L1236-L1241 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/framework.py | python | cuda_places | (device_ids=None) | return [core.CUDAPlace(dev_id) for dev_id in device_ids] | **Note**:
For multi-card tasks, please use `FLAGS_selected_gpus` environment variable to set the visible GPU device.
The next version will fix the problem with `CUDA_VISIBLE_DEVICES` environment variable.
This function creates a list of :code:`paddle.CUDAPlace` objects.
If :code:`device_ids` is None, environment variable of
:code:`FLAGS_selected_gpus` would be checked first. For example, if
:code:`FLAGS_selected_gpus=0,1,2`, the returned list would
be [paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)].
If :code:`FLAGS_selected_gpus` is not set, all visible
gpu places would be returned according to the :code:`CUDA_VISIBLE_DEVICES` environment variable.
If :code:`device_ids` is not None, it should be the device
ids of GPUs. For example, if :code:`device_ids=[0,1,2]`,
the returned list would be
[paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)].
Parameters:
device_ids (list|tuple, optional): A list/tuple of int of GPU device ids.
Returns:
list of paddle.CUDAPlace: Created GPU place list.
Examples:
.. code-block:: python
import paddle
import paddle.static as static
# required: gpu
paddle.enable_static()
cuda_places = static.cuda_places() | **Note**:
For multi-card tasks, please use `FLAGS_selected_gpus` environment variable to set the visible GPU device.
The next version will fix the problem with `CUDA_VISIBLE_DEVICES` environment variable. | [
"**",
"Note",
"**",
":",
"For",
"multi",
"-",
"card",
"tasks",
"please",
"use",
"FLAGS_selected_gpus",
"environment",
"variable",
"to",
"set",
"the",
"visible",
"GPU",
"device",
".",
"The",
"next",
"version",
"will",
"fix",
"the",
"problem",
"with",
"CUDA_VI... | def cuda_places(device_ids=None):
"""
**Note**:
For multi-card tasks, please use `FLAGS_selected_gpus` environment variable to set the visible GPU device.
The next version will fix the problem with `CUDA_VISIBLE_DEVICES` environment variable.
This function creates a list of :code:`paddle.CUDAPlace` objects.
If :code:`device_ids` is None, environment variable of
:code:`FLAGS_selected_gpus` would be checked first. For example, if
:code:`FLAGS_selected_gpus=0,1,2`, the returned list would
be [paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)].
If :code:`FLAGS_selected_gpus` is not set, all visible
gpu places would be returned according to the :code:`CUDA_VISIBLE_DEVICES` environment variable.
If :code:`device_ids` is not None, it should be the device
ids of GPUs. For example, if :code:`device_ids=[0,1,2]`,
the returned list would be
[paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)].
Parameters:
device_ids (list|tuple, optional): A list/tuple of int of GPU device ids.
Returns:
list of paddle.CUDAPlace: Created GPU place list.
Examples:
.. code-block:: python
import paddle
import paddle.static as static
# required: gpu
paddle.enable_static()
cuda_places = static.cuda_places()
"""
assert core.is_compiled_with_cuda(), \
"Not compiled with CUDA"
if device_ids is None:
device_ids = _cuda_ids()
elif not isinstance(device_ids, (list, tuple)):
device_ids = [device_ids]
return [core.CUDAPlace(dev_id) for dev_id in device_ids] | [
"def",
"cuda_places",
"(",
"device_ids",
"=",
"None",
")",
":",
"assert",
"core",
".",
"is_compiled_with_cuda",
"(",
")",
",",
"\"Not compiled with CUDA\"",
"if",
"device_ids",
"is",
"None",
":",
"device_ids",
"=",
"_cuda_ids",
"(",
")",
"elif",
"not",
"isinst... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/framework.py#L619-L664 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Log.SetVerbose | (*args, **kwargs) | return _misc_.Log_SetVerbose(*args, **kwargs) | SetVerbose(bool bVerbose=True) | SetVerbose(bool bVerbose=True) | [
"SetVerbose",
"(",
"bool",
"bVerbose",
"=",
"True",
")"
] | def SetVerbose(*args, **kwargs):
"""SetVerbose(bool bVerbose=True)"""
return _misc_.Log_SetVerbose(*args, **kwargs) | [
"def",
"SetVerbose",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Log_SetVerbose",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1496-L1498 | |
EricLYang/courseRepo | 60679ec7ec130fe0cff9d26b704f1e286e5fde13 | 1_Introduction/build/catkin_generated/installspace/_setup_util.py | python | prepend_env_variables | (environ, env_var_subfolders, workspaces) | return lines | Generate shell code to prepend environment variables
for the all workspaces. | Generate shell code to prepend environment variables
for the all workspaces. | [
"Generate",
"shell",
"code",
"to",
"prepend",
"environment",
"variables",
"for",
"the",
"all",
"workspaces",
"."
] | def prepend_env_variables(environ, env_var_subfolders, workspaces):
'''
Generate shell code to prepend environment variables
for the all workspaces.
'''
lines = []
lines.append(comment('prepend folders of workspaces to environment variables'))
paths = [path for path in workspaces.split(os.pathsep) if path]
prefix = _prefix_env_variable(environ, 'CMAKE_PREFIX_PATH', paths, '')
lines.append(prepend(environ, 'CMAKE_PREFIX_PATH', prefix))
for key in sorted([key for key in env_var_subfolders.keys() if key != 'CMAKE_PREFIX_PATH']):
subfolder = env_var_subfolders[key]
prefix = _prefix_env_variable(environ, key, paths, subfolder)
lines.append(prepend(environ, key, prefix))
return lines | [
"def",
"prepend_env_variables",
"(",
"environ",
",",
"env_var_subfolders",
",",
"workspaces",
")",
":",
"lines",
"=",
"[",
"]",
"lines",
".",
"append",
"(",
"comment",
"(",
"'prepend folders of workspaces to environment variables'",
")",
")",
"paths",
"=",
"[",
"p... | https://github.com/EricLYang/courseRepo/blob/60679ec7ec130fe0cff9d26b704f1e286e5fde13/1_Introduction/build/catkin_generated/installspace/_setup_util.py#L130-L147 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/profileapp.py | python | ProfileList._print_profiles | (self, profiles) | print list of profiles, indented. | print list of profiles, indented. | [
"print",
"list",
"of",
"profiles",
"indented",
"."
] | def _print_profiles(self, profiles):
"""print list of profiles, indented."""
for profile in profiles:
print(' %s' % profile) | [
"def",
"_print_profiles",
"(",
"self",
",",
"profiles",
")",
":",
"for",
"profile",
"in",
"profiles",
":",
"print",
"(",
"' %s'",
"%",
"profile",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/profileapp.py#L159-L162 | ||
lighttransport/nanort | 74063967336311f54ede5dffdfa242123825033b | deps/cpplint.py | python | CheckForFunctionLengths | (filename, clean_lines, linenum,
function_state, error) | Reports for long function bodies.
For an overview why this is done, see:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found. | Reports for long function bodies. | [
"Reports",
"for",
"long",
"function",
"bodies",
"."
] | def CheckForFunctionLengths(filename, clean_lines, linenum,
function_state, error):
"""Reports for long function bodies.
For an overview why this is done, see:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found.
"""
lines = clean_lines.lines
line = lines[linenum]
joined_line = ''
starting_func = False
regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
match_result = Match(regexp, line)
if match_result:
# If the name is all caps and underscores, figure it's a macro and
# ignore it, unless it's TEST or TEST_F.
function_name = match_result.group(1).split()[-1]
if function_name == 'TEST' or function_name == 'TEST_F' or (
not Match(r'[A-Z_]+$', function_name)):
starting_func = True
if starting_func:
body_found = False
for start_linenum in xrange(linenum, clean_lines.NumLines()):
start_line = lines[start_linenum]
joined_line += ' ' + start_line.lstrip()
if Search(r'(;|})', start_line): # Declarations and trivial functions
body_found = True
break # ... ignore
elif Search(r'{', start_line):
body_found = True
function = Search(r'((\w|:)*)\(', line).group(1)
if Match(r'TEST', function): # Handle TEST... macros
parameter_regexp = Search(r'(\(.*\))', joined_line)
if parameter_regexp: # Ignore bad syntax
function += parameter_regexp.group(1)
else:
function += '()'
function_state.Begin(function)
break
if not body_found:
# No body for the function (or evidence of a non-function) was found.
error(filename, linenum, 'readability/fn_size', 5,
'Lint failed to find start of function body.')
elif Match(r'^\}\s*$', line): # function end
function_state.Check(error, filename, linenum)
function_state.End()
elif not Match(r'^\s*$', line):
function_state.Count() | [
"def",
"CheckForFunctionLengths",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"function_state",
",",
"error",
")",
":",
"lines",
"=",
"clean_lines",
".",
"lines",
"line",
"=",
"lines",
"[",
"linenum",
"]",
"joined_line",
"=",
"''",
"starting_func... | https://github.com/lighttransport/nanort/blob/74063967336311f54ede5dffdfa242123825033b/deps/cpplint.py#L2842-L2907 | ||
citizenfx/fivem | 88276d40cc7baf8285d02754cc5ae42ec7a8563f | vendor/chromium/base/android/jni_generator/jni_generator.py | python | JavaTypeToProxyCast | (java_type) | return 'Object' + java_type[len(raw_type):] | Maps from a java type to the type used by the native proxy GEN_JNI class | Maps from a java type to the type used by the native proxy GEN_JNI class | [
"Maps",
"from",
"a",
"java",
"type",
"to",
"the",
"type",
"used",
"by",
"the",
"native",
"proxy",
"GEN_JNI",
"class"
] | def JavaTypeToProxyCast(java_type):
"""Maps from a java type to the type used by the native proxy GEN_JNI class"""
# All the types and array types of JAVA_TYPE_MAP become jobjectArray across
# jni but they still need to be passed as the original type on the java side.
raw_type = java_type.rstrip('[]')
if raw_type in JAVA_POD_TYPE_MAP or raw_type in JAVA_TYPE_MAP:
return java_type
# All other types should just be passed as Objects or Object arrays.
return 'Object' + java_type[len(raw_type):] | [
"def",
"JavaTypeToProxyCast",
"(",
"java_type",
")",
":",
"# All the types and array types of JAVA_TYPE_MAP become jobjectArray across",
"# jni but they still need to be passed as the original type on the java side.",
"raw_type",
"=",
"java_type",
".",
"rstrip",
"(",
"'[]'",
")",
"if... | https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/base/android/jni_generator/jni_generator.py#L201-L210 | |
NREL/EnergyPlus | fadc5973b85c70e8cc923efb69c144e808a26078 | src/EnergyPlus/api/runtime.py | python | Runtime.callback_progress | (self, state: c_void_p, f: FunctionType) | This function allows a client to register a function to be called back by EnergyPlus at the end of each
day with a progress (percentage) indicator
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:param f: A python function which takes an integer argument and returns nothing
:return: Nothing | This function allows a client to register a function to be called back by EnergyPlus at the end of each
day with a progress (percentage) indicator | [
"This",
"function",
"allows",
"a",
"client",
"to",
"register",
"a",
"function",
"to",
"be",
"called",
"back",
"by",
"EnergyPlus",
"at",
"the",
"end",
"of",
"each",
"day",
"with",
"a",
"progress",
"(",
"percentage",
")",
"indicator"
] | def callback_progress(self, state: c_void_p, f: FunctionType) -> None:
"""
This function allows a client to register a function to be called back by EnergyPlus at the end of each
day with a progress (percentage) indicator
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:param f: A python function which takes an integer argument and returns nothing
:return: Nothing
"""
self._check_callback_args(f, 1, 'callback_progress')
cb_ptr = self.py_progress_callback_type(f)
all_callbacks.append(cb_ptr)
self.api.registerProgressCallback(state, cb_ptr) | [
"def",
"callback_progress",
"(",
"self",
",",
"state",
":",
"c_void_p",
",",
"f",
":",
"FunctionType",
")",
"->",
"None",
":",
"self",
".",
"_check_callback_args",
"(",
"f",
",",
"1",
",",
"'callback_progress'",
")",
"cb_ptr",
"=",
"self",
".",
"py_progres... | https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/src/EnergyPlus/api/runtime.py#L300-L312 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | ShouldCheckNamespaceIndentation | (nesting_state, is_namespace_indent_item,
raw_lines_no_comments, linenum) | return IsBlockInNameSpace(nesting_state, is_forward_declaration) | This method determines if we should apply our namespace indentation check.
Args:
nesting_state: The current nesting state.
is_namespace_indent_item: If we just put a new class on the stack, True.
If the top of the stack is not a class, or we did not recently
add the class, False.
raw_lines_no_comments: The lines without the comments.
linenum: The current line number we are processing.
Returns:
True if we should apply our namespace indentation check. Currently, it
only works for classes and namespaces inside of a namespace. | This method determines if we should apply our namespace indentation check. | [
"This",
"method",
"determines",
"if",
"we",
"should",
"apply",
"our",
"namespace",
"indentation",
"check",
"."
] | def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
raw_lines_no_comments, linenum):
"""This method determines if we should apply our namespace indentation check.
Args:
nesting_state: The current nesting state.
is_namespace_indent_item: If we just put a new class on the stack, True.
If the top of the stack is not a class, or we did not recently
add the class, False.
raw_lines_no_comments: The lines without the comments.
linenum: The current line number we are processing.
Returns:
True if we should apply our namespace indentation check. Currently, it
only works for classes and namespaces inside of a namespace.
"""
is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
linenum)
if not (is_namespace_indent_item or is_forward_declaration):
return False
# If we are in a macro, we do not want to check the namespace indentation.
if IsMacroDefinition(raw_lines_no_comments, linenum):
return False
return IsBlockInNameSpace(nesting_state, is_forward_declaration) | [
"def",
"ShouldCheckNamespaceIndentation",
"(",
"nesting_state",
",",
"is_namespace_indent_item",
",",
"raw_lines_no_comments",
",",
"linenum",
")",
":",
"is_forward_declaration",
"=",
"IsForwardClassDeclaration",
"(",
"raw_lines_no_comments",
",",
"linenum",
")",
"if",
"not... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L5739-L5766 | |
nektra/Deviare-InProc | e88b91afff32b773b10deeb82a928c6d4af1a9c2 | NktHookLib/Src/libudis86/source/scripts/ud_opcode.py | python | UdOpcodeTables.map | (self, tbl, opcodes, obj) | Create a mapping from a given string of opcodes to an
object in the opcode trie. Constructs trie branches as
needed. | Create a mapping from a given string of opcodes to an
object in the opcode trie. Constructs trie branches as
needed. | [
"Create",
"a",
"mapping",
"from",
"a",
"given",
"string",
"of",
"opcodes",
"to",
"an",
"object",
"in",
"the",
"opcode",
"trie",
".",
"Constructs",
"trie",
"branches",
"as",
"needed",
"."
] | def map(self, tbl, opcodes, obj):
"""Create a mapping from a given string of opcodes to an
object in the opcode trie. Constructs trie branches as
needed.
"""
opc = opcodes[0]
e = tbl.lookup(opc)
if e is None:
tbl.add(opc, self.mkTrie(opcodes[1:], obj))
else:
if len(opcodes[1:]) == 0:
raise self.CollisionError(e, obj)
self.map(e, opcodes[1:], obj) | [
"def",
"map",
"(",
"self",
",",
"tbl",
",",
"opcodes",
",",
"obj",
")",
":",
"opc",
"=",
"opcodes",
"[",
"0",
"]",
"e",
"=",
"tbl",
".",
"lookup",
"(",
"opc",
")",
"if",
"e",
"is",
"None",
":",
"tbl",
".",
"add",
"(",
"opc",
",",
"self",
".... | https://github.com/nektra/Deviare-InProc/blob/e88b91afff32b773b10deeb82a928c6d4af1a9c2/NktHookLib/Src/libudis86/source/scripts/ud_opcode.py#L292-L304 | ||
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/gt_single_data_layer/minibatch.py | python | get_minibatch | (roidb, voxelizer, extents) | return blobs | Given a roidb, construct a minibatch sampled from it. | Given a roidb, construct a minibatch sampled from it. | [
"Given",
"a",
"roidb",
"construct",
"a",
"minibatch",
"sampled",
"from",
"it",
"."
] | def get_minibatch(roidb, voxelizer, extents):
"""Given a roidb, construct a minibatch sampled from it."""
num_images = len(roidb)
# Get the input image blob, formatted for tensorflow
random_scale_ind = npr.randint(0, high=len(cfg.TRAIN.SCALES_BASE))
im_blob, im_rescale_blob, im_depth_blob, im_normal_blob, im_scales = _get_image_blob(roidb, random_scale_ind)
# build the label blob
depth_blob, label_blob, meta_data_blob, vertex_target_blob, vertex_weight_blob, pose_blob, \
gan_z_blob = _get_label_blob(roidb, voxelizer, im_scales)
# For debug visualizations
if cfg.TRAIN.VISUALIZE:
_vis_minibatch(im_blob, im_depth_blob, depth_blob, label_blob, meta_data_blob, vertex_target_blob, pose_blob, extents)
blobs = {'data_image_color': im_blob,
'data_image_color_rescale': im_rescale_blob,
'data_image_depth': im_depth_blob,
'data_image_normal': im_normal_blob,
'data_label': label_blob,
'data_depth': depth_blob,
'data_meta_data': meta_data_blob,
'data_vertex_targets': vertex_target_blob,
'data_vertex_weights': vertex_weight_blob,
'data_pose': pose_blob,
'data_gan_z': gan_z_blob,
'data_extents': extents}
return blobs | [
"def",
"get_minibatch",
"(",
"roidb",
",",
"voxelizer",
",",
"extents",
")",
":",
"num_images",
"=",
"len",
"(",
"roidb",
")",
"# Get the input image blob, formatted for tensorflow",
"random_scale_ind",
"=",
"npr",
".",
"randint",
"(",
"0",
",",
"high",
"=",
"le... | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/gt_single_data_layer/minibatch.py#L22-L51 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/dist/commands.py | python | build_apps.copy_dependencies | (self, target_path, target_dir, search_path, referenced_by) | Copies the dependencies of target_path into target_dir. | Copies the dependencies of target_path into target_dir. | [
"Copies",
"the",
"dependencies",
"of",
"target_path",
"into",
"target_dir",
"."
] | def copy_dependencies(self, target_path, target_dir, search_path, referenced_by):
""" Copies the dependencies of target_path into target_dir. """
fp = open(target_path, 'rb+')
# What kind of magic does the file contain?
deps = []
magic = fp.read(4)
if magic.startswith(b'MZ'):
# It's a Windows DLL or EXE file.
pe = pefile.PEFile()
pe.read(fp)
for lib in pe.imports:
deps.append(lib)
elif magic == b'\x7FELF':
# Elf magic. Used on (among others) Linux and FreeBSD.
deps = self._read_dependencies_elf(fp, target_dir, search_path)
elif magic in (b'\xCE\xFA\xED\xFE', b'\xCF\xFA\xED\xFE'):
# A Mach-O file, as used on macOS.
deps = self._read_dependencies_macho(fp, '<', flatten=True)
elif magic in (b'\xFE\xED\xFA\xCE', b'\xFE\xED\xFA\xCF'):
rel_dir = os.path.relpath(target_dir, os.path.dirname(target_path))
deps = self._read_dependencies_macho(fp, '>', flatten=True)
elif magic in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\xCA'):
# A fat file, containing multiple Mach-O binaries. In the future,
# we may want to extract the one containing the architecture we
# are building for.
deps = self._read_dependencies_fat(fp, False, flatten=True)
elif magic in (b'\xCA\xFE\xBA\xBF', b'\xBF\xBA\xFE\xCA'):
# A 64-bit fat file.
deps = self._read_dependencies_fat(fp, True, flatten=True)
# If we discovered any dependencies, recursively add those.
for dep in deps:
self.add_dependency(dep, target_dir, search_path, referenced_by) | [
"def",
"copy_dependencies",
"(",
"self",
",",
"target_path",
",",
"target_dir",
",",
"search_path",
",",
"referenced_by",
")",
":",
"fp",
"=",
"open",
"(",
"target_path",
",",
"'rb+'",
")",
"# What kind of magic does the file contain?",
"deps",
"=",
"[",
"]",
"m... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/dist/commands.py#L1385-L1424 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/io.py | python | IOBase.readlines | (self, hint=None) | return lines | Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint. | Return a list of lines from the stream. | [
"Return",
"a",
"list",
"of",
"lines",
"from",
"the",
"stream",
"."
] | def readlines(self, hint=None):
"""Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
"""
if hint is None:
hint = -1
if not isinstance(hint, (int, long)):
raise TypeError("hint must be an integer")
if hint <= 0:
return list(self)
n = 0
lines = []
for line in self:
lines.append(line)
n += len(line)
if n >= hint:
break
return lines | [
"def",
"readlines",
"(",
"self",
",",
"hint",
"=",
"None",
")",
":",
"if",
"hint",
"is",
"None",
":",
"hint",
"=",
"-",
"1",
"if",
"not",
"isinstance",
"(",
"hint",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"hint m... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/io.py#L538-L558 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/calendar.py | python | GenericCalendarCtrl.GetYearControl | (*args, **kwargs) | return _calendar.GenericCalendarCtrl_GetYearControl(*args, **kwargs) | GetYearControl(self) -> Control
Get the currently shown control for year. | GetYearControl(self) -> Control | [
"GetYearControl",
"(",
"self",
")",
"-",
">",
"Control"
] | def GetYearControl(*args, **kwargs):
"""
GetYearControl(self) -> Control
Get the currently shown control for year.
"""
return _calendar.GenericCalendarCtrl_GetYearControl(*args, **kwargs) | [
"def",
"GetYearControl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"GenericCalendarCtrl_GetYearControl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/calendar.py#L565-L571 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py | python | GenerateCopyrightHeader | () | return COPYRIGHT_HEADER_TEMPLATE % datetime.date.today().year | Generates the copyright header for JavaScript code. | Generates the copyright header for JavaScript code. | [
"Generates",
"the",
"copyright",
"header",
"for",
"JavaScript",
"code",
"."
] | def GenerateCopyrightHeader():
"""Generates the copyright header for JavaScript code."""
return COPYRIGHT_HEADER_TEMPLATE % datetime.date.today().year | [
"def",
"GenerateCopyrightHeader",
"(",
")",
":",
"return",
"COPYRIGHT_HEADER_TEMPLATE",
"%",
"datetime",
".",
"date",
".",
"today",
"(",
")",
".",
"year"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py#L439-L441 | |
manticoresoftware/manticoresearch | f675d16267543d934ce84074f087d13496ec462c | api/sphinxapi.py | python | SphinxClient.SetMaxQueryTime | (self, maxquerytime) | Set maximum query time, in milliseconds, per-index. 0 means 'do not limit'. | Set maximum query time, in milliseconds, per-index. 0 means 'do not limit'. | [
"Set",
"maximum",
"query",
"time",
"in",
"milliseconds",
"per",
"-",
"index",
".",
"0",
"means",
"do",
"not",
"limit",
"."
] | def SetMaxQueryTime (self, maxquerytime):
"""
Set maximum query time, in milliseconds, per-index. 0 means 'do not limit'.
"""
assert(isinstance(maxquerytime,int) and maxquerytime>0)
self._maxquerytime = maxquerytime | [
"def",
"SetMaxQueryTime",
"(",
"self",
",",
"maxquerytime",
")",
":",
"assert",
"(",
"isinstance",
"(",
"maxquerytime",
",",
"int",
")",
"and",
"maxquerytime",
">",
"0",
")",
"self",
".",
"_maxquerytime",
"=",
"maxquerytime"
] | https://github.com/manticoresoftware/manticoresearch/blob/f675d16267543d934ce84074f087d13496ec462c/api/sphinxapi.py#L358-L363 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/function.py | python | _FuncGraph.capture | (self, tensor, name=None) | Adds the given tensor to this graph and returns the captured tensor. | Adds the given tensor to this graph and returns the captured tensor. | [
"Adds",
"the",
"given",
"tensor",
"to",
"this",
"graph",
"and",
"returns",
"the",
"captured",
"tensor",
"."
] | def capture(self, tensor, name=None):
"""Adds the given tensor to this graph and returns the captured tensor."""
if tensor.ref() in self._captured:
# Captured already.
return self._captured[tensor.ref()]
elif self._capture_by_value:
return self._add_tensor_and_parents(tensor)
else:
return self._capture_tensor_as_extra_input(tensor, name) | [
"def",
"capture",
"(",
"self",
",",
"tensor",
",",
"name",
"=",
"None",
")",
":",
"if",
"tensor",
".",
"ref",
"(",
")",
"in",
"self",
".",
"_captured",
":",
"# Captured already.",
"return",
"self",
".",
"_captured",
"[",
"tensor",
".",
"ref",
"(",
")... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/function.py#L827-L835 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/sdata.py | python | SDataByAngle.get_empty | (cls: SDBA, *,
angles: Sequence[float],
frequencies: np.ndarray,
atom_keys: Sequence[str],
order_keys: Sequence[str],
**kwargs) | return cls(data=data, angles=angles, frequencies=frequencies, **kwargs) | Construct data container with zeroed arrays of appropriate dimensions
This is useful as a starting point for accumulating data in a loop.
Args:
angles: inelastic scattering angles
frequencies: inelastic scattering energies
atom_keys:
keys for atom data sets, corresponding to keys of ``data=``
init argument of SData() of SDataByAngle(). Usually this is
['atom_0', 'atom_1', ...]
order_keys:
keys for quantum order
**kwargs:
remaining keyword arguments will be passed to class constructor
(Usually these would be ``temperature=`` and ``sample_form=``.)
Returns:
Empty data collection with appropriate dimensions and metadata | Construct data container with zeroed arrays of appropriate dimensions | [
"Construct",
"data",
"container",
"with",
"zeroed",
"arrays",
"of",
"appropriate",
"dimensions"
] | def get_empty(cls: SDBA, *,
angles: Sequence[float],
frequencies: np.ndarray,
atom_keys: Sequence[str],
order_keys: Sequence[str],
**kwargs) -> SDBA:
"""Construct data container with zeroed arrays of appropriate dimensions
This is useful as a starting point for accumulating data in a loop.
Args:
angles: inelastic scattering angles
frequencies: inelastic scattering energies
atom_keys:
keys for atom data sets, corresponding to keys of ``data=``
init argument of SData() of SDataByAngle(). Usually this is
['atom_0', 'atom_1', ...]
order_keys:
keys for quantum order
**kwargs:
remaining keyword arguments will be passed to class constructor
(Usually these would be ``temperature=`` and ``sample_form=``.)
Returns:
Empty data collection with appropriate dimensions and metadata
"""
n_angles, n_frequencies = len(angles), len(frequencies)
data = {atom_key: {'s': {order_key: np.zeros((n_angles, n_frequencies))
for order_key in order_keys}}
for atom_key in atom_keys}
return cls(data=data, angles=angles, frequencies=frequencies, **kwargs) | [
"def",
"get_empty",
"(",
"cls",
":",
"SDBA",
",",
"*",
",",
"angles",
":",
"Sequence",
"[",
"float",
"]",
",",
"frequencies",
":",
"np",
".",
"ndarray",
",",
"atom_keys",
":",
"Sequence",
"[",
"str",
"]",
",",
"order_keys",
":",
"Sequence",
"[",
"str... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/sdata.py#L469-L507 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm._define_partial_maximization_operation | (self, shard_id, shard) | Computes the partial statistics of the means and covariances.
Args:
shard_id: current shard id.
shard: current data shard, 1 X num_examples X dimensions. | Computes the partial statistics of the means and covariances. | [
"Computes",
"the",
"partial",
"statistics",
"of",
"the",
"means",
"and",
"covariances",
"."
] | def _define_partial_maximization_operation(self, shard_id, shard):
"""Computes the partial statistics of the means and covariances.
Args:
shard_id: current shard id.
shard: current data shard, 1 X num_examples X dimensions.
"""
# Soft assignment of each data point to each of the two clusters.
self._points_in_k[shard_id] = tf.reduce_sum(self._w[shard_id], 0,
keep_dims=True)
# Partial means.
w_mul_x = tf.expand_dims(
tf.matmul(self._w[shard_id],
tf.squeeze(shard, [0]), transpose_a=True), 1)
self._w_mul_x.append(w_mul_x)
# Partial covariances.
x = tf.concat(0, [shard for _ in range(self._num_classes)])
x_trans = tf.transpose(x, perm=[0, 2, 1])
x_mul_w = tf.concat(0, [
tf.expand_dims(x_trans[k, :, :] * self._w[shard_id][:, k], 0)
for k in range(self._num_classes)])
self._w_mul_x2.append(tf.batch_matmul(x_mul_w, x)) | [
"def",
"_define_partial_maximization_operation",
"(",
"self",
",",
"shard_id",
",",
"shard",
")",
":",
"# Soft assignment of each data point to each of the two clusters.",
"self",
".",
"_points_in_k",
"[",
"shard_id",
"]",
"=",
"tf",
".",
"reduce_sum",
"(",
"self",
".",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L307-L328 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/api.py | python | put | (url, data=None, **kwargs) | return request('put', url, data=data, **kwargs) | r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response | r"""Sends a PUT request. | [
"r",
"Sends",
"a",
"PUT",
"request",
"."
] | def put(url, data=None, **kwargs):
r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('put', url, data=data, **kwargs) | [
"def",
"put",
"(",
"url",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"request",
"(",
"'put'",
",",
"url",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/api.py#L122-L134 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/output/base.py | python | Output.erase_down | (self) | Erases the screen from the current line down to the bottom of the
screen. | Erases the screen from the current line down to the bottom of the
screen. | [
"Erases",
"the",
"screen",
"from",
"the",
"current",
"line",
"down",
"to",
"the",
"bottom",
"of",
"the",
"screen",
"."
] | def erase_down(self) -> None:
"""
Erases the screen from the current line down to the bottom of the
screen.
""" | [
"def",
"erase_down",
"(",
"self",
")",
"->",
"None",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/base.py#L94-L98 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vcs/__init__.py | python | VersionControl.normalize_url | (self, url) | return urllib.unquote(url).rstrip('/') | Normalize a URL for comparison by unquoting it and removing any trailing slash. | Normalize a URL for comparison by unquoting it and removing any trailing slash. | [
"Normalize",
"a",
"URL",
"for",
"comparison",
"by",
"unquoting",
"it",
"and",
"removing",
"any",
"trailing",
"slash",
"."
] | def normalize_url(self, url):
"""
Normalize a URL for comparison by unquoting it and removing any trailing slash.
"""
return urllib.unquote(url).rstrip('/') | [
"def",
"normalize_url",
"(",
"self",
",",
"url",
")",
":",
"return",
"urllib",
".",
"unquote",
"(",
"url",
")",
".",
"rstrip",
"(",
"'/'",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vcs/__init__.py#L140-L144 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/SubSequence.py | python | SubSequence.start_pos | (self) | return self._internal.get_start_pos() | Gets the starting position. | Gets the starting position. | [
"Gets",
"the",
"starting",
"position",
"."
] | def start_pos(self):
"""Gets the starting position.
"""
return self._internal.get_start_pos() | [
"def",
"start_pos",
"(",
"self",
")",
":",
"return",
"self",
".",
"_internal",
".",
"get_start_pos",
"(",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/SubSequence.py#L63-L66 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/util/screenshot.py | python | TryCaptureScreenShot | (platform, tab=None) | If the platform or tab supports screenshot, attempt to take a screenshot
of the current browser.
Args:
platform: current platform
tab: browser tab if available
Returns:
file handle of the tempoerary file path for the screenshot if
present, None otherwise. | If the platform or tab supports screenshot, attempt to take a screenshot
of the current browser. | [
"If",
"the",
"platform",
"or",
"tab",
"supports",
"screenshot",
"attempt",
"to",
"take",
"a",
"screenshot",
"of",
"the",
"current",
"browser",
"."
] | def TryCaptureScreenShot(platform, tab=None):
""" If the platform or tab supports screenshot, attempt to take a screenshot
of the current browser.
Args:
platform: current platform
tab: browser tab if available
Returns:
file handle of the tempoerary file path for the screenshot if
present, None otherwise.
"""
try:
# TODO(nednguyen): once all platforms support taking screenshot,
# remove the tab checking logic and consider moving this to story_runner.
# (crbug.com/369490)
if platform.CanTakeScreenshot():
tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
tf.close()
platform.TakeScreenshot(tf.name)
return file_handle.FromTempFile(tf)
elif tab and tab.IsAlive() and tab.screenshot_supported:
tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
tf.close()
image = tab.Screenshot()
image_util.WritePngFile(image, tf.name)
return file_handle.FromTempFile(tf)
else:
logging.warning(
'Either tab has crashed or browser does not support taking tab '
'screenshot. Skip taking screenshot on failure.')
return None
except Exception as e:
logging.warning('Exception when trying to capture screenshot: %s', repr(e))
return None | [
"def",
"TryCaptureScreenShot",
"(",
"platform",
",",
"tab",
"=",
"None",
")",
":",
"try",
":",
"# TODO(nednguyen): once all platforms support taking screenshot,",
"# remove the tab checking logic and consider moving this to story_runner.",
"# (crbug.com/369490)",
"if",
"platform",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/util/screenshot.py#L16-L50 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distro.py | python | LinuxDistribution.linux_distribution | (self, full_distribution_name=True) | return (
self.name() if full_distribution_name else self.id(),
self.version(),
self.codename()
) | Return information about the OS distribution that is compatible
with Python's :func:`platform.linux_distribution`, supporting a subset
of its parameters.
For details, see :func:`distro.linux_distribution`. | Return information about the OS distribution that is compatible
with Python's :func:`platform.linux_distribution`, supporting a subset
of its parameters. | [
"Return",
"information",
"about",
"the",
"OS",
"distribution",
"that",
"is",
"compatible",
"with",
"Python",
"s",
":",
"func",
":",
"platform",
".",
"linux_distribution",
"supporting",
"a",
"subset",
"of",
"its",
"parameters",
"."
] | def linux_distribution(self, full_distribution_name=True):
"""
Return information about the OS distribution that is compatible
with Python's :func:`platform.linux_distribution`, supporting a subset
of its parameters.
For details, see :func:`distro.linux_distribution`.
"""
return (
self.name() if full_distribution_name else self.id(),
self.version(),
self.codename()
) | [
"def",
"linux_distribution",
"(",
"self",
",",
"full_distribution_name",
"=",
"True",
")",
":",
"return",
"(",
"self",
".",
"name",
"(",
")",
"if",
"full_distribution_name",
"else",
"self",
".",
"id",
"(",
")",
",",
"self",
".",
"version",
"(",
")",
",",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distro.py#L671-L683 | |
pskun/finance_news_analysis | 6ac13e32deede37a4cf57bba8b2897941ae3d80d | preprocess/news_preprocess_handler.py | python | NewsPreprocessHandler.insert_keyword_info | (self, news_id, data) | 插入新闻正文关键词数据 | 插入新闻正文关键词数据 | [
"插入新闻正文关键词数据"
] | def insert_keyword_info(self, news_id, data):
''' 插入新闻正文关键词数据 '''
news_keywords = data.get('all_type_keywords')
if news_keywords is not None:
# 如果提取出了关键字
for kw_type in news_keywords:
# 对每种关键字类型
for keyword in news_keywords[kw_type]:
# 对每种关键字类型中的关键字
keyword_tuple = (
# 关键字在新闻中出现的数量
news_keywords[kw_type][keyword],
self.keywords[
self.keyword_property[kw_type]][keyword],
news_id
)
self.news_keywords_tuple_list.append(keyword_tuple)
if len(self.news_keywords_tuple_list) >= self.bat_insert_num:
self.db_session.insertMany(
mysql_config.TABLE_KEYWORDS_NEWS,
self.news_keywords_tuple_list,
"amount_keywords_in_news", "keywords_id", "news_id")
self.news_keywords_tuple_list = []
pass | [
"def",
"insert_keyword_info",
"(",
"self",
",",
"news_id",
",",
"data",
")",
":",
"news_keywords",
"=",
"data",
".",
"get",
"(",
"'all_type_keywords'",
")",
"if",
"news_keywords",
"is",
"not",
"None",
":",
"# 如果提取出了关键字",
"for",
"kw_type",
"in",
"news_keywords"... | https://github.com/pskun/finance_news_analysis/blob/6ac13e32deede37a4cf57bba8b2897941ae3d80d/preprocess/news_preprocess_handler.py#L287-L310 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/binhex.py | python | _Hqxdecoderengine.read | (self, totalwtd) | return decdata | Read at least wtd bytes (or until EOF) | Read at least wtd bytes (or until EOF) | [
"Read",
"at",
"least",
"wtd",
"bytes",
"(",
"or",
"until",
"EOF",
")"
] | def read(self, totalwtd):
"""Read at least wtd bytes (or until EOF)"""
decdata = ''
wtd = totalwtd
#
# The loop here is convoluted, since we don't really now how
# much to decode: there may be newlines in the incoming data.
while wtd > 0:
if self.eof: return decdata
wtd = ((wtd+2)//3)*4
data = self.ifp.read(wtd)
#
# Next problem: there may not be a complete number of
# bytes in what we pass to a2b. Solve by yet another
# loop.
#
while 1:
try:
decdatacur, self.eof = \
binascii.a2b_hqx(data)
break
except binascii.Incomplete:
pass
newdata = self.ifp.read(1)
if not newdata:
raise Error, \
'Premature EOF on binhex file'
data = data + newdata
decdata = decdata + decdatacur
wtd = totalwtd - len(decdata)
if not decdata and not self.eof:
raise Error, 'Premature EOF on binhex file'
return decdata | [
"def",
"read",
"(",
"self",
",",
"totalwtd",
")",
":",
"decdata",
"=",
"''",
"wtd",
"=",
"totalwtd",
"#",
"# The loop here is convoluted, since we don't really now how",
"# much to decode: there may be newlines in the incoming data.",
"while",
"wtd",
">",
"0",
":",
"if",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/binhex.py#L279-L311 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py | python | KMeans._mini_batch_training_op | (self, inputs, cluster_idx_list, cluster_centers,
total_counts) | return control_flow_ops.group(*update_ops) | Creates an op for training for mini batch case.
Args:
inputs: list of input Tensors.
cluster_idx_list: A vector (or list of vectors). Each element in the
vector corresponds to an input row in 'inp' and specifies the cluster id
corresponding to the input.
cluster_centers: Tensor Ref of cluster centers.
total_counts: Tensor Ref of cluster counts.
Returns:
An op for doing an update of mini-batch k-means. | Creates an op for training for mini batch case. | [
"Creates",
"an",
"op",
"for",
"training",
"for",
"mini",
"batch",
"case",
"."
] | def _mini_batch_training_op(self, inputs, cluster_idx_list, cluster_centers,
total_counts):
"""Creates an op for training for mini batch case.
Args:
inputs: list of input Tensors.
cluster_idx_list: A vector (or list of vectors). Each element in the
vector corresponds to an input row in 'inp' and specifies the cluster id
corresponding to the input.
cluster_centers: Tensor Ref of cluster centers.
total_counts: Tensor Ref of cluster counts.
Returns:
An op for doing an update of mini-batch k-means.
"""
update_ops = []
for inp, cluster_idx in zip(inputs, cluster_idx_list):
with ops.colocate_with(inp, ignore_existing=True):
assert total_counts is not None
cluster_idx = array_ops.reshape(cluster_idx, [-1])
# Dedupe the unique ids of cluster_centers being updated so that updates
# can be locally aggregated.
unique_ids, unique_idx = array_ops.unique(cluster_idx)
num_unique_cluster_idx = array_ops.size(unique_ids)
# Fetch the old values of counts and cluster_centers.
with ops.colocate_with(total_counts, ignore_existing=True):
old_counts = array_ops.gather(total_counts, unique_ids)
# TODO(agarwal): This colocation seems to run into problems. Fix it.
with ops.colocate_with(cluster_centers, ignore_existing=True):
old_cluster_centers = array_ops.gather(cluster_centers, unique_ids)
# Locally aggregate the increment to counts.
count_updates = math_ops.unsorted_segment_sum(
array_ops.ones_like(unique_idx, dtype=total_counts.dtype),
unique_idx, num_unique_cluster_idx)
# Locally compute the sum of inputs mapped to each id.
# For a cluster with old cluster value x, old count n, and with data
# d_1,...d_k newly assigned to it, we recompute the new value as
# \\(x += (sum_i(d_i) - k * x) / (n + k)\\).
# Compute \\(sum_i(d_i)\\), see comment above.
cluster_center_updates = math_ops.unsorted_segment_sum(
inp, unique_idx, num_unique_cluster_idx)
# Shape to enable broadcasting count_updates and learning_rate to inp.
# It extends the shape with 1's to match the rank of inp.
broadcast_shape = array_ops.concat([
array_ops.reshape(num_unique_cluster_idx, [1]),
array_ops.ones(
array_ops.reshape(array_ops.rank(inp) - 1, [1]),
dtype=dtypes.int32)
], 0)
# Subtract k * x, see comment above.
cluster_center_updates -= math_ops.cast(
array_ops.reshape(count_updates, broadcast_shape),
inp.dtype) * old_cluster_centers
learning_rate = math_ops.reciprocal(
math_ops.cast(old_counts + count_updates, inp.dtype))
learning_rate = array_ops.reshape(learning_rate, broadcast_shape)
# scale by 1 / (n + k), see comment above.
cluster_center_updates *= learning_rate
# Apply the updates.
update_counts = state_ops.scatter_add(total_counts, unique_ids,
count_updates)
update_cluster_centers = state_ops.scatter_add(
cluster_centers, unique_ids, cluster_center_updates)
update_ops.extend([update_counts, update_cluster_centers])
return control_flow_ops.group(*update_ops) | [
"def",
"_mini_batch_training_op",
"(",
"self",
",",
"inputs",
",",
"cluster_idx_list",
",",
"cluster_centers",
",",
"total_counts",
")",
":",
"update_ops",
"=",
"[",
"]",
"for",
"inp",
",",
"cluster_idx",
"in",
"zip",
"(",
"inputs",
",",
"cluster_idx_list",
")... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py#L435-L499 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/utils/network.py | python | NodeFilter.data_provider | (self) | return self.type(Host2DeviceCopy) | r"""get :class:`.DataProvider` oprs; shorthand for
``.type(DataProvider)`` | r"""get :class:`.DataProvider` oprs; shorthand for
``.type(DataProvider)`` | [
"r",
"get",
":",
"class",
":",
".",
"DataProvider",
"oprs",
";",
"shorthand",
"for",
".",
"type",
"(",
"DataProvider",
")"
] | def data_provider(self):
r"""get :class:`.DataProvider` oprs; shorthand for
``.type(DataProvider)``
"""
return self.type(Host2DeviceCopy) | [
"def",
"data_provider",
"(",
"self",
")",
":",
"return",
"self",
".",
"type",
"(",
"Host2DeviceCopy",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/utils/network.py#L688-L693 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/swf/layer1.py | python | Layer1.json_request | (self, action, data, object_hook=None) | return self.make_request(action, json_input, object_hook) | This method wraps around make_request() to normalize and serialize the
dictionary with request parameters.
:type action: string
:param action: Specifies an SWF action.
:type data: dict
:param data: Specifies request parameters associated with the action. | This method wraps around make_request() to normalize and serialize the
dictionary with request parameters. | [
"This",
"method",
"wraps",
"around",
"make_request",
"()",
"to",
"normalize",
"and",
"serialize",
"the",
"dictionary",
"with",
"request",
"parameters",
"."
] | def json_request(self, action, data, object_hook=None):
"""
This method wraps around make_request() to normalize and serialize the
dictionary with request parameters.
:type action: string
:param action: Specifies an SWF action.
:type data: dict
:param data: Specifies request parameters associated with the action.
"""
self._normalize_request_dict(data)
json_input = json.dumps(data)
return self.make_request(action, json_input, object_hook) | [
"def",
"json_request",
"(",
"self",
",",
"action",
",",
"data",
",",
"object_hook",
"=",
"None",
")",
":",
"self",
".",
"_normalize_request_dict",
"(",
"data",
")",
"json_input",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"return",
"self",
".",
"make_r... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/swf/layer1.py#L105-L118 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/_inputstream.py | python | HTMLUnicodeInputStream.char | (self) | return char | Read one character from the stream or queue if available. Return
EOF when EOF is reached. | Read one character from the stream or queue if available. Return | [
"Read",
"one",
"character",
"from",
"the",
"stream",
"or",
"queue",
"if",
"available",
".",
"Return"
] | def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = chunkOffset + 1
return char | [
"def",
"char",
"(",
"self",
")",
":",
"# Read a new chunk from the input stream if necessary",
"if",
"self",
".",
"chunkOffset",
">=",
"self",
".",
"chunkSize",
":",
"if",
"not",
"self",
".",
"readChunk",
"(",
")",
":",
"return",
"EOF",
"chunkOffset",
"=",
"se... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/_inputstream.py#L467-L493 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/download.py | python | DownloadSubmissionTask._get_download_output_manager_cls | (self, transfer_future, osutil) | Retrieves a class for managing output for a download
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future for the request
:type osutil: s3transfer.utils.OSUtils
:param osutil: The os utility associated to the transfer
:rtype: class of DownloadOutputManager
:returns: The appropriate class to use for managing a specific type of
input for downloads. | Retrieves a class for managing output for a download | [
"Retrieves",
"a",
"class",
"for",
"managing",
"output",
"for",
"a",
"download"
] | def _get_download_output_manager_cls(self, transfer_future, osutil):
"""Retrieves a class for managing output for a download
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future for the request
:type osutil: s3transfer.utils.OSUtils
:param osutil: The os utility associated to the transfer
:rtype: class of DownloadOutputManager
:returns: The appropriate class to use for managing a specific type of
input for downloads.
"""
download_manager_resolver_chain = [
DownloadSpecialFilenameOutputManager,
DownloadFilenameOutputManager,
DownloadSeekableOutputManager,
DownloadNonSeekableOutputManager,
]
fileobj = transfer_future.meta.call_args.fileobj
for download_manager_cls in download_manager_resolver_chain:
if download_manager_cls.is_compatible(fileobj, osutil):
return download_manager_cls
raise RuntimeError(
'Output %s of type: %s is not supported.' % (
fileobj, type(fileobj))) | [
"def",
"_get_download_output_manager_cls",
"(",
"self",
",",
"transfer_future",
",",
"osutil",
")",
":",
"download_manager_resolver_chain",
"=",
"[",
"DownloadSpecialFilenameOutputManager",
",",
"DownloadFilenameOutputManager",
",",
"DownloadSeekableOutputManager",
",",
"Downlo... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/download.py#L281-L307 | ||
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_logic_utils.py | python | formula_to_clauses_aux | (f) | return [y for x in f.args for y in formula_to_clauses_aux(x)] | Clausify a formula. Outside of a TseitinContext, this requires that
the formula is in CNF and with raise ValueException otherwise. Within a
TseitinContext will do Tseitin encoding. | Clausify a formula. Outside of a TseitinContext, this requires that
the formula is in CNF and with raise ValueException otherwise. Within a
TseitinContext will do Tseitin encoding. | [
"Clausify",
"a",
"formula",
".",
"Outside",
"of",
"a",
"TseitinContext",
"this",
"requires",
"that",
"the",
"formula",
"is",
"in",
"CNF",
"and",
"with",
"raise",
"ValueException",
"otherwise",
".",
"Within",
"a",
"TseitinContext",
"will",
"do",
"Tseitin",
"enc... | def formula_to_clauses_aux(f):
""" Clausify a formula. Outside of a TseitinContext, this requires that
the formula is in CNF and with raise ValueException otherwise. Within a
TseitinContext will do Tseitin encoding. """
# print "ftc: {} : {} : {}".format(f,type(f),And)
f = drop_universals(f)
f = de_morgan(f)
# print "ftc: {} : {} : {}".format(f,type(f),And)
if is_false(f):
return [[]]
if not(isinstance(f,And)):
cls = formula_to_clause(f)
return [] if any(is_taut_lit(lit) for lit in cls) else [cls]
return [y for x in f.args for y in formula_to_clauses_aux(x)] | [
"def",
"formula_to_clauses_aux",
"(",
"f",
")",
":",
"# print \"ftc: {} : {} : {}\".format(f,type(f),And)",
"f",
"=",
"drop_universals",
"(",
"f",
")",
"f",
"=",
"de_morgan",
"(",
"f",
")",
"# print \"ftc: {} : {} : {}\".format(f,type(f),And)",
"if",
"is_false",
"("... | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_logic_utils.py#L836-L849 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py | python | FontPage.load_tab_cfg | (self) | Load current configuration settings for the tab options.
Attributes updated:
space_num: Set to value from idleConf. | Load current configuration settings for the tab options. | [
"Load",
"current",
"configuration",
"settings",
"for",
"the",
"tab",
"options",
"."
] | def load_tab_cfg(self):
"""Load current configuration settings for the tab options.
Attributes updated:
space_num: Set to value from idleConf.
"""
# Set indent sizes.
space_num = idleConf.GetOption(
'main', 'Indent', 'num-spaces', default=4, type='int')
self.space_num.set(space_num) | [
"def",
"load_tab_cfg",
"(",
"self",
")",
":",
"# Set indent sizes.",
"space_num",
"=",
"idleConf",
".",
"GetOption",
"(",
"'main'",
",",
"'Indent'",
",",
"'num-spaces'",
",",
"default",
"=",
"4",
",",
"type",
"=",
"'int'",
")",
"self",
".",
"space_num",
".... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py#L669-L678 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | SplitWords | (input_string) | Transforms a input_string into a list of lower-case components.
Args:
input_string: the input string.
Returns:
a list of lower-case words. | Transforms a input_string into a list of lower-case components. | [
"Transforms",
"a",
"input_string",
"into",
"a",
"list",
"of",
"lower",
"-",
"case",
"components",
"."
] | def SplitWords(input_string):
"""Transforms a input_string into a list of lower-case components.
Args:
input_string: the input string.
Returns:
a list of lower-case words.
"""
if input_string.find('_') > -1:
# 'some_TEXT_' -> 'some text'
return input_string.replace('_', ' ').strip().lower().split()
else:
if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
# mixed case.
# look for capitalization to cut input_strings
# 'SomeText' -> 'Some Text'
input_string = re.sub('([A-Z])', r' \1', input_string).strip()
# 'Vector3' -> 'Vector 3'
input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
return input_string.lower().split() | [
"def",
"SplitWords",
"(",
"input_string",
")",
":",
"if",
"input_string",
".",
"find",
"(",
"'_'",
")",
">",
"-",
"1",
":",
"# 'some_TEXT_' -> 'some text'",
"return",
"input_string",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"strip",
"(",
")",
".... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L2516-L2536 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/autograph/operators/py_builtins.py | python | locals_in_original_context | (caller_fn_scope) | return _find_originating_frame(caller_fn_scope, innermost=True).f_locals | Executes the locals function in the context of a specified function. | Executes the locals function in the context of a specified function. | [
"Executes",
"the",
"locals",
"function",
"in",
"the",
"context",
"of",
"a",
"specified",
"function",
"."
] | def locals_in_original_context(caller_fn_scope):
"""Executes the locals function in the context of a specified function."""
return _find_originating_frame(caller_fn_scope, innermost=True).f_locals | [
"def",
"locals_in_original_context",
"(",
"caller_fn_scope",
")",
":",
"return",
"_find_originating_frame",
"(",
"caller_fn_scope",
",",
"innermost",
"=",
"True",
")",
".",
"f_locals"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/operators/py_builtins.py#L86-L88 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/plotting/_matplotlib/style.py | python | _is_single_color | (color: Color | Collection[Color]) | return False | Check if `color` is a single color, not a sequence of colors.
Single color is of these kinds:
- Named color "red", "C0", "firebrick"
- Alias "g"
- Sequence of floats, such as (0.1, 0.2, 0.3) or (0.1, 0.2, 0.3, 0.4).
See Also
--------
_is_single_string_color | Check if `color` is a single color, not a sequence of colors. | [
"Check",
"if",
"color",
"is",
"a",
"single",
"color",
"not",
"a",
"sequence",
"of",
"colors",
"."
] | def _is_single_color(color: Color | Collection[Color]) -> bool:
"""Check if `color` is a single color, not a sequence of colors.
Single color is of these kinds:
- Named color "red", "C0", "firebrick"
- Alias "g"
- Sequence of floats, such as (0.1, 0.2, 0.3) or (0.1, 0.2, 0.3, 0.4).
See Also
--------
_is_single_string_color
"""
if isinstance(color, str) and _is_single_string_color(color):
# GH #36972
return True
if _is_floats_color(color):
return True
return False | [
"def",
"_is_single_color",
"(",
"color",
":",
"Color",
"|",
"Collection",
"[",
"Color",
"]",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
"and",
"_is_single_string_color",
"(",
"color",
")",
":",
"# GH #36972",
"return",
"True... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/plotting/_matplotlib/style.py#L175-L194 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextParagraphLayoutBox.MoveAnchoredObjectToParagraph | (*args, **kwargs) | return _richtext.RichTextParagraphLayoutBox_MoveAnchoredObjectToParagraph(*args, **kwargs) | MoveAnchoredObjectToParagraph(self, RichTextParagraph from, RichTextParagraph to, RichTextObject obj) | MoveAnchoredObjectToParagraph(self, RichTextParagraph from, RichTextParagraph to, RichTextObject obj) | [
"MoveAnchoredObjectToParagraph",
"(",
"self",
"RichTextParagraph",
"from",
"RichTextParagraph",
"to",
"RichTextObject",
"obj",
")"
] | def MoveAnchoredObjectToParagraph(*args, **kwargs):
"""MoveAnchoredObjectToParagraph(self, RichTextParagraph from, RichTextParagraph to, RichTextObject obj)"""
return _richtext.RichTextParagraphLayoutBox_MoveAnchoredObjectToParagraph(*args, **kwargs) | [
"def",
"MoveAnchoredObjectToParagraph",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraphLayoutBox_MoveAnchoredObjectToParagraph",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1640-L1642 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/cookielib.py | python | CookieJar.add_cookie_header | (self, request) | Add correct Cookie: header to request (urllib2.Request object).
The Cookie2 header is also added unless policy.hide_cookie2 is true. | Add correct Cookie: header to request (urllib2.Request object). | [
"Add",
"correct",
"Cookie",
":",
"header",
"to",
"request",
"(",
"urllib2",
".",
"Request",
"object",
")",
"."
] | def add_cookie_header(self, request):
"""Add correct Cookie: header to request (urllib2.Request object).
The Cookie2 header is also added unless policy.hide_cookie2 is true.
"""
_debug("add_cookie_header")
self._cookies_lock.acquire()
try:
self._policy._now = self._now = int(time.time())
cookies = self._cookies_for_request(request)
attrs = self._cookie_attrs(cookies)
if attrs:
if not request.has_header("Cookie"):
request.add_unredirected_header(
"Cookie", "; ".join(attrs))
# if necessary, advertise that we know RFC 2965
if (self._policy.rfc2965 and not self._policy.hide_cookie2 and
not request.has_header("Cookie2")):
for cookie in cookies:
if cookie.version != 1:
request.add_unredirected_header("Cookie2", '$Version="1"')
break
finally:
self._cookies_lock.release()
self.clear_expired_cookies() | [
"def",
"add_cookie_header",
"(",
"self",
",",
"request",
")",
":",
"_debug",
"(",
"\"add_cookie_header\"",
")",
"self",
".",
"_cookies_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_policy",
".",
"_now",
"=",
"self",
".",
"_now",
"=",
"int",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cookielib.py#L1328-L1359 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | shell/ext-py/prettytable-0.7.2/prettytable.py | python | PrettyTable._get_hrules | (self) | return self._hrules | Controls printing of horizontal rules after rows
Arguments:
hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE | Controls printing of horizontal rules after rows | [
"Controls",
"printing",
"of",
"horizontal",
"rules",
"after",
"rows"
] | def _get_hrules(self):
"""Controls printing of horizontal rules after rows
Arguments:
hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE"""
return self._hrules | [
"def",
"_get_hrules",
"(",
"self",
")",
":",
"return",
"self",
".",
"_hrules"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/ext-py/prettytable-0.7.2/prettytable.py#L569-L575 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py | python | UBMatrixPeakTable.get_hkl | (self, row_index, is_spice_hkl) | return m_h, m_k, m_l | Get reflection's miller index
:except RuntimeError:
:param row_index:
:param is_spice_hkl:
:return: 3-tuple as H, K, L | Get reflection's miller index
:except RuntimeError:
:param row_index:
:param is_spice_hkl:
:return: 3-tuple as H, K, L | [
"Get",
"reflection",
"s",
"miller",
"index",
":",
"except",
"RuntimeError",
":",
":",
"param",
"row_index",
":",
":",
"param",
"is_spice_hkl",
":",
":",
"return",
":",
"3",
"-",
"tuple",
"as",
"H",
"K",
"L"
] | def get_hkl(self, row_index, is_spice_hkl):
"""
Get reflection's miller index
:except RuntimeError:
:param row_index:
:param is_spice_hkl:
:return: 3-tuple as H, K, L
"""
# check input
assert isinstance(row_index, int), 'Row index {0} must be an integer but not a {1}.' \
''.format(row_index, type(row_index))
# get the HKL either parsed from SPICE file or from calculation
if is_spice_hkl:
hkl_str = self.get_cell_value(row_index, self._colIndexSpiceHKL)
else:
hkl_str = self.get_cell_value(row_index, self._colIndexCalculatedHKL)
# convert the recorded string to HKL
status, ret_obj = guiutility.parse_float_array(hkl_str)
if not status:
raise RuntimeError('Unable to parse hkl (str) due to {0}'.format(ret_obj))
elif len(ret_obj) != 3:
raise RuntimeError('Unable to convert array "{0}" to 3 floating points.'.format(hkl_str))
else:
m_h, m_k, m_l = ret_obj
return m_h, m_k, m_l | [
"def",
"get_hkl",
"(",
"self",
",",
"row_index",
",",
"is_spice_hkl",
")",
":",
"# check input",
"assert",
"isinstance",
"(",
"row_index",
",",
"int",
")",
",",
"'Row index {0} must be an integer but not a {1}.'",
"''",
".",
"format",
"(",
"row_index",
",",
"type"... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L1763-L1790 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | _mboxMMDF.get_bytes | (self, key, from_=False) | return string.replace(linesep, b'\n') | Return a string representation or raise a KeyError. | Return a string representation or raise a KeyError. | [
"Return",
"a",
"string",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_bytes(self, key, from_=False):
"""Return a string representation or raise a KeyError."""
start, stop = self._lookup(key)
self._file.seek(start)
if not from_:
self._file.readline()
string = self._file.read(stop - self._file.tell())
return string.replace(linesep, b'\n') | [
"def",
"get_bytes",
"(",
"self",
",",
"key",
",",
"from_",
"=",
"False",
")",
":",
"start",
",",
"stop",
"=",
"self",
".",
"_lookup",
"(",
"key",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"start",
")",
"if",
"not",
"from_",
":",
"self",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L792-L799 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/cgi.py | python | FieldStorage.getlist | (self, key) | Return list of received values. | Return list of received values. | [
"Return",
"list",
"of",
"received",
"values",
"."
] | def getlist(self, key):
""" Return list of received values."""
if key in self:
value = self[key]
if type(value) is type([]):
return map(attrgetter('value'), value)
else:
return [value.value]
else:
return [] | [
"def",
"getlist",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
":",
"value",
"=",
"self",
"[",
"key",
"]",
"if",
"type",
"(",
"value",
")",
"is",
"type",
"(",
"[",
"]",
")",
":",
"return",
"map",
"(",
"attrgetter",
"(",
"'value... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/cgi.py#L568-L577 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/fps/connection.py | python | FPSConnection.cancel_token | (self, action, response, **kw) | return self.get_object(action, kw, response) | Cancels any token installed by the calling application on its own
account. | Cancels any token installed by the calling application on its own
account. | [
"Cancels",
"any",
"token",
"installed",
"by",
"the",
"calling",
"application",
"on",
"its",
"own",
"account",
"."
] | def cancel_token(self, action, response, **kw):
"""
Cancels any token installed by the calling application on its own
account.
"""
return self.get_object(action, kw, response) | [
"def",
"cancel_token",
"(",
"self",
",",
"action",
",",
"response",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"get_object",
"(",
"action",
",",
"kw",
",",
"response",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/fps/connection.py#L321-L326 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py | python | merge_completers | (
completers: Sequence[Completer], deduplicate: bool = False
) | return _MergedCompleter(completers) | Combine several completers into one.
:param deduplicate: If `True`, wrap the result in a `DeduplicateCompleter`
so that completions that would result in the same text will be
deduplicated. | Combine several completers into one. | [
"Combine",
"several",
"completers",
"into",
"one",
"."
] | def merge_completers(
completers: Sequence[Completer], deduplicate: bool = False
) -> Completer:
"""
Combine several completers into one.
:param deduplicate: If `True`, wrap the result in a `DeduplicateCompleter`
so that completions that would result in the same text will be
deduplicated.
"""
if deduplicate:
from .deduplicate import DeduplicateCompleter
return DeduplicateCompleter(_MergedCompleter(completers))
return _MergedCompleter(completers) | [
"def",
"merge_completers",
"(",
"completers",
":",
"Sequence",
"[",
"Completer",
"]",
",",
"deduplicate",
":",
"bool",
"=",
"False",
")",
"->",
"Completer",
":",
"if",
"deduplicate",
":",
"from",
".",
"deduplicate",
"import",
"DeduplicateCompleter",
"return",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py#L342-L357 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py | python | tool_list | (platform, env) | return [ 'xgettext', 'msginit', 'msgmerge', 'msgfmt' ] | List tools that shall be generated by top-level `gettext` tool | List tools that shall be generated by top-level `gettext` tool | [
"List",
"tools",
"that",
"shall",
"be",
"generated",
"by",
"top",
"-",
"level",
"gettext",
"tool"
] | def tool_list(platform, env):
""" List tools that shall be generated by top-level `gettext` tool """
return [ 'xgettext', 'msginit', 'msgmerge', 'msgfmt' ] | [
"def",
"tool_list",
"(",
"platform",
",",
"env",
")",
":",
"return",
"[",
"'xgettext'",
",",
"'msginit'",
",",
"'msgmerge'",
",",
"'msgfmt'",
"]"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py#L409-L411 | |
raymondlu/super-animation-samples | 04234269112ff0dc32447f27a761dbbb00b8ba17 | samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | TranslationUnit.reparse | (self, unsaved_files=None, options=0) | Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects. | Reparse an already parsed translation unit. | [
"Reparse",
"an",
"already",
"parsed",
"translation",
"unit",
"."
] | def reparse(self, unsaved_files=None, options=0):
"""
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print value
if not isinstance(value, str):
raise TypeError,'Unexpected unsaved file contents.'
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
unsaved_files_array, options) | [
"def",
"reparse",
"(",
"self",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
")",
":",
"if",
"unsaved_files",
"is",
"None",
":",
"unsaved_files",
"=",
"[",
"]",
"unsaved_files_array",
"=",
"0",
"if",
"len",
"(",
"unsaved_files",
")",
":",
... | https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2371-L2398 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/image/python/ops/image_ops.py | python | angles_to_projective_transforms | (angles,
image_height,
image_width,
name=None) | Returns projective transform(s) for the given angle(s).
Args:
angles: A scalar angle to rotate all images by, or (for batches of images)
a vector with an angle to rotate each image in the batch. The rank must
be statically known (the shape is not `TensorShape(None)`.
image_height: Height of the image(s) to be transformed.
image_width: Width of the image(s) to be transformed.
Returns:
A tensor of shape (num_images, 8). Projective transforms which can be given
to `tf.contrib.image.transform`. | Returns projective transform(s) for the given angle(s). | [
"Returns",
"projective",
"transform",
"(",
"s",
")",
"for",
"the",
"given",
"angle",
"(",
"s",
")",
"."
] | def angles_to_projective_transforms(angles,
image_height,
image_width,
name=None):
"""Returns projective transform(s) for the given angle(s).
Args:
angles: A scalar angle to rotate all images by, or (for batches of images)
a vector with an angle to rotate each image in the batch. The rank must
be statically known (the shape is not `TensorShape(None)`.
image_height: Height of the image(s) to be transformed.
image_width: Width of the image(s) to be transformed.
Returns:
A tensor of shape (num_images, 8). Projective transforms which can be given
to `tf.contrib.image.transform`.
"""
with ops.name_scope(name, "angles_to_projective_transforms"):
angle_or_angles = ops.convert_to_tensor(
angles, name="angles", dtype=dtypes.float32)
if len(angle_or_angles.get_shape()) == 0: # pylint: disable=g-explicit-length-test
angles = angle_or_angles[None]
elif len(angle_or_angles.get_shape()) == 1:
angles = angle_or_angles
else:
raise TypeError("Angles should have rank 0 or 1.")
x_offset = ((image_width - 1) - (math_ops.cos(angles) *
(image_width - 1) - math_ops.sin(angles) *
(image_height - 1))) / 2.0
y_offset = ((image_height - 1) - (math_ops.sin(angles) *
(image_width - 1) + math_ops.cos(angles) *
(image_height - 1))) / 2.0
num_angles = array_ops.shape(angles)[0]
return array_ops.concat(
values=[
math_ops.cos(angles)[:, None],
-math_ops.sin(angles)[:, None],
x_offset[:, None],
math_ops.sin(angles)[:, None],
math_ops.cos(angles)[:, None],
y_offset[:, None],
array_ops.zeros((num_angles, 2), dtypes.float32),
],
axis=1) | [
"def",
"angles_to_projective_transforms",
"(",
"angles",
",",
"image_height",
",",
"image_width",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"angles_to_projective_transforms\"",
")",
":",
"angle_or_angles",
"=",
"ops"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/image/python/ops/image_ops.py#L130-L173 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/bond_core/smclib/python/smclib/statemap.py | python | FSMContext.pushState | (self, state) | Push the current state on top of the state stack
and make the specified state the current state. | Push the current state on top of the state stack
and make the specified state the current state. | [
"Push",
"the",
"current",
"state",
"on",
"top",
"of",
"the",
"state",
"stack",
"and",
"make",
"the",
"specified",
"state",
"the",
"current",
"state",
"."
] | def pushState(self, state):
"""Push the current state on top of the state stack
and make the specified state the current state."""
if not isinstance(state, State):
raise ValueError("state should be a statemap.State")
if self._state != None:
self._state_stack.append(self._state)
self._state = state
if self._debug_flag:
self._debug_stream.write("PUSH TO STATE : %s\n" % self._state.getName()) | [
"def",
"pushState",
"(",
"self",
",",
"state",
")",
":",
"if",
"not",
"isinstance",
"(",
"state",
",",
"State",
")",
":",
"raise",
"ValueError",
"(",
"\"state should be a statemap.State\"",
")",
"if",
"self",
".",
"_state",
"!=",
"None",
":",
"self",
".",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/bond_core/smclib/python/smclib/statemap.py#L148-L157 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.InvalidateBestSize | (*args, **kwargs) | return _core_.Window_InvalidateBestSize(*args, **kwargs) | InvalidateBestSize(self)
Reset the cached best size value so it will be recalculated the next
time it is needed. | InvalidateBestSize(self) | [
"InvalidateBestSize",
"(",
"self",
")"
] | def InvalidateBestSize(*args, **kwargs):
"""
InvalidateBestSize(self)
Reset the cached best size value so it will be recalculated the next
time it is needed.
"""
return _core_.Window_InvalidateBestSize(*args, **kwargs) | [
"def",
"InvalidateBestSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_InvalidateBestSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L9619-L9626 | |
stulp/dmpbbo | ca900e3b851d25faaf59ea296650370c70ed7d0f | python/bbo/updaters.py | python | UpdaterCovarAdaptation.__init__ | (self,eliteness = 10, weighting_method = 'PI-BB',diagonal_max=None,diagonal_min=None,diag_only=False,learning_rate=1.0) | Constructor
\param[in] eliteness The eliteness parameter ('mu' in CMA-ES, 'h' in PI^2)
\param[in] weighting_method ('PI-BB' = PI^2 style weighting)
\param[in] base_level Small covariance matrix that is added after each update to avoid premature convergence
\param[in] diag_only Update only the diagonal of the covariance matrix (true) or the full matrix (false)
\param[in] learning_rate Low pass filter on the covariance updates. In range [0.0-1.0] with 0.0 = no updating, 1.0 = complete update by ignoring previous covar matrix. | Constructor
\param[in] eliteness The eliteness parameter ('mu' in CMA-ES, 'h' in PI^2)
\param[in] weighting_method ('PI-BB' = PI^2 style weighting)
\param[in] base_level Small covariance matrix that is added after each update to avoid premature convergence
\param[in] diag_only Update only the diagonal of the covariance matrix (true) or the full matrix (false)
\param[in] learning_rate Low pass filter on the covariance updates. In range [0.0-1.0] with 0.0 = no updating, 1.0 = complete update by ignoring previous covar matrix. | [
"Constructor",
"\\",
"param",
"[",
"in",
"]",
"eliteness",
"The",
"eliteness",
"parameter",
"(",
"mu",
"in",
"CMA",
"-",
"ES",
"h",
"in",
"PI^2",
")",
"\\",
"param",
"[",
"in",
"]",
"weighting_method",
"(",
"PI",
"-",
"BB",
"=",
"PI^2",
"style",
"wei... | def __init__(self,eliteness = 10, weighting_method = 'PI-BB',diagonal_max=None,diagonal_min=None,diag_only=False,learning_rate=1.0):
""" Constructor
\param[in] eliteness The eliteness parameter ('mu' in CMA-ES, 'h' in PI^2)
\param[in] weighting_method ('PI-BB' = PI^2 style weighting)
\param[in] base_level Small covariance matrix that is added after each update to avoid premature convergence
\param[in] diag_only Update only the diagonal of the covariance matrix (true) or the full matrix (false)
\param[in] learning_rate Low pass filter on the covariance updates. In range [0.0-1.0] with 0.0 = no updating, 1.0 = complete update by ignoring previous covar matrix.
"""
self.eliteness = eliteness
self.weighting_method = weighting_method
self.diagonal_max = diagonal_max
self.diagonal_min = diagonal_min
self.diag_only = diag_only
if (learning_rate>1.0):
learning_rate=1.0
elif (learning_rate<0.0):
learning_rate=0.0
self.learning_rate = learning_rate | [
"def",
"__init__",
"(",
"self",
",",
"eliteness",
"=",
"10",
",",
"weighting_method",
"=",
"'PI-BB'",
",",
"diagonal_max",
"=",
"None",
",",
"diagonal_min",
"=",
"None",
",",
"diag_only",
"=",
"False",
",",
"learning_rate",
"=",
"1.0",
")",
":",
"self",
... | https://github.com/stulp/dmpbbo/blob/ca900e3b851d25faaf59ea296650370c70ed7d0f/python/bbo/updaters.py#L113-L130 | ||
OAID/Tengine | 66b2c22ad129d25e2fc6de3b22a608bb54dd90db | pytengine/tengine/graph.py | python | Graph.preRun | (self) | Initialize resource for graph execution
:return: None | Initialize resource for graph execution
:return: None | [
"Initialize",
"resource",
"for",
"graph",
"execution",
":",
"return",
":",
"None"
] | def preRun(self):
"""
Initialize resource for graph execution
:return: None
"""
check_call(_LIB.prerun_graph(ctypes.c_void_p(self.graph))) | [
"def",
"preRun",
"(",
"self",
")",
":",
"check_call",
"(",
"_LIB",
".",
"prerun_graph",
"(",
"ctypes",
".",
"c_void_p",
"(",
"self",
".",
"graph",
")",
")",
")"
] | https://github.com/OAID/Tengine/blob/66b2c22ad129d25e2fc6de3b22a608bb54dd90db/pytengine/tengine/graph.py#L330-L335 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/panelbox.py | python | PanelBox.AppendItem | (self, item) | Append an item to the list
@param item: PanelBoxItem | Append an item to the list
@param item: PanelBoxItem | [
"Append",
"an",
"item",
"to",
"the",
"list",
"@param",
"item",
":",
"PanelBoxItem"
] | def AppendItem(self, item):
"""Append an item to the list
@param item: PanelBoxItem
"""
self._items.append(item)
self._sizer.Add(item, 0, wx.EXPAND)
item.Realize() | [
"def",
"AppendItem",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"_items",
".",
"append",
"(",
"item",
")",
"self",
".",
"_sizer",
".",
"Add",
"(",
"item",
",",
"0",
",",
"wx",
".",
"EXPAND",
")",
"item",
".",
"Realize",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/panelbox.py#L145-L152 | ||
Sigil-Ebook/Sigil | 0d145d3a4874b4a26f7aabd68dbd9d18a2402e52 | src/Resource_Files/plugin_launchers/python/sigil_bs4/builder/_lxml.py | python | LXMLTreeBuilder.test_fragment_to_document | (self, fragment) | return '<html><body>%s</body></html>' % fragment | See `TreeBuilder`. | See `TreeBuilder`. | [
"See",
"TreeBuilder",
"."
] | def test_fragment_to_document(self, fragment):
"""See `TreeBuilder`."""
return '<html><body>%s</body></html>' % fragment | [
"def",
"test_fragment_to_document",
"(",
"self",
",",
"fragment",
")",
":",
"return",
"'<html><body>%s</body></html>'",
"%",
"fragment"
] | https://github.com/Sigil-Ebook/Sigil/blob/0d145d3a4874b4a26f7aabd68dbd9d18a2402e52/src/Resource_Files/plugin_launchers/python/sigil_bs4/builder/_lxml.py#L306-L308 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/numpy/_op.py | python | isneginf | (x, out=None, **kwargs) | return _pure_unary_func_helper(x, _api_internal.isneginf, _np.isneginf, out=out, **kwargs) | Test element-wise for negative infinity, return result as bool array.
Parameters
----------
x : ndarray
Input array.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
y : ndarray or bool
True where x is negative infinity, false otherwise.
This is a scalar if x is a scalar.
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).
This means that Not a Number is not equivalent to infinity.
Examples
--------
>>> np.isneginf(-np.inf)
True
>>> np.isneginf(np.inf)
False
>>> np.isneginf(float('-inf'))
True
>>> np.isneginf(np.array([-np.inf, 0., np.inf]))
array([ True, False, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([True, True, True], dtype=np.bool)
>>> np.isneginf(x, y)
array([ True, False, False])
>>> y
array([ True, False, False]) | Test element-wise for negative infinity, return result as bool array. | [
"Test",
"element",
"-",
"wise",
"for",
"negative",
"infinity",
"return",
"result",
"as",
"bool",
"array",
"."
] | def isneginf(x, out=None, **kwargs):
"""
Test element-wise for negative infinity, return result as bool array.
Parameters
----------
x : ndarray
Input array.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
y : ndarray or bool
True where x is negative infinity, false otherwise.
This is a scalar if x is a scalar.
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).
This means that Not a Number is not equivalent to infinity.
Examples
--------
>>> np.isneginf(-np.inf)
True
>>> np.isneginf(np.inf)
False
>>> np.isneginf(float('-inf'))
True
>>> np.isneginf(np.array([-np.inf, 0., np.inf]))
array([ True, False, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([True, True, True], dtype=np.bool)
>>> np.isneginf(x, y)
array([ True, False, False])
>>> y
array([ True, False, False])
"""
return _pure_unary_func_helper(x, _api_internal.isneginf, _np.isneginf, out=out, **kwargs) | [
"def",
"isneginf",
"(",
"x",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_pure_unary_func_helper",
"(",
"x",
",",
"_api_internal",
".",
"isneginf",
",",
"_np",
".",
"isneginf",
",",
"out",
"=",
"out",
",",
"*",
"*",
"kwargs... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L8983-L9024 | |
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/newclasscalc/calc.py | python | Calc.p_expression_binop | (self, p) | expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
| expression EXP expression | expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
| expression EXP expression | [
"expression",
":",
"expression",
"PLUS",
"expression",
"|",
"expression",
"MINUS",
"expression",
"|",
"expression",
"TIMES",
"expression",
"|",
"expression",
"DIVIDE",
"expression",
"|",
"expression",
"EXP",
"expression"
] | def p_expression_binop(self, p):
"""
expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
| expression EXP expression
"""
#print [repr(p[i]) for i in range(0,4)]
if p[2] == '+' : p[0] = p[1] + p[3]
elif p[2] == '-': p[0] = p[1] - p[3]
elif p[2] == '*': p[0] = p[1] * p[3]
elif p[2] == '/': p[0] = p[1] / p[3]
elif p[2] == '**': p[0] = p[1] ** p[3] | [
"def",
"p_expression_binop",
"(",
"self",
",",
"p",
")",
":",
"#print [repr(p[i]) for i in range(0,4)]",
"if",
"p",
"[",
"2",
"]",
"==",
"'+'",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"p",
"[",
"3",
"]",
"elif",
"p",
"[",
"2",
"]",... | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/newclasscalc/calc.py#L117-L130 | ||
NVIDIA/MDL-SDK | aa9642b2546ad7b6236b5627385d882c2ed83c5d | src/mdl/jit/llvm/dist/utils/lit/lit/ShUtil.py | python | ShLexer.lex_one_token | (self) | return self.lex_arg(c) | lex_one_token - Lex a single 'sh' token. | lex_one_token - Lex a single 'sh' token. | [
"lex_one_token",
"-",
"Lex",
"a",
"single",
"sh",
"token",
"."
] | def lex_one_token(self):
"""
lex_one_token - Lex a single 'sh' token. """
c = self.eat()
if c == ';':
return (c,)
if c == '|':
if self.maybe_eat('|'):
return ('||',)
return (c,)
if c == '&':
if self.maybe_eat('&'):
return ('&&',)
if self.maybe_eat('>'):
return ('&>',)
return (c,)
if c == '>':
if self.maybe_eat('&'):
return ('>&',)
if self.maybe_eat('>'):
return ('>>',)
return (c,)
if c == '<':
if self.maybe_eat('&'):
return ('<&',)
if self.maybe_eat('>'):
return ('<<',)
return (c,)
return self.lex_arg(c) | [
"def",
"lex_one_token",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"eat",
"(",
")",
"if",
"c",
"==",
"';'",
":",
"return",
"(",
"c",
",",
")",
"if",
"c",
"==",
"'|'",
":",
"if",
"self",
".",
"maybe_eat",
"(",
"'|'",
")",
":",
"return",
"("... | https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/utils/lit/lit/ShUtil.py#L148-L178 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/linear_model/base.py | python | sparse_center_data | (X, y, fit_intercept, normalize=False) | return X, y, X_offset, y_offset, X_std | Compute information needed to center data to have mean zero along
axis 0. Be aware that X will not be centered since it would break
the sparsity, but will be normalized if asked so. | Compute information needed to center data to have mean zero along
axis 0. Be aware that X will not be centered since it would break
the sparsity, but will be normalized if asked so. | [
"Compute",
"information",
"needed",
"to",
"center",
"data",
"to",
"have",
"mean",
"zero",
"along",
"axis",
"0",
".",
"Be",
"aware",
"that",
"X",
"will",
"not",
"be",
"centered",
"since",
"it",
"would",
"break",
"the",
"sparsity",
"but",
"will",
"be",
"no... | def sparse_center_data(X, y, fit_intercept, normalize=False):
"""
Compute information needed to center data to have mean zero along
axis 0. Be aware that X will not be centered since it would break
the sparsity, but will be normalized if asked so.
"""
if fit_intercept:
# we might require not to change the csr matrix sometimes
# store a copy if normalize is True.
# Change dtype to float64 since mean_variance_axis accepts
# it that way.
if sp.isspmatrix(X) and X.getformat() == 'csr':
X = sp.csr_matrix(X, copy=normalize, dtype=np.float64)
else:
X = sp.csc_matrix(X, copy=normalize, dtype=np.float64)
X_offset, X_var = mean_variance_axis(X, axis=0)
if normalize:
# transform variance to std in-place
X_var *= X.shape[0]
X_std = np.sqrt(X_var, X_var)
del X_var
X_std[X_std == 0] = 1
inplace_column_scale(X, 1. / X_std)
else:
X_std = np.ones(X.shape[1])
y_offset = y.mean(axis=0)
y = y - y_offset
else:
X_offset = np.zeros(X.shape[1])
X_std = np.ones(X.shape[1])
y_offset = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype)
return X, y, X_offset, y_offset, X_std | [
"def",
"sparse_center_data",
"(",
"X",
",",
"y",
",",
"fit_intercept",
",",
"normalize",
"=",
"False",
")",
":",
"if",
"fit_intercept",
":",
"# we might require not to change the csr matrix sometimes",
"# store a copy if normalize is True.",
"# Change dtype to float64 since mea... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/base.py#L72-L105 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/lowering.py | python | Lower.storevar | (self, value, name) | Store the value into the given variable. | Store the value into the given variable. | [
"Store",
"the",
"value",
"into",
"the",
"given",
"variable",
"."
] | def storevar(self, value, name):
"""
Store the value into the given variable.
"""
fetype = self.typeof(name)
# Define if not already
self._alloca_var(name, fetype)
# Clean up existing value stored in the variable
old = self.loadvar(name)
self.decref(fetype, old)
# Store variable
ptr = self.getvar(name)
if value.type != ptr.type.pointee:
msg = ("Storing {value.type} to ptr of {ptr.type.pointee} "
"('{name}'). FE type {fetype}").format(value=value,
ptr=ptr,
fetype=fetype,
name=name)
raise AssertionError(msg)
self.builder.store(value, ptr) | [
"def",
"storevar",
"(",
"self",
",",
"value",
",",
"name",
")",
":",
"fetype",
"=",
"self",
".",
"typeof",
"(",
"name",
")",
"# Define if not already",
"self",
".",
"_alloca_var",
"(",
"name",
",",
"fetype",
")",
"# Clean up existing value stored in the variable... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/lowering.py#L1218-L1241 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/utils/lit/lit/ProgressBar.py | python | TerminalController.render | (self, template) | return re.sub(r'\$\$|\${\w+}', self._render_sub, template) | Replace each $-substitutions in the given template string with
the corresponding terminal control string (if it's defined) or
'' (if it's not). | Replace each $-substitutions in the given template string with
the corresponding terminal control string (if it's defined) or
'' (if it's not). | [
"Replace",
"each",
"$",
"-",
"substitutions",
"in",
"the",
"given",
"template",
"string",
"with",
"the",
"corresponding",
"terminal",
"control",
"string",
"(",
"if",
"it",
"s",
"defined",
")",
"or",
"(",
"if",
"it",
"s",
"not",
")",
"."
] | def render(self, template):
"""
Replace each $-substitutions in the given template string with
the corresponding terminal control string (if it's defined) or
'' (if it's not).
"""
return re.sub(r'\$\$|\${\w+}', self._render_sub, template) | [
"def",
"render",
"(",
"self",
",",
"template",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\\$\\$|\\${\\w+}'",
",",
"self",
".",
"_render_sub",
",",
"template",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/lit/lit/ProgressBar.py#L153-L159 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/errcheck.py | python | options | (opt) | Error verification can be enabled by default (not just on ``waf -v``) by adding to the user script options | Error verification can be enabled by default (not just on ``waf -v``) by adding to the user script options | [
"Error",
"verification",
"can",
"be",
"enabled",
"by",
"default",
"(",
"not",
"just",
"on",
"waf",
"-",
"v",
")",
"by",
"adding",
"to",
"the",
"user",
"script",
"options"
] | def options(opt):
"""
Error verification can be enabled by default (not just on ``waf -v``) by adding to the user script options
"""
enhance_lib() | [
"def",
"options",
"(",
"opt",
")",
":",
"enhance_lib",
"(",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/errcheck.py#L232-L236 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | TurtleScreen.onkeypress | (self, fun, key=None) | Bind fun to key-press event of key if key is given,
or to any key-press-event if no key is given.
Arguments:
fun -- a function with no arguments
key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
In order to be able to register key-events, TurtleScreen
must have focus. (See method listen.)
Example (for a TurtleScreen instance named screen
and a Turtle instance named turtle):
>>> def f():
... fd(50)
... lt(60)
...
>>> screen.onkeypress(f, "Up")
>>> screen.listen()
Subsequently the turtle can be moved by repeatedly pressing
the up-arrow key, or by keeping pressed the up-arrow key.
consequently drawing a hexagon. | Bind fun to key-press event of key if key is given,
or to any key-press-event if no key is given. | [
"Bind",
"fun",
"to",
"key",
"-",
"press",
"event",
"of",
"key",
"if",
"key",
"is",
"given",
"or",
"to",
"any",
"key",
"-",
"press",
"-",
"event",
"if",
"no",
"key",
"is",
"given",
"."
] | def onkeypress(self, fun, key=None):
"""Bind fun to key-press event of key if key is given,
or to any key-press-event if no key is given.
Arguments:
fun -- a function with no arguments
key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
In order to be able to register key-events, TurtleScreen
must have focus. (See method listen.)
Example (for a TurtleScreen instance named screen
and a Turtle instance named turtle):
>>> def f():
... fd(50)
... lt(60)
...
>>> screen.onkeypress(f, "Up")
>>> screen.listen()
Subsequently the turtle can be moved by repeatedly pressing
the up-arrow key, or by keeping pressed the up-arrow key.
consequently drawing a hexagon.
"""
if fun is None:
if key in self._keys:
self._keys.remove(key)
elif key is not None and key not in self._keys:
self._keys.append(key)
self._onkeypress(fun, key) | [
"def",
"onkeypress",
"(",
"self",
",",
"fun",
",",
"key",
"=",
"None",
")",
":",
"if",
"fun",
"is",
"None",
":",
"if",
"key",
"in",
"self",
".",
"_keys",
":",
"self",
".",
"_keys",
".",
"remove",
"(",
"key",
")",
"elif",
"key",
"is",
"not",
"No... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L1397-L1427 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/misc_util.py | python | Configuration.have_f77c | (self) | return flag | Check for availability of Fortran 77 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 77 compiler is available (because a simple Fortran 77
code was able to be compiled successfully). | Check for availability of Fortran 77 compiler. | [
"Check",
"for",
"availability",
"of",
"Fortran",
"77",
"compiler",
"."
] | def have_f77c(self):
"""Check for availability of Fortran 77 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 77 compiler is available (because a simple Fortran 77
code was able to be compiled successfully).
"""
simple_fortran_subroutine = '''
subroutine simple
end
'''
config_cmd = self.get_config_cmd()
flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77')
return flag | [
"def",
"have_f77c",
"(",
"self",
")",
":",
"simple_fortran_subroutine",
"=",
"'''\n subroutine simple\n end\n '''",
"config_cmd",
"=",
"self",
".",
"get_config_cmd",
"(",
")",
"flag",
"=",
"config_cmd",
".",
"try_compile",
"(",
"simple_fortran_subrout... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/misc_util.py#L1815-L1832 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/nn.py | python | log_poisson_loss | (log_input, targets, compute_full_loss=False, name=None) | Computes log poisson loss given `log_input`.
Gives the log-likelihood loss between the prediction and the target under the
assumption that the target has a poisson distribution.
Caveat: By default, this is not the exact loss, but the loss minus a
constant term [log(z!)]. That has no effect for optimization, but
does not play well with relative loss comparisons. To compute an
approximation of the log factorial term, specify
compute_full_loss=True to enable Stirling's Approximation.
For brevity, let `c = log(x) = log_input`, `z = targets`. The log poisson
loss is
-log(exp(-x) * (x^z) / z!)
= -log(exp(-x) * (x^z)) + log(z!)
~ -log(exp(-x)) - log(x^z) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
[ Note the second term is the Stirling's Approximation for log(z!).
It is invariant to x and does not affect optimization, though
important for correct relative loss comparisons. It is only
computed when compute_full_loss == True. ]
= x - z * log(x) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
= exp(c) - z * c [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
Args:
log_input: A `Tensor` of type `float32` or `float64`.
targets: A `Tensor` of the same type and shape as `log_input`.
compute_full_loss: whether to compute the full loss. If false, a constant
term is dropped in favor of more efficient optimization.
name: A name for the operation (optional).
Returns:
A `Tensor` of the same shape as `log_input` with the componentwise
logistic losses.
Raises:
ValueError: If `log_input` and `targets` do not have the same shape. | Computes log poisson loss given `log_input`. | [
"Computes",
"log",
"poisson",
"loss",
"given",
"log_input",
"."
] | def log_poisson_loss(log_input, targets, compute_full_loss=False, name=None):
"""Computes log poisson loss given `log_input`.
Gives the log-likelihood loss between the prediction and the target under the
assumption that the target has a poisson distribution.
Caveat: By default, this is not the exact loss, but the loss minus a
constant term [log(z!)]. That has no effect for optimization, but
does not play well with relative loss comparisons. To compute an
approximation of the log factorial term, specify
compute_full_loss=True to enable Stirling's Approximation.
For brevity, let `c = log(x) = log_input`, `z = targets`. The log poisson
loss is
-log(exp(-x) * (x^z) / z!)
= -log(exp(-x) * (x^z)) + log(z!)
~ -log(exp(-x)) - log(x^z) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
[ Note the second term is the Stirling's Approximation for log(z!).
It is invariant to x and does not affect optimization, though
important for correct relative loss comparisons. It is only
computed when compute_full_loss == True. ]
= x - z * log(x) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
= exp(c) - z * c [+ z * log(z) - z + 0.5 * log(2 * pi * z)]
Args:
log_input: A `Tensor` of type `float32` or `float64`.
targets: A `Tensor` of the same type and shape as `log_input`.
compute_full_loss: whether to compute the full loss. If false, a constant
term is dropped in favor of more efficient optimization.
name: A name for the operation (optional).
Returns:
A `Tensor` of the same shape as `log_input` with the componentwise
logistic losses.
Raises:
ValueError: If `log_input` and `targets` do not have the same shape.
"""
with ops.op_scope([log_input, targets], name, "log_poisson_loss") as name:
log_input = ops.convert_to_tensor(log_input, name="log_input")
targets = ops.convert_to_tensor(targets, name="targets")
try:
targets.get_shape().merge_with(log_input.get_shape())
except ValueError:
raise ValueError(
"log_input and targets must have the same shape (%s vs %s)" %
(log_input.get_shape(), targets.get_shape()))
result = math_ops.exp(log_input) - log_input * targets
if compute_full_loss:
# need to create constant tensors here so that their dtypes can be matched
# to that of the targets.
point_five = constant_op.constant(0.5, dtype=targets.dtype)
two_pi = constant_op.constant(2 * math.pi, dtype=targets.dtype)
stirling_approx = (targets * math_ops.log(targets)) - targets + (
point_five * math_ops.log(two_pi * targets))
zeros = array_ops.zeros_like(targets, dtype=targets.dtype)
ones = array_ops.ones_like(targets, dtype=targets.dtype)
cond = math_ops.logical_and(targets >= zeros, targets <= ones)
result += math_ops.select(cond, zeros, stirling_approx)
return result | [
"def",
"log_poisson_loss",
"(",
"log_input",
",",
"targets",
",",
"compute_full_loss",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"log_input",
",",
"targets",
"]",
",",
"name",
",",
"\"log_poisson_loss\"",
"... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/nn.py#L314-L375 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.setSGroupXCoord | (self, x) | return self.dispatcher._checkResult(
Indigo._lib.indigoSetSGroupXCoord(self.id, x)
) | Sgroup method sets X coordinate
Args:
x (float): X coordinate
Returns:
int: 1 if there are no errors | Sgroup method sets X coordinate | [
"Sgroup",
"method",
"sets",
"X",
"coordinate"
] | def setSGroupXCoord(self, x):
"""Sgroup method sets X coordinate
Args:
x (float): X coordinate
Returns:
int: 1 if there are no errors
"""
self.dispatcher._setSessionId()
return self.dispatcher._checkResult(
Indigo._lib.indigoSetSGroupXCoord(self.id, x)
) | [
"def",
"setSGroupXCoord",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"dispatcher",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoSetSGroupXCoord",
"(",
"self",
".",
"id"... | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L1815-L1827 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/range.py | python | RangeIndex.__len__ | (self) | return len(self._range) | return the length of the RangeIndex | return the length of the RangeIndex | [
"return",
"the",
"length",
"of",
"the",
"RangeIndex"
] | def __len__(self) -> int:
"""
return the length of the RangeIndex
"""
return len(self._range) | [
"def",
"__len__",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"_range",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/range.py#L675-L679 | |
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/internal/decoder.py | python | Decoder.ReadSInt32 | (self) | return wire_format.ZigZagDecode(self._stream.ReadVarUInt32()) | Reads and returns a signed, zigzag-encoded, varint-encoded,
32-bit integer. | Reads and returns a signed, zigzag-encoded, varint-encoded,
32-bit integer. | [
"Reads",
"and",
"returns",
"a",
"signed",
"zigzag",
"-",
"encoded",
"varint",
"-",
"encoded",
"32",
"-",
"bit",
"integer",
"."
] | def ReadSInt32(self):
"""Reads and returns a signed, zigzag-encoded, varint-encoded,
32-bit integer."""
return wire_format.ZigZagDecode(self._stream.ReadVarUInt32()) | [
"def",
"ReadSInt32",
"(",
"self",
")",
":",
"return",
"wire_format",
".",
"ZigZagDecode",
"(",
"self",
".",
"_stream",
".",
"ReadVarUInt32",
"(",
")",
")"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/decoder.py#L103-L106 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextPlainText.SetText | (*args, **kwargs) | return _richtext.RichTextPlainText_SetText(*args, **kwargs) | SetText(self, String text) | SetText(self, String text) | [
"SetText",
"(",
"self",
"String",
"text",
")"
] | def SetText(*args, **kwargs):
"""SetText(self, String text)"""
return _richtext.RichTextPlainText_SetText(*args, **kwargs) | [
"def",
"SetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextPlainText_SetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2100-L2102 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | Position.checkskip | (self, string) | return True | Check for a string at the given position; if there, skip it | Check for a string at the given position; if there, skip it | [
"Check",
"for",
"a",
"string",
"at",
"the",
"given",
"position",
";",
"if",
"there",
"skip",
"it"
] | def checkskip(self, string):
"Check for a string at the given position; if there, skip it"
if not self.checkfor(string):
return False
self.skip(string)
return True | [
"def",
"checkskip",
"(",
"self",
",",
"string",
")",
":",
"if",
"not",
"self",
".",
"checkfor",
"(",
"string",
")",
":",
"return",
"False",
"self",
".",
"skip",
"(",
"string",
")",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L2065-L2070 | |
dicecco1/fpga_caffe | 7a191704efd7873071cfef35772d7e7bf3e3cfd6 | scripts/cpp_lint.py | python | CheckForBadCharacters | (filename, lines, error) | Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error for each line containing bad characters. | [
"Logs",
"an",
"error",
"for",
"each",
"line",
"containing",
"bad",
"characters",
"."
] | def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') | [
"def",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"for",
"linenum",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"u'\\ufffd'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'reada... | https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/scripts/cpp_lint.py#L1487-L1509 | ||
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/mox.py | python | UnorderedGroup.IsSatisfied | (self) | return len(self._methods) == 0 | Return True if there are not any methods in this group. | Return True if there are not any methods in this group. | [
"Return",
"True",
"if",
"there",
"are",
"not",
"any",
"methods",
"in",
"this",
"group",
"."
] | def IsSatisfied(self):
"""Return True if there are not any methods in this group."""
return len(self._methods) == 0 | [
"def",
"IsSatisfied",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_methods",
")",
"==",
"0"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/mox.py#L1257-L1260 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/magics/basic.py | python | MagicsDisplay._jsonable | (self) | return magic_dict | turn magics dict into jsonable dict of the same structure
replaces object instances with their class names as strings | turn magics dict into jsonable dict of the same structure
replaces object instances with their class names as strings | [
"turn",
"magics",
"dict",
"into",
"jsonable",
"dict",
"of",
"the",
"same",
"structure",
"replaces",
"object",
"instances",
"with",
"their",
"class",
"names",
"as",
"strings"
] | def _jsonable(self):
"""turn magics dict into jsonable dict of the same structure
replaces object instances with their class names as strings
"""
magic_dict = {}
mman = self.magics_manager
magics = mman.lsmagic()
for key, subdict in magics.items():
d = {}
magic_dict[key] = d
for name, obj in subdict.items():
try:
classname = obj.__self__.__class__.__name__
except AttributeError:
classname = 'Other'
d[name] = classname
return magic_dict | [
"def",
"_jsonable",
"(",
"self",
")",
":",
"magic_dict",
"=",
"{",
"}",
"mman",
"=",
"self",
".",
"magics_manager",
"magics",
"=",
"mman",
".",
"lsmagic",
"(",
")",
"for",
"key",
",",
"subdict",
"in",
"magics",
".",
"items",
"(",
")",
":",
"d",
"="... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/magics/basic.py#L47-L65 | |
Harick1/caffe-yolo | eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3 | python/draw_net.py | python | parse_args | () | return args | Parse input arguments | Parse input arguments | [
"Parse",
"input",
"arguments"
] | def parse_args():
"""Parse input arguments
"""
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('input_net_proto_file',
help='Input network prototxt file')
parser.add_argument('output_image_file',
help='Output image file')
parser.add_argument('--rankdir',
help=('One of TB (top-bottom, i.e., vertical), '
'RL (right-left, i.e., horizontal), or another '
'valid dot option; see '
'http://www.graphviz.org/doc/info/'
'attrs.html#k:rankdir'),
default='LR')
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'input_net_proto_file'",
",",
"help",
"=",
"'Input networ... | https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/python/draw_net.py#L13-L33 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/reductions/solvers/conic_solvers/cvxopt_conif.py | python | CVXOPT.name | (self) | return s.CVXOPT | The name of the solver. | The name of the solver. | [
"The",
"name",
"of",
"the",
"solver",
"."
] | def name(self):
"""The name of the solver.
"""
return s.CVXOPT | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"s",
".",
"CVXOPT"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/reductions/solvers/conic_solvers/cvxopt_conif.py#L68-L71 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchWall.py | python | _CommandWall.setHeight | (self,d) | Simple callback for the interactive mode gui widget to set height. | Simple callback for the interactive mode gui widget to set height. | [
"Simple",
"callback",
"for",
"the",
"interactive",
"mode",
"gui",
"widget",
"to",
"set",
"height",
"."
] | def setHeight(self,d):
"""Simple callback for the interactive mode gui widget to set height."""
self.Height = d
self.tracker.height(d)
FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").SetFloat("WallHeight",d) | [
"def",
"setHeight",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"Height",
"=",
"d",
"self",
".",
"tracker",
".",
"height",
"(",
"d",
")",
"FreeCAD",
".",
"ParamGet",
"(",
"\"User parameter:BaseApp/Preferences/Mod/Arch\"",
")",
".",
"SetFloat",
"(",
"\"Wa... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchWall.py#L574-L579 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py | python | Buffer.cursor_down | (self, count: int = 1) | (for multiline edit). Move cursor to the next line. | (for multiline edit). Move cursor to the next line. | [
"(",
"for",
"multiline",
"edit",
")",
".",
"Move",
"cursor",
"to",
"the",
"next",
"line",
"."
] | def cursor_down(self, count: int = 1) -> None:
"""(for multiline edit). Move cursor to the next line."""
original_column = self.preferred_column or self.document.cursor_position_col
self.cursor_position += self.document.get_cursor_down_position(
count=count, preferred_column=original_column
)
# Remember the original column for the next up/down movement.
self.preferred_column = original_column | [
"def",
"cursor_down",
"(",
"self",
",",
"count",
":",
"int",
"=",
"1",
")",
"->",
"None",
":",
"original_column",
"=",
"self",
".",
"preferred_column",
"or",
"self",
".",
"document",
".",
"cursor_position_col",
"self",
".",
"cursor_position",
"+=",
"self",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py#L737-L745 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/_sys_util.py | python | make_unity_server_env | () | return env | Returns the environment for unity_server.
The environment is necessary to start the unity_server
by setting the proper environments for shared libraries,
hadoop classpath, and module search paths for python lambda workers.
The environment has 3 components:
1. CLASSPATH, contains hadoop class path
2. __GL_PYTHON_EXECUTABLE__, path to the python executable
3. __GL_PYLAMBDA_SCRIPT__, path to the lambda worker executable
4. __GL_SYS_PATH__: contains the python sys.path of the interpreter | Returns the environment for unity_server. | [
"Returns",
"the",
"environment",
"for",
"unity_server",
"."
] | def make_unity_server_env():
"""
Returns the environment for unity_server.
The environment is necessary to start the unity_server
by setting the proper environments for shared libraries,
hadoop classpath, and module search paths for python lambda workers.
The environment has 3 components:
1. CLASSPATH, contains hadoop class path
2. __GL_PYTHON_EXECUTABLE__, path to the python executable
3. __GL_PYLAMBDA_SCRIPT__, path to the lambda worker executable
4. __GL_SYS_PATH__: contains the python sys.path of the interpreter
"""
env = os.environ.copy()
# Add hadoop class path
classpath = get_hadoop_class_path()
if "CLASSPATH" in env:
env["CLASSPATH"] = env["CLASSPATH"] + (
os.path.pathsep + classpath if classpath != "" else ""
)
else:
env["CLASSPATH"] = classpath
# Add python syspath
env["__GL_SYS_PATH__"] = (os.path.pathsep).join(sys.path + [os.getcwd()])
# Add the python executable to the runtime config
env["__GL_PYTHON_EXECUTABLE__"] = os.path.abspath(sys.executable)
# Add the pylambda execution script to the runtime config
env["__GL_PYLAMBDA_SCRIPT__"] = os.path.abspath(_pylambda_worker.__file__)
#### Remove PYTHONEXECUTABLE ####
# Anaconda overwrites this environment variable
# which forces all python sub-processes to use the same binary.
# When using virtualenv with ipython (which is outside virtualenv),
# all subprocess launched under unity_server will use the
# conda binary outside of virtualenv, which lacks the access
# to all packages installed inside virtualenv.
if "PYTHONEXECUTABLE" in env:
del env["PYTHONEXECUTABLE"]
# add certificate file
if (
"TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE" not in env
and "TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR" not in env
):
try:
import certifi
env["TURI_FILEIO_ALTERNATIVE_SSL_CERT_FILE"] = certifi.where()
env["TURI_FILEIO_ALTERNATIVE_SSL_CERT_DIR"] = ""
except:
pass
return env | [
"def",
"make_unity_server_env",
"(",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"# Add hadoop class path",
"classpath",
"=",
"get_hadoop_class_path",
"(",
")",
"if",
"\"CLASSPATH\"",
"in",
"env",
":",
"env",
"[",
"\"CLASSPATH\"",
"]",
... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/_sys_util.py#L23-L79 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.