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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/calendar.py | python | GenericCalendarCtrl.EnableYearChange | (*args, **kwargs) | return _calendar.GenericCalendarCtrl_EnableYearChange(*args, **kwargs) | EnableYearChange(self, bool enable=True)
This function should be used instead of changing CAL_NO_YEAR_CHANGE
style bit directly. It allows or disallows the user to change the year
interactively. | EnableYearChange(self, bool enable=True) | [
"EnableYearChange",
"(",
"self",
"bool",
"enable",
"=",
"True",
")"
] | def EnableYearChange(*args, **kwargs):
"""
EnableYearChange(self, bool enable=True)
This function should be used instead of changing CAL_NO_YEAR_CHANGE
style bit directly. It allows or disallows the user to change the year
interactively.
"""
return _calendar.GenericCalendarCtrl_EnableYearChange(*args, **kwargs) | [
"def",
"EnableYearChange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"GenericCalendarCtrl_EnableYearChange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/calendar.py#L547-L555 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py | python | FitPropertyBrowser.set_fit_range | (self, fit_range) | Sets the range to fit in the FitPropertyBrowser
:param fit_range: The new fit range | Sets the range to fit in the FitPropertyBrowser
:param fit_range: The new fit range | [
"Sets",
"the",
"range",
"to",
"fit",
"in",
"the",
"FitPropertyBrowser",
":",
"param",
"fit_range",
":",
"The",
"new",
"fit",
"range"
] | def set_fit_range(self, fit_range):
"""
Sets the range to fit in the FitPropertyBrowser
:param fit_range: The new fit range
"""
if fit_range is not None:
self.setXRange(fit_range[0], fit_range[1]) | [
"def",
"set_fit_range",
"(",
"self",
",",
"fit_range",
")",
":",
"if",
"fit_range",
"is",
"not",
"None",
":",
"self",
".",
"setXRange",
"(",
"fit_range",
"[",
"0",
"]",
",",
"fit_range",
"[",
"1",
"]",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py#L264-L270 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/generic.py | python | NDFrame.pct_change | (
self: FrameOrSeries,
periods=1,
fill_method="pad",
limit=None,
freq=None,
**kwargs,
) | return rs | Percentage change between the current and a prior element.
Computes the percentage change from the immediately previous row by
default. This is useful in comparing the percentage of change in a time
series of elements.
Parameters
----------
periods : int, default 1
Periods to shift for forming percent change.
fill_method : str, default 'pad'
How to handle NAs before computing percent changes.
limit : int, default None
The number of consecutive NAs to fill before stopping.
freq : DateOffset, timedelta, or str, optional
Increment to use from time series API (e.g. 'M' or BDay()).
**kwargs
Additional keyword arguments are passed into
`DataFrame.shift` or `Series.shift`.
Returns
-------
chg : Series or DataFrame
The same type as the calling object.
See Also
--------
Series.diff : Compute the difference of two elements in a Series.
DataFrame.diff : Compute the difference of two elements in a DataFrame.
Series.shift : Shift the index by some number of periods.
DataFrame.shift : Shift the index by some number of periods.
Examples
--------
**Series**
>>> s = pd.Series([90, 91, 85])
>>> s
0 90
1 91
2 85
dtype: int64
>>> s.pct_change()
0 NaN
1 0.011111
2 -0.065934
dtype: float64
>>> s.pct_change(periods=2)
0 NaN
1 NaN
2 -0.055556
dtype: float64
See the percentage change in a Series where filling NAs with last
valid observation forward to next valid.
>>> s = pd.Series([90, 91, None, 85])
>>> s
0 90.0
1 91.0
2 NaN
3 85.0
dtype: float64
>>> s.pct_change(fill_method='ffill')
0 NaN
1 0.011111
2 0.000000
3 -0.065934
dtype: float64
**DataFrame**
Percentage change in French franc, Deutsche Mark, and Italian lira from
1980-01-01 to 1980-03-01.
>>> df = pd.DataFrame({
... 'FR': [4.0405, 4.0963, 4.3149],
... 'GR': [1.7246, 1.7482, 1.8519],
... 'IT': [804.74, 810.01, 860.13]},
... index=['1980-01-01', '1980-02-01', '1980-03-01'])
>>> df
FR GR IT
1980-01-01 4.0405 1.7246 804.74
1980-02-01 4.0963 1.7482 810.01
1980-03-01 4.3149 1.8519 860.13
>>> df.pct_change()
FR GR IT
1980-01-01 NaN NaN NaN
1980-02-01 0.013810 0.013684 0.006549
1980-03-01 0.053365 0.059318 0.061876
Percentage of change in GOOG and APPL stock volume. Shows computing
the percentage change between columns.
>>> df = pd.DataFrame({
... '2016': [1769950, 30586265],
... '2015': [1500923, 40912316],
... '2014': [1371819, 41403351]},
... index=['GOOG', 'APPL'])
>>> df
2016 2015 2014
GOOG 1769950 1500923 1371819
APPL 30586265 40912316 41403351
>>> df.pct_change(axis='columns', periods=-1)
2016 2015 2014
GOOG 0.179241 0.094112 NaN
APPL -0.252395 -0.011860 NaN | Percentage change between the current and a prior element. | [
"Percentage",
"change",
"between",
"the",
"current",
"and",
"a",
"prior",
"element",
"."
] | def pct_change(
self: FrameOrSeries,
periods=1,
fill_method="pad",
limit=None,
freq=None,
**kwargs,
) -> FrameOrSeries:
"""
Percentage change between the current and a prior element.
Computes the percentage change from the immediately previous row by
default. This is useful in comparing the percentage of change in a time
series of elements.
Parameters
----------
periods : int, default 1
Periods to shift for forming percent change.
fill_method : str, default 'pad'
How to handle NAs before computing percent changes.
limit : int, default None
The number of consecutive NAs to fill before stopping.
freq : DateOffset, timedelta, or str, optional
Increment to use from time series API (e.g. 'M' or BDay()).
**kwargs
Additional keyword arguments are passed into
`DataFrame.shift` or `Series.shift`.
Returns
-------
chg : Series or DataFrame
The same type as the calling object.
See Also
--------
Series.diff : Compute the difference of two elements in a Series.
DataFrame.diff : Compute the difference of two elements in a DataFrame.
Series.shift : Shift the index by some number of periods.
DataFrame.shift : Shift the index by some number of periods.
Examples
--------
**Series**
>>> s = pd.Series([90, 91, 85])
>>> s
0 90
1 91
2 85
dtype: int64
>>> s.pct_change()
0 NaN
1 0.011111
2 -0.065934
dtype: float64
>>> s.pct_change(periods=2)
0 NaN
1 NaN
2 -0.055556
dtype: float64
See the percentage change in a Series where filling NAs with last
valid observation forward to next valid.
>>> s = pd.Series([90, 91, None, 85])
>>> s
0 90.0
1 91.0
2 NaN
3 85.0
dtype: float64
>>> s.pct_change(fill_method='ffill')
0 NaN
1 0.011111
2 0.000000
3 -0.065934
dtype: float64
**DataFrame**
Percentage change in French franc, Deutsche Mark, and Italian lira from
1980-01-01 to 1980-03-01.
>>> df = pd.DataFrame({
... 'FR': [4.0405, 4.0963, 4.3149],
... 'GR': [1.7246, 1.7482, 1.8519],
... 'IT': [804.74, 810.01, 860.13]},
... index=['1980-01-01', '1980-02-01', '1980-03-01'])
>>> df
FR GR IT
1980-01-01 4.0405 1.7246 804.74
1980-02-01 4.0963 1.7482 810.01
1980-03-01 4.3149 1.8519 860.13
>>> df.pct_change()
FR GR IT
1980-01-01 NaN NaN NaN
1980-02-01 0.013810 0.013684 0.006549
1980-03-01 0.053365 0.059318 0.061876
Percentage of change in GOOG and APPL stock volume. Shows computing
the percentage change between columns.
>>> df = pd.DataFrame({
... '2016': [1769950, 30586265],
... '2015': [1500923, 40912316],
... '2014': [1371819, 41403351]},
... index=['GOOG', 'APPL'])
>>> df
2016 2015 2014
GOOG 1769950 1500923 1371819
APPL 30586265 40912316 41403351
>>> df.pct_change(axis='columns', periods=-1)
2016 2015 2014
GOOG 0.179241 0.094112 NaN
APPL -0.252395 -0.011860 NaN
"""
axis = self._get_axis_number(kwargs.pop("axis", self._stat_axis_name))
if fill_method is None:
data = self
else:
_data = self.fillna(method=fill_method, axis=axis, limit=limit)
assert _data is not None # needed for mypy
data = _data
shifted = data.shift(periods=periods, freq=freq, axis=axis, **kwargs)
# Unsupported left operand type for / ("FrameOrSeries")
rs = data / shifted - 1 # type: ignore[operator]
if freq is not None:
# Shift method is implemented differently when freq is not None
# We want to restore the original index
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(data)
return rs | [
"def",
"pct_change",
"(",
"self",
":",
"FrameOrSeries",
",",
"periods",
"=",
"1",
",",
"fill_method",
"=",
"\"pad\"",
",",
"limit",
"=",
"None",
",",
"freq",
"=",
"None",
",",
"*",
"*",
"kwargs",
",",
")",
"->",
"FrameOrSeries",
":",
"axis",
"=",
"se... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L10033-L10171 | |
yushroom/FishEngine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | Script/reflect/clang/cindex.py | python | Index.create | (excludeDecls=False) | return Index(conf.lib.clang_createIndex(excludeDecls, 0)) | Create a new Index.
Parameters:
excludeDecls -- Exclude local declarations from translation units. | Create a new Index.
Parameters:
excludeDecls -- Exclude local declarations from translation units. | [
"Create",
"a",
"new",
"Index",
".",
"Parameters",
":",
"excludeDecls",
"--",
"Exclude",
"local",
"declarations",
"from",
"translation",
"units",
"."
] | def create(excludeDecls=False):
"""
Create a new Index.
Parameters:
excludeDecls -- Exclude local declarations from translation units.
"""
return Index(conf.lib.clang_createIndex(excludeDecls, 0)) | [
"def",
"create",
"(",
"excludeDecls",
"=",
"False",
")",
":",
"return",
"Index",
"(",
"conf",
".",
"lib",
".",
"clang_createIndex",
"(",
"excludeDecls",
",",
"0",
")",
")"
] | https://github.com/yushroom/FishEngine/blob/a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9/Script/reflect/clang/cindex.py#L2421-L2427 | |
facebook/watchman | 0917460c71b000b96be9b9575d77f06f2f6053bb | build/fbcode_builder/getdeps/fetcher.py | python | Fetcher.get_src_dir | (self) | Returns the source directory that the project was
extracted into | Returns the source directory that the project was
extracted into | [
"Returns",
"the",
"source",
"directory",
"that",
"the",
"project",
"was",
"extracted",
"into"
] | def get_src_dir(self):
"""Returns the source directory that the project was
extracted into"""
pass | [
"def",
"get_src_dir",
"(",
"self",
")",
":",
"pass"
] | https://github.com/facebook/watchman/blob/0917460c71b000b96be9b9575d77f06f2f6053bb/build/fbcode_builder/getdeps/fetcher.py#L131-L134 | ||
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/aio/_call.py | python | AioRpcError.details | (self) | return self._details | Accesses the details sent by the server.
Returns:
The description of the error. | Accesses the details sent by the server. | [
"Accesses",
"the",
"details",
"sent",
"by",
"the",
"server",
"."
] | def details(self) -> Optional[str]:
"""Accesses the details sent by the server.
Returns:
The description of the error.
"""
return self._details | [
"def",
"details",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_details"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_call.py#L104-L110 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/jax/deep_cfr.py | python | DeepCFRSolver._serialize_strategy_memory | (self, info_state, iteration,
strategy_action_probs, legal_actions_mask) | return example.SerializeToString() | Create serialized example to store a strategy entry. | Create serialized example to store a strategy entry. | [
"Create",
"serialized",
"example",
"to",
"store",
"a",
"strategy",
"entry",
"."
] | def _serialize_strategy_memory(self, info_state, iteration,
strategy_action_probs, legal_actions_mask):
"""Create serialized example to store a strategy entry."""
example = tf.train.Example(
features=tf.train.Features(
feature={
'info_state':
tf.train.Feature(
float_list=tf.train.FloatList(value=info_state)),
'action_probs':
tf.train.Feature(
float_list=tf.train.FloatList(
value=strategy_action_probs)),
'iteration':
tf.train.Feature(
float_list=tf.train.FloatList(value=[iteration])),
'legal_actions':
tf.train.Feature(
float_list=tf.train.FloatList(value=legal_actions_mask))
}))
return example.SerializeToString() | [
"def",
"_serialize_strategy_memory",
"(",
"self",
",",
"info_state",
",",
"iteration",
",",
"strategy_action_probs",
",",
"legal_actions_mask",
")",
":",
"example",
"=",
"tf",
".",
"train",
".",
"Example",
"(",
"features",
"=",
"tf",
".",
"train",
".",
"Featur... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/jax/deep_cfr.py#L381-L401 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py | python | matchPreviousLiteral | (expr) | return rep | Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
will match C{"1:1"}, but not C{"1:2"}. Because this matches a
previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
If this is not desired, use C{matchPreviousExpr}.
Do I{not} use with packrat parsing enabled. | Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
will match C{"1:1"}, but not C{"1:2"}. Because this matches a
previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
If this is not desired, use C{matchPreviousExpr}.
Do I{not} use with packrat parsing enabled. | [
"Helper",
"to",
"define",
"an",
"expression",
"that",
"is",
"indirectly",
"defined",
"from",
"the",
"tokens",
"matched",
"in",
"a",
"previous",
"expression",
"that",
"is",
"it",
"looks",
"for",
"a",
"repeat",
"of",
"a",
"previous",
"expression",
".",
"For",
... | def matchPreviousLiteral(expr):
"""
Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
will match C{"1:1"}, but not C{"1:2"}. Because this matches a
previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
If this is not desired, use C{matchPreviousExpr}.
Do I{not} use with packrat parsing enabled.
"""
rep = Forward()
def copyTokenToRepeater(s,l,t):
if t:
if len(t) == 1:
rep << t[0]
else:
# flatten t tokens
tflat = _flatten(t.asList())
rep << And(Literal(tt) for tt in tflat)
else:
rep << Empty()
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
rep.setName('(prev) ' + _ustr(expr))
return rep | [
"def",
"matchPreviousLiteral",
"(",
"expr",
")",
":",
"rep",
"=",
"Forward",
"(",
")",
"def",
"copyTokenToRepeater",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"if",
"t",
":",
"if",
"len",
"(",
"t",
")",
"==",
"1",
":",
"rep",
"<<",
"t",
"[",
"0",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L4509-L4535 | |
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/wall.py | python | _WallsMetaList._get_obj_backend_index | (self, frontend_index, new_type, old_type=None) | Find the correct backend index while adjusting other indices.
The method increments all backend indices of the same type that come
after ``frontend_index``, and decrements all indices of the same type as
``old_type`` if provided. | Find the correct backend index while adjusting other indices. | [
"Find",
"the",
"correct",
"backend",
"index",
"while",
"adjusting",
"other",
"indices",
"."
] | def _get_obj_backend_index(self, frontend_index, new_type, old_type=None):
"""Find the correct backend index while adjusting other indices.
The method increments all backend indices of the same type that come
after ``frontend_index``, and decrements all indices of the same type as
``old_type`` if provided.
"""
backend_index = None
# Check for next index that is of the same type as the new wall,
# while incrementing or decrementing the indices of the appropriate
# type.
for bi in self._backend_list_index[frontend_index:]:
if bi.type == new_type:
if backend_index is None:
backend_index = copy(bi)
bi.index += 1
elif old_type is not None and bi.type == old_type:
bi.index -= 1
# If we did not find a _MetaListIndex of the appropriate type check
# before the index in the list for a _MetaListIndex of the correct type.
if backend_index is not None:
return backend_index
for bi in self._backend_list_index[frontend_index - 1::-1]:
if bi.type == new_type:
backend_index = copy(bi)
backend_index.index += 1
return backend_index
# No other object of this wall type currently exists create a new
# index object to use.
else:
return _MetaListIndex(new_type) | [
"def",
"_get_obj_backend_index",
"(",
"self",
",",
"frontend_index",
",",
"new_type",
",",
"old_type",
"=",
"None",
")",
":",
"backend_index",
"=",
"None",
"# Check for next index that is of the same type as the new wall,",
"# while incrementing or decrementing the indices of the... | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/wall.py#L455-L486 | ||
Illumina/hap.py | 84011695b2ff2406c16a335106db6831fb67fdfe | src/python/Tools/fastasize.py | python | fastaNonNContigLengths | (fastafile) | return fastacontiglengths | Return contig lengths in a fasta file excluding
Ns in the beginning or end | Return contig lengths in a fasta file excluding
Ns in the beginning or end | [
"Return",
"contig",
"lengths",
"in",
"a",
"fasta",
"file",
"excluding",
"Ns",
"in",
"the",
"beginning",
"or",
"end"
] | def fastaNonNContigLengths(fastafile):
""" Return contig lengths in a fasta file excluding
Ns in the beginning or end
"""
if not os.path.exists(fastafile + ".fai"):
raise Exception("Fasta file %s is not indexed" % fastafile)
fastacontiglengths = {}
tf = tempfile.NamedTemporaryFile(delete=False)
tf.close()
try:
subprocess.check_call("fastainfo %s %s" % (pipes.quote(fastafile), pipes.quote(tf.name)), shell=True)
with open(tf.name) as f:
fasta_info = json.load(f)
for k, v in fasta_info.iteritems():
fastacontiglengths[k] = int(v["n_trimmed_length"])
finally:
os.unlink(tf.name)
return fastacontiglengths | [
"def",
"fastaNonNContigLengths",
"(",
"fastafile",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fastafile",
"+",
"\".fai\"",
")",
":",
"raise",
"Exception",
"(",
"\"Fasta file %s is not indexed\"",
"%",
"fastafile",
")",
"fastacontiglengths",
"... | https://github.com/Illumina/hap.py/blob/84011695b2ff2406c16a335106db6831fb67fdfe/src/python/Tools/fastasize.py#L50-L72 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/compiler/pycodegen.py | python | generateArgList | (arglist) | return args + extra, count | Generate an arg list marking TupleArgs | Generate an arg list marking TupleArgs | [
"Generate",
"an",
"arg",
"list",
"marking",
"TupleArgs"
] | def generateArgList(arglist):
"""Generate an arg list marking TupleArgs"""
args = []
extra = []
count = 0
for i in range(len(arglist)):
elt = arglist[i]
if isinstance(elt, str):
args.append(elt)
elif isinstance(elt, tuple):
args.append(TupleArg(i * 2, elt))
extra.extend(misc.flatten(elt))
count = count + 1
else:
raise ValueError, "unexpect argument type:", elt
return args + extra, count | [
"def",
"generateArgList",
"(",
"arglist",
")",
":",
"args",
"=",
"[",
"]",
"extra",
"=",
"[",
"]",
"count",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arglist",
")",
")",
":",
"elt",
"=",
"arglist",
"[",
"i",
"]",
"if",
"isinstance",
... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/compiler/pycodegen.py#L1455-L1470 | |
dmlc/treelite | df56babb6a4a2d7c29d719c28ce53acfa7dbab3c | python/treelite/frontend.py | python | Model.serialize | (self, filename) | Serialize (persist) the model to a checkpoint file in the disk, using a fast binary
representation. To recover the model from the checkpoint, use :py:func:`deserialize`
method.
.. note:: Use exactly matching versions of Treelite when exchanging checkpoints
We provide ZERO backward compatibility guarantee. You will not be able to recover
the model from a checkpoint that was generated by a previous version of Treelite. Both
the producer and the consumer of the checkpoint must have the identical major and minor
versions of Treelite.
Parameters
----------
filename : :py:class:`str <python:str>`
Path to checkpoint | Serialize (persist) the model to a checkpoint file in the disk, using a fast binary
representation. To recover the model from the checkpoint, use :py:func:`deserialize`
method. | [
"Serialize",
"(",
"persist",
")",
"the",
"model",
"to",
"a",
"checkpoint",
"file",
"in",
"the",
"disk",
"using",
"a",
"fast",
"binary",
"representation",
".",
"To",
"recover",
"the",
"model",
"from",
"the",
"checkpoint",
"use",
":",
"py",
":",
"func",
":... | def serialize(self, filename):
"""
Serialize (persist) the model to a checkpoint file in the disk, using a fast binary
representation. To recover the model from the checkpoint, use :py:func:`deserialize`
method.
.. note:: Use exactly matching versions of Treelite when exchanging checkpoints
We provide ZERO backward compatibility guarantee. You will not be able to recover
the model from a checkpoint that was generated by a previous version of Treelite. Both
the producer and the consumer of the checkpoint must have the identical major and minor
versions of Treelite.
Parameters
----------
filename : :py:class:`str <python:str>`
Path to checkpoint
"""
_check_call(_LIB.TreeliteSerializeModel(c_str(filename), self.handle)) | [
"def",
"serialize",
"(",
"self",
",",
"filename",
")",
":",
"_check_call",
"(",
"_LIB",
".",
"TreeliteSerializeModel",
"(",
"c_str",
"(",
"filename",
")",
",",
"self",
".",
"handle",
")",
")"
] | https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/treelite/frontend.py#L58-L76 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/automate/automate-git.py | python | is_git_checkout | (path) | return os.path.exists(os.path.join(path, '.git')) | Returns true if the path represents a git checkout. | Returns true if the path represents a git checkout. | [
"Returns",
"true",
"if",
"the",
"path",
"represents",
"a",
"git",
"checkout",
"."
] | def is_git_checkout(path):
""" Returns true if the path represents a git checkout. """
return os.path.exists(os.path.join(path, '.git')) | [
"def",
"is_git_checkout",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'.git'",
")",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/automate/automate-git.py#L97-L99 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/random_ops.py | python | random_crop | (value, size, seed=None, name=None) | Randomly crops a tensor to a given size.
Slices a shape `size` portion out of `value` at a uniformly chosen offset.
Requires `value.shape >= size`.
If a dimension should not be cropped, pass the full size of that dimension.
For example, RGB images can be cropped with
`size = [crop_height, crop_width, 3]`.
Example usage:
>>> image = [[1, 2, 3], [4, 5, 6]]
>>> result = tf.image.random_crop(value=image, size=(1, 3))
>>> result.shape.as_list()
[1, 3]
For producing deterministic results given a `seed` value, use
`tf.image.stateless_random_crop`. Unlike using the `seed` param with
`tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the same
results given the same seed independent of how many times the function is
called, and independent of global seed settings (e.g. tf.random.set_seed).
Args:
value: Input tensor to crop.
size: 1-D tensor with size the rank of `value`.
seed: Python integer. Used to create a random seed. See
`tf.random.set_seed`
for behavior.
name: A name for this operation (optional).
Returns:
A cropped tensor of the same rank as `value` and shape `size`. | Randomly crops a tensor to a given size. | [
"Randomly",
"crops",
"a",
"tensor",
"to",
"a",
"given",
"size",
"."
] | def random_crop(value, size, seed=None, name=None):
"""Randomly crops a tensor to a given size.
Slices a shape `size` portion out of `value` at a uniformly chosen offset.
Requires `value.shape >= size`.
If a dimension should not be cropped, pass the full size of that dimension.
For example, RGB images can be cropped with
`size = [crop_height, crop_width, 3]`.
Example usage:
>>> image = [[1, 2, 3], [4, 5, 6]]
>>> result = tf.image.random_crop(value=image, size=(1, 3))
>>> result.shape.as_list()
[1, 3]
For producing deterministic results given a `seed` value, use
`tf.image.stateless_random_crop`. Unlike using the `seed` param with
`tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the same
results given the same seed independent of how many times the function is
called, and independent of global seed settings (e.g. tf.random.set_seed).
Args:
value: Input tensor to crop.
size: 1-D tensor with size the rank of `value`.
seed: Python integer. Used to create a random seed. See
`tf.random.set_seed`
for behavior.
name: A name for this operation (optional).
Returns:
A cropped tensor of the same rank as `value` and shape `size`.
"""
with ops.name_scope(name, "random_crop", [value, size]) as name:
value = ops.convert_to_tensor(value, name="value")
size = ops.convert_to_tensor(size, dtype=dtypes.int32, name="size")
shape = array_ops.shape(value)
check = control_flow_ops.Assert(
math_ops.reduce_all(shape >= size),
["Need value.shape >= size, got ", shape, size],
summarize=1000)
shape = control_flow_ops.with_dependencies([check], shape)
limit = shape - size + 1
offset = random_uniform(
array_ops.shape(shape),
dtype=size.dtype,
maxval=size.dtype.max,
seed=seed) % limit
return array_ops.slice(value, offset, size, name=name) | [
"def",
"random_crop",
"(",
"value",
",",
"size",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"random_crop\"",
",",
"[",
"value",
",",
"size",
"]",
")",
"as",
"name",
":",
"valu... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/random_ops.py#L363-L412 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | RobotModelDriver.robot | (self) | return _robotsim.RobotModelDriver_robot(self) | robot(RobotModelDriver self) -> RobotModel
Returns a reference to the driver's robot. | robot(RobotModelDriver self) -> RobotModel | [
"robot",
"(",
"RobotModelDriver",
"self",
")",
"-",
">",
"RobotModel"
] | def robot(self):
"""
robot(RobotModelDriver self) -> RobotModel
Returns a reference to the driver's robot.
"""
return _robotsim.RobotModelDriver_robot(self) | [
"def",
"robot",
"(",
"self",
")",
":",
"return",
"_robotsim",
".",
"RobotModelDriver_robot",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L4313-L4322 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/load_build_files.py | python | load_targets | (target_ids, working_dir, blade_root_dir, blade) | return direct_targets, all_command_targets, related_targets | load_targets.
Parse and load targets, including those specified in command line
and their direct and indirect dependencies, by loading related BUILD
files. Returns a map which contains all these targets. | load_targets. | [
"load_targets",
"."
] | def load_targets(target_ids, working_dir, blade_root_dir, blade):
"""load_targets.
Parse and load targets, including those specified in command line
and their direct and indirect dependencies, by loading related BUILD
files. Returns a map which contains all these targets.
"""
target_database = blade.get_target_database()
# targets specified in command line
cited_targets = set()
# cited_targets and all its dependencies
related_targets = {}
# source dirs mentioned in command line
source_dirs = []
# to prevent duplicated loading of BUILD files
processed_source_dirs = set()
direct_targets = []
all_command_targets = []
# Parse command line target_ids. For those in the form of <path>:<target>,
# record (<path>,<target>) in cited_targets; for the rest (with <path>
# but without <target>), record <path> into paths.
for target_id in target_ids:
if target_id.find(':') == -1:
source_dir, target_name = target_id, '*'
else:
source_dir, target_name = target_id.rsplit(':', 1)
source_dir = relative_path(os.path.join(working_dir, source_dir),
blade_root_dir)
if target_name != '*' and target_name != '':
cited_targets.add((source_dir, target_name))
elif source_dir.endswith('...'):
source_dir = source_dir[:-3]
if not source_dir:
source_dir = './'
source_dirs.append((source_dir, WARN_IF_FAIL))
for root, dirs, files in os.walk(source_dir):
# Skip over subdirs starting with '.', e.g., .svn.
# Note the dirs[:] = slice assignment; we are replacing the
# elements in dirs (and not the list referred to by dirs) so
# that os.walk() will not process deleted directories.
dirs[:] = [d for d in dirs if not d.startswith('.')]
for d in dirs:
source_dirs.append((os.path.join(root, d), IGNORE_IF_FAIL))
else:
source_dirs.append((source_dir, ABORT_IF_FAIL))
direct_targets = list(cited_targets)
# Load BUILD files in paths, and add all loaded targets into
# cited_targets. Together with above step, we can ensure that all
# targets mentioned in the command line are now in cited_targets.
for source_dir, action_if_fail in source_dirs:
_load_build_file(source_dir,
action_if_fail,
processed_source_dirs,
blade)
for key in target_database:
cited_targets.add(key)
all_command_targets = list(cited_targets)
# Starting from targets specified in command line, breath-first
# propagate to load BUILD files containing directly and indirectly
# dependent targets. All these targets form related_targets,
# which is a subset of target_databased created by loading BUILD files.
while cited_targets:
source_dir, target_name = cited_targets.pop()
target_id = (source_dir, target_name)
if target_id in related_targets:
continue
_load_build_file(source_dir,
ABORT_IF_FAIL,
processed_source_dirs,
blade)
if target_id not in target_database:
console.error_exit('%s: target //%s:%s does not exists' % (
_find_depender(target_id, blade), source_dir, target_name))
related_targets[target_id] = target_database[target_id]
for key in related_targets[target_id].expanded_deps:
if key not in related_targets:
cited_targets.add(key)
# Iterating to get svn root dirs
for path, name in related_targets:
root_dir = path.split('/')[0].strip()
if root_dir not in blade.svn_root_dirs and '#' not in root_dir:
blade.svn_root_dirs.append(root_dir)
return direct_targets, all_command_targets, related_targets | [
"def",
"load_targets",
"(",
"target_ids",
",",
"working_dir",
",",
"blade_root_dir",
",",
"blade",
")",
":",
"target_database",
"=",
"blade",
".",
"get_target_database",
"(",
")",
"# targets specified in command line",
"cited_targets",
"=",
"set",
"(",
")",
"# cited... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/load_build_files.py#L158-L254 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStr_GetNrFExt | (*args) | return _snap.TStr_GetNrFExt(*args) | TStr_GetNrFExt(TStr FExt) -> TStr
Parameters:
FExt: TStr const & | TStr_GetNrFExt(TStr FExt) -> TStr | [
"TStr_GetNrFExt",
"(",
"TStr",
"FExt",
")",
"-",
">",
"TStr"
] | def TStr_GetNrFExt(*args):
"""
TStr_GetNrFExt(TStr FExt) -> TStr
Parameters:
FExt: TStr const &
"""
return _snap.TStr_GetNrFExt(*args) | [
"def",
"TStr_GetNrFExt",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStr_GetNrFExt",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L11157-L11165 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/generator/analyzer.py | python | TargetCalculator._supplied_target_names_no_all | (self) | return result | Returns the supplied test targets without 'all'. | Returns the supplied test targets without 'all'. | [
"Returns",
"the",
"supplied",
"test",
"targets",
"without",
"all",
"."
] | def _supplied_target_names_no_all(self):
"""Returns the supplied test targets without 'all'."""
result = self._supplied_target_names()
result.discard("all")
return result | [
"def",
"_supplied_target_names_no_all",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_supplied_target_names",
"(",
")",
"result",
".",
"discard",
"(",
"\"all\"",
")",
"return",
"result"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/analyzer.py#L662-L666 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/MSCommon/vs.py | python | get_default_arch | (env) | return arch | Return the default arch to use for MSVS
if no version was requested by the user through the MSVS_ARCH environment
variable, select x86
Return
------
arch: str | Return the default arch to use for MSVS | [
"Return",
"the",
"default",
"arch",
"to",
"use",
"for",
"MSVS"
] | def get_default_arch(env):
"""Return the default arch to use for MSVS
if no version was requested by the user through the MSVS_ARCH environment
variable, select x86
Return
------
arch: str
"""
arch = env.get('MSVS_ARCH', 'x86')
msvs = InstalledVSMap.get(env['MSVS_VERSION'])
if not msvs:
arch = 'x86'
elif arch not in msvs.get_supported_arch():
fmt = "Visual Studio version %s does not support architecture %s"
raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch))
return arch | [
"def",
"get_default_arch",
"(",
"env",
")",
":",
"arch",
"=",
"env",
".",
"get",
"(",
"'MSVS_ARCH'",
",",
"'x86'",
")",
"msvs",
"=",
"InstalledVSMap",
".",
"get",
"(",
"env",
"[",
"'MSVS_VERSION'",
"]",
")",
"if",
"not",
"msvs",
":",
"arch",
"=",
"'x... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/MSCommon/vs.py#L518-L538 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/thrift/transport/TTransport.py | python | TMemoryBuffer.__init__ | (self, value=None) | value -- a value to read from for stringio
If value is set, this will be a transport for reading,
otherwise, it is for writing | value -- a value to read from for stringio | [
"value",
"--",
"a",
"value",
"to",
"read",
"from",
"for",
"stringio"
] | def __init__(self, value=None):
"""value -- a value to read from for stringio
If value is set, this will be a transport for reading,
otherwise, it is for writing"""
if value is not None:
self._buffer = StringIO(value)
else:
self._buffer = StringIO() | [
"def",
"__init__",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"_buffer",
"=",
"StringIO",
"(",
"value",
")",
"else",
":",
"self",
".",
"_buffer",
"=",
"StringIO",
"(",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/thrift/transport/TTransport.py#L200-L208 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | AcceleratorTable.IsOk | (*args, **kwargs) | return _core_.AcceleratorTable_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _core_.AcceleratorTable_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"AcceleratorTable_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L9014-L9016 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftobjects/array.py | python | Array.onChanged | (self, obj, prop) | Execute when a property is changed. | Execute when a property is changed. | [
"Execute",
"when",
"a",
"property",
"is",
"changed",
"."
] | def onChanged(self, obj, prop):
"""Execute when a property is changed."""
super(Array, self).onChanged(obj, prop)
# print(prop, ": ", getattr(obj, prop))
self.show_and_hide(obj, prop) | [
"def",
"onChanged",
"(",
"self",
",",
"obj",
",",
"prop",
")",
":",
"super",
"(",
"Array",
",",
"self",
")",
".",
"onChanged",
"(",
"obj",
",",
"prop",
")",
"# print(prop, \": \", getattr(obj, prop))",
"self",
".",
"show_and_hide",
"(",
"obj",
",",
"prop",... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/array.py#L332-L336 | ||
blackberry/Boost | fc90c3fde129c62565c023f091eddc4a7ed9902b | tools/build/v2/tools/gcc.py | python | init_link_flags | (toolset, linker, condition) | Now, the vendor specific flags.
The parameter linker can be either gnu, darwin, osf, hpux or sun. | Now, the vendor specific flags.
The parameter linker can be either gnu, darwin, osf, hpux or sun. | [
"Now",
"the",
"vendor",
"specific",
"flags",
".",
"The",
"parameter",
"linker",
"can",
"be",
"either",
"gnu",
"darwin",
"osf",
"hpux",
"or",
"sun",
"."
] | def init_link_flags(toolset, linker, condition):
"""
Now, the vendor specific flags.
The parameter linker can be either gnu, darwin, osf, hpux or sun.
"""
toolset_link = toolset + '.link'
if linker == 'gnu':
# Strip the binary when no debugging is needed. We use --strip-all flag
# as opposed to -s since icc (intel's compiler) is generally
# option-compatible with and inherits from the gcc toolset, but does not
# support -s.
# FIXME: what does unchecked translate to?
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition), ['-Wl,--strip-all']) # : unchecked ;
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
flags(toolset_link, 'RPATH_LINK', condition, ['<xdll-path>']) # : unchecked ;
flags(toolset_link, 'START-GROUP', condition, ['-Wl,--start-group'])# : unchecked ;
flags(toolset_link, 'END-GROUP', condition, ['-Wl,--end-group']) # : unchecked ;
# gnu ld has the ability to change the search behaviour for libraries
# referenced by -l switch. These modifiers are -Bstatic and -Bdynamic
# and change search for -l switches that follow them. The following list
# shows the tried variants.
# The search stops at the first variant that has a match.
# *nix: -Bstatic -lxxx
# libxxx.a
#
# *nix: -Bdynamic -lxxx
# libxxx.so
# libxxx.a
#
# windows (mingw,cygwin) -Bstatic -lxxx
# libxxx.a
# xxx.lib
#
# windows (mingw,cygwin) -Bdynamic -lxxx
# libxxx.dll.a
# xxx.dll.a
# libxxx.a
# xxx.lib
# cygxxx.dll (*)
# libxxx.dll
# xxx.dll
# libxxx.a
#
# (*) This is for cygwin
# Please note that -Bstatic and -Bdynamic are not a guarantee that a
# static or dynamic lib indeed gets linked in. The switches only change
# search patterns!
# On *nix mixing shared libs with static runtime is not a good idea.
flags(toolset_link, 'FINDLIBS-ST-PFX',
map(lambda x: x + '/<runtime-link>shared', condition),
['-Wl,-Bstatic']) # : unchecked ;
flags(toolset_link, 'FINDLIBS-SA-PFX',
map(lambda x: x + '/<runtime-link>shared', condition),
['-Wl,-Bdynamic']) # : unchecked ;
# On windows allow mixing of static and dynamic libs with static
# runtime.
flags(toolset_link, 'FINDLIBS-ST-PFX',
map(lambda x: x + '/<runtime-link>static/<target-os>windows', condition),
['-Wl,-Bstatic']) # : unchecked ;
flags(toolset_link, 'FINDLIBS-SA-PFX',
map(lambda x: x + '/<runtime-link>static/<target-os>windows', condition),
['-Wl,-Bdynamic']) # : unchecked ;
flags(toolset_link, 'OPTIONS',
map(lambda x: x + '/<runtime-link>static/<target-os>windows', condition),
['-Wl,-Bstatic']) # : unchecked ;
elif linker == 'darwin':
# On Darwin, the -s option to ld does not work unless we pass -static,
# and passing -static unconditionally is a bad idea. So, don't pass -s.
# at all, darwin.jam will use separate 'strip' invocation.
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
flags(toolset_link, 'RPATH_LINK', condition, ['<xdll-path>']) # : unchecked ;
elif linker == 'osf':
# No --strip-all, just -s.
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition), ['-Wl,-s'])
# : unchecked ;
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
# This does not supports -R.
flags(toolset_link, 'RPATH_OPTION', condition, ['-rpath']) # : unchecked ;
# -rpath-link is not supported at all.
elif linker == 'sun':
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition), ['-Wl,-s'])
# : unchecked ;
flags(toolset_link, 'RPATH', condition, ['<dll-path>']) # : unchecked ;
# Solaris linker does not have a separate -rpath-link, but allows to use
# -L for the same purpose.
flags(toolset_link, 'LINKPATH', condition, ['<xdll-path>']) # : unchecked ;
# This permits shared libraries with non-PIC code on Solaris.
# VP, 2004/09/07: Now that we have -fPIC hardcode in link.dll, the
# following is not needed. Whether -fPIC should be hardcoded, is a
# separate question.
# AH, 2004/10/16: it is still necessary because some tests link against
# static libraries that were compiled without PIC.
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<link>shared', condition), ['-mimpure-text'])
# : unchecked ;
elif linker == 'hpux':
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<debug-symbols>off', condition),
['-Wl,-s']) # : unchecked ;
flags(toolset_link, 'OPTIONS', map(lambda x: x + '/<link>shared', condition),
['-fPIC']) # : unchecked ;
else:
# FIXME:
errors.user_error(
"$(toolset) initialization: invalid linker '$(linker)' " +
"The value '$(linker)' specified for <linker> is not recognized. " +
"Possible values are 'gnu', 'darwin', 'osf', 'hpux' or 'sun'") | [
"def",
"init_link_flags",
"(",
"toolset",
",",
"linker",
",",
"condition",
")",
":",
"toolset_link",
"=",
"toolset",
"+",
"'.link'",
"if",
"linker",
"==",
"'gnu'",
":",
"# Strip the binary when no debugging is needed. We use --strip-all flag",
"# as opposed to -s since icc ... | https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/tools/gcc.py#L463-L577 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/util.py | python | get_resources_dests | (resources_root, rules) | return destinations | Find destinations for resources files | Find destinations for resources files | [
"Find",
"destinations",
"for",
"resources",
"files"
] | def get_resources_dests(resources_root, rules):
"""Find destinations for resources files"""
def get_rel_path(root, path):
# normalizes and returns a lstripped-/-separated path
root = root.replace(os.path.sep, '/')
path = path.replace(os.path.sep, '/')
assert path.startswith(root)
return path[len(root):].lstrip('/')
destinations = {}
for base, suffix, dest in rules:
prefix = os.path.join(resources_root, base)
for abs_base in iglob(prefix):
abs_glob = os.path.join(abs_base, suffix)
for abs_path in iglob(abs_glob):
resource_file = get_rel_path(resources_root, abs_path)
if dest is None: # remove the entry if it was here
destinations.pop(resource_file, None)
else:
rel_path = get_rel_path(abs_base, abs_path)
rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
destinations[resource_file] = rel_dest + '/' + rel_path
return destinations | [
"def",
"get_resources_dests",
"(",
"resources_root",
",",
"rules",
")",
":",
"def",
"get_rel_path",
"(",
"root",
",",
"path",
")",
":",
"# normalizes and returns a lstripped-/-separated path",
"root",
"=",
"root",
".",
"replace",
"(",
"os",
".",
"path",
".",
"se... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/util.py#L266-L289 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/tools/rc.py | python | configure | (command = None, condition = None, options = None) | Configures a new resource compilation command specific to a condition,
usually a toolset selection condition. The possible options are:
* <rc-type>(rc|windres) - Indicates the type of options the command
accepts.
Even though the arguments are all optional, only when a command, condition,
and at minimum the rc-type option are given will the command be configured.
This is so that callers don't have to check auto-configuration values
before calling this. And still get the functionality of build failures when
the resource compiler can't be found. | Configures a new resource compilation command specific to a condition,
usually a toolset selection condition. The possible options are:
* <rc-type>(rc|windres) - Indicates the type of options the command
accepts.
Even though the arguments are all optional, only when a command, condition,
and at minimum the rc-type option are given will the command be configured.
This is so that callers don't have to check auto-configuration values
before calling this. And still get the functionality of build failures when
the resource compiler can't be found. | [
"Configures",
"a",
"new",
"resource",
"compilation",
"command",
"specific",
"to",
"a",
"condition",
"usually",
"a",
"toolset",
"selection",
"condition",
".",
"The",
"possible",
"options",
"are",
":",
"*",
"<rc",
"-",
"type",
">",
"(",
"rc|windres",
")",
"-",... | def configure (command = None, condition = None, options = None):
"""
Configures a new resource compilation command specific to a condition,
usually a toolset selection condition. The possible options are:
* <rc-type>(rc|windres) - Indicates the type of options the command
accepts.
Even though the arguments are all optional, only when a command, condition,
and at minimum the rc-type option are given will the command be configured.
This is so that callers don't have to check auto-configuration values
before calling this. And still get the functionality of build failures when
the resource compiler can't be found.
"""
rc_type = feature.get_values('<rc-type>', options)
if rc_type:
assert(len(rc_type) == 1)
rc_type = rc_type[0]
if command and condition and rc_type:
flags('rc.compile.resource', '.RC', condition, command)
flags('rc.compile.resource', '.RC_TYPE', condition, rc_type.lower())
flags('rc.compile.resource', 'DEFINES', [], ['<define>'])
flags('rc.compile.resource', 'INCLUDES', [], ['<include>'])
if debug():
print 'notice: using rc compiler ::', condition, '::', command | [
"def",
"configure",
"(",
"command",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"rc_type",
"=",
"feature",
".",
"get_values",
"(",
"'<rc-type>'",
",",
"options",
")",
"if",
"rc_type",
":",
"assert",
"(",
"len",
"(... | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/tools/rc.py#L43-L68 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | orttraining/orttraining/python/training/ortmodule/ortmodule.py | python | ORTModule._load_from_state_dict | (self, state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs) | Override original method to delegate execution to the original PyTorch user module | Override original method to delegate execution to the original PyTorch user module | [
"Override",
"original",
"method",
"to",
"delegate",
"execution",
"to",
"the",
"original",
"PyTorch",
"user",
"module"
] | def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
"""Override original method to delegate execution to the original PyTorch user module"""
self._torch_module._load_from_state_dict(state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs) | [
"def",
"_load_from_state_dict",
"(",
"self",
",",
"state_dict",
",",
"prefix",
",",
"local_metadata",
",",
"strict",
",",
"missing_keys",
",",
"unexpected_keys",
",",
"error_msgs",
")",
":",
"self",
".",
"_torch_module",
".",
"_load_from_state_dict",
"(",
"state_d... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/ortmodule/ortmodule.py#L253-L258 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/mesa/MesaLib/src/gallium/auxiliary/util/u_format_pack.py | python | generate_format_pack | (format, src_channel, src_native_type, src_suffix) | Generate the function to pack pixels to a particular format | Generate the function to pack pixels to a particular format | [
"Generate",
"the",
"function",
"to",
"pack",
"pixels",
"to",
"a",
"particular",
"format"
] | def generate_format_pack(format, src_channel, src_native_type, src_suffix):
'''Generate the function to pack pixels to a particular format'''
name = format.short_name()
print 'static INLINE void'
print 'util_format_%s_pack_%s(uint8_t *dst_row, unsigned dst_stride, const %s *src_row, unsigned src_stride, unsigned width, unsigned height)' % (name, src_suffix, src_native_type)
print '{'
if is_format_supported(format):
print ' unsigned x, y;'
print ' for(y = 0; y < height; y += %u) {' % (format.block_height,)
print ' const %s *src = src_row;' % (src_native_type)
print ' uint8_t *dst = dst_row;'
print ' for(x = 0; x < width; x += %u) {' % (format.block_width,)
generate_pack_kernel(format, src_channel, src_native_type)
print ' src += 4;'
print ' dst += %u;' % (format.block_size() / 8,)
print ' }'
print ' dst_row += dst_stride;'
print ' src_row += src_stride/sizeof(*src_row);'
print ' }'
print '}'
print | [
"def",
"generate_format_pack",
"(",
"format",
",",
"src_channel",
",",
"src_native_type",
",",
"src_suffix",
")",
":",
"name",
"=",
"format",
".",
"short_name",
"(",
")",
"print",
"'static INLINE void'",
"print",
"'util_format_%s_pack_%s(uint8_t *dst_row, unsigned dst_str... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/mesa/MesaLib/src/gallium/auxiliary/util/u_format_pack.py#L589-L615 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.SetWhitespaceForeground | (*args, **kwargs) | return _stc.StyledTextCtrl_SetWhitespaceForeground(*args, **kwargs) | SetWhitespaceForeground(self, bool useSetting, Colour fore)
Set the foreground colour of all whitespace and whether to use this setting. | SetWhitespaceForeground(self, bool useSetting, Colour fore) | [
"SetWhitespaceForeground",
"(",
"self",
"bool",
"useSetting",
"Colour",
"fore",
")"
] | def SetWhitespaceForeground(*args, **kwargs):
"""
SetWhitespaceForeground(self, bool useSetting, Colour fore)
Set the foreground colour of all whitespace and whether to use this setting.
"""
return _stc.StyledTextCtrl_SetWhitespaceForeground(*args, **kwargs) | [
"def",
"SetWhitespaceForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetWhitespaceForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2913-L2919 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/metrics/loss.py | python | Loss.update | (self, *inputs) | Updates the internal evaluation result.
Args:
inputs: Inputs contain only one element, the element is loss. The dimension of
loss must be 0 or 1.
Raises:
ValueError: If the length of inputs is not 1.
ValueError: If the dimension of loss is not 1 or 0. | Updates the internal evaluation result. | [
"Updates",
"the",
"internal",
"evaluation",
"result",
"."
] | def update(self, *inputs):
"""
Updates the internal evaluation result.
Args:
inputs: Inputs contain only one element, the element is loss. The dimension of
loss must be 0 or 1.
Raises:
ValueError: If the length of inputs is not 1.
ValueError: If the dimension of loss is not 1 or 0.
"""
if len(inputs) != 1:
raise ValueError("For 'Loss.update', it needs 1 input (loss), but got {}".format(len(inputs)))
loss = self._convert_data(inputs[0])
if loss.ndim == 0:
loss = loss.reshape(1)
if loss.ndim != 1:
raise ValueError("For 'Loss.update', the dimension of your input (loss) must be 1, "
"but got {}.".format(loss.ndim))
loss = loss.mean(-1)
self._sum_loss += loss
self._total_num += 1 | [
"def",
"update",
"(",
"self",
",",
"*",
"inputs",
")",
":",
"if",
"len",
"(",
"inputs",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"For 'Loss.update', it needs 1 input (loss), but got {}\"",
".",
"format",
"(",
"len",
"(",
"inputs",
")",
")",
")",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/metrics/loss.py#L50-L76 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/ops.py | python | _EagerTensorBase._copy | (self, ctx=None, device_name=None) | return new_tensor | Copies tensor to dest device. | Copies tensor to dest device. | [
"Copies",
"tensor",
"to",
"dest",
"device",
"."
] | def _copy(self, ctx=None, device_name=None):
"""Copies tensor to dest device."""
# pylint: disable=protected-access
# Creates a new tensor on the dest device.
if ctx is None:
ctx = context.context()
if device_name is None:
device_name = ctx.device_name
# pylint: disable=protected-access
try:
new_tensor = self._copy_to_device(context=ctx._handle, device=device_name)
except core._NotOkStatusException as e:
six.raise_from(core._status_to_exception(e.code, e.message), None)
if core.active_trace() is not None:
core.active_trace().record_tensor("COPY",
tensor_id(new_tensor),
new_tensor.device,
new_tensor.shape.num_elements())
# Record the copy on tape and define backprop copy as well.
if not context.in_graph_mode():
self_device = self.device
def grad_fun(dresult):
return [dresult._copy(device_name=self_device)]
tape.record_operation("_copy", [new_tensor], [self], grad_fun)
return new_tensor | [
"def",
"_copy",
"(",
"self",
",",
"ctx",
"=",
"None",
",",
"device_name",
"=",
"None",
")",
":",
"# pylint: disable=protected-access",
"# Creates a new tensor on the dest device.",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"context",
".",
"context",
"(",
")",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L675-L700 | |
alibaba/MNN | c4d9566171d589c3ded23aa18ffb197016995a12 | pymnn/pip_package/MNN/expr/__init__.py | python | subtract | (x, y) | return _F.subtract(x, y) | subtract(x, y)
Return the ``x - y``, element-wise.
Parameters
----------
x : var_like, input value.
y : var_like, input value.
Returns
-------
z : Var. The ``x - y`` of `x` and `y`.
Example:
-------
>>> expr.subtract([9., 0.5], [1.2, -3.0])
var([7.8, 3.5]) | subtract(x, y)
Return the ``x - y``, element-wise. | [
"subtract",
"(",
"x",
"y",
")",
"Return",
"the",
"x",
"-",
"y",
"element",
"-",
"wise",
"."
] | def subtract(x, y):
'''
subtract(x, y)
Return the ``x - y``, element-wise.
Parameters
----------
x : var_like, input value.
y : var_like, input value.
Returns
-------
z : Var. The ``x - y`` of `x` and `y`.
Example:
-------
>>> expr.subtract([9., 0.5], [1.2, -3.0])
var([7.8, 3.5])
'''
x = _to_var(x)
y = _to_var(y)
x, y = _match_dtype(x, y)
return _F.subtract(x, y) | [
"def",
"subtract",
"(",
"x",
",",
"y",
")",
":",
"x",
"=",
"_to_var",
"(",
"x",
")",
"y",
"=",
"_to_var",
"(",
"y",
")",
"x",
",",
"y",
"=",
"_match_dtype",
"(",
"x",
",",
"y",
")",
"return",
"_F",
".",
"subtract",
"(",
"x",
",",
"y",
")"
] | https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L729-L751 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/html5lib/inputstream.py | python | EncodingParser.getAttribute | (self) | Return a name,value pair for the next attribute in the stream,
if one is found, or None | Return a name,value pair for the next attribute in the stream,
if one is found, or None | [
"Return",
"a",
"name",
"value",
"pair",
"for",
"the",
"next",
"attribute",
"in",
"the",
"stream",
"if",
"one",
"is",
"found",
"or",
"None"
] | def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c) | [
"def",
"getAttribute",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"# Step 1 (skip chars)",
"c",
"=",
"data",
".",
"skip",
"(",
"spaceCharactersBytes",
"|",
"frozenset",
"(",
"[",
"b\"/\"",
"]",
")",
")",
"assert",
"c",
"is",
"None",
"or",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/html5lib/inputstream.py#L775-L849 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/_multivariate.py | python | random_correlation_gen.rvs | (self, eigs, random_state=None, tol=1e-13, diag_tol=1e-7) | return m | Draw random correlation matrices
Parameters
----------
eigs : 1d ndarray
Eigenvalues of correlation matrix
tol : float, optional
Tolerance for input parameter checks
diag_tol : float, optional
Tolerance for deviation of the diagonal of the resulting
matrix. Default: 1e-7
Raises
------
RuntimeError
Floating point error prevented generating a valid correlation
matrix.
Returns
-------
rvs : ndarray or scalar
Random size N-dimensional matrices, dimension (size, dim, dim),
each having eigenvalues eigs. | Draw random correlation matrices | [
"Draw",
"random",
"correlation",
"matrices"
] | def rvs(self, eigs, random_state=None, tol=1e-13, diag_tol=1e-7):
"""
Draw random correlation matrices
Parameters
----------
eigs : 1d ndarray
Eigenvalues of correlation matrix
tol : float, optional
Tolerance for input parameter checks
diag_tol : float, optional
Tolerance for deviation of the diagonal of the resulting
matrix. Default: 1e-7
Raises
------
RuntimeError
Floating point error prevented generating a valid correlation
matrix.
Returns
-------
rvs : ndarray or scalar
Random size N-dimensional matrices, dimension (size, dim, dim),
each having eigenvalues eigs.
"""
dim, eigs = self._process_parameters(eigs, tol=tol)
random_state = self._get_random_state(random_state)
m = ortho_group.rvs(dim, random_state=random_state)
m = np.dot(np.dot(m, np.diag(eigs)), m.T) # Set the trace of m
m = self._to_corr(m) # Carefully rotate to unit diagonal
# Check diagonal
if abs(m.diagonal() - 1).max() > diag_tol:
raise RuntimeError("Failed to generate a valid correlation matrix")
return m | [
"def",
"rvs",
"(",
"self",
",",
"eigs",
",",
"random_state",
"=",
"None",
",",
"tol",
"=",
"1e-13",
",",
"diag_tol",
"=",
"1e-7",
")",
":",
"dim",
",",
"eigs",
"=",
"self",
".",
"_process_parameters",
"(",
"eigs",
",",
"tol",
"=",
"tol",
")",
"rand... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L3057-L3096 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/dumbmake/dumbmake.py | python | add_extra_dependencies | (target_pairs, dependency_map) | Take a list [(make_dir, make_target)] and expand (make_dir, None)
entries with extra make dependencies from |dependency_map|.
Returns an iterator of pairs (make_dir, make_target). | Take a list [(make_dir, make_target)] and expand (make_dir, None)
entries with extra make dependencies from |dependency_map|. | [
"Take",
"a",
"list",
"[",
"(",
"make_dir",
"make_target",
")",
"]",
"and",
"expand",
"(",
"make_dir",
"None",
")",
"entries",
"with",
"extra",
"make",
"dependencies",
"from",
"|dependency_map|",
"."
] | def add_extra_dependencies(target_pairs, dependency_map):
"""Take a list [(make_dir, make_target)] and expand (make_dir, None)
entries with extra make dependencies from |dependency_map|.
Returns an iterator of pairs (make_dir, make_target).
"""
all_targets = OrderedDict() # Used as an ordered set.
make_dirs = OrderedDict() # Used as an ordered set.
for make_target, group in groupby(target_pairs, itemgetter(1)):
# Return non-simple directory targets untouched.
if make_target is not None:
for pair in group:
# Generate dependencies for all components of a path.
# Given path a/b/c, examine a, a/b, and a/b/c in that order.
paths = get_components(pair[1])
# For each component of a path, find and add all dependencies
# to the final target list.
for target in paths:
if target not in all_targets:
yield pair[0], target
all_targets[target] = True
continue
# Add extra dumbmake dependencies to simple directory targets.
for make_dir, _ in group:
if make_dir not in make_dirs:
yield make_dir, None
make_dirs[make_dir] = True
all_components = []
for make_dir in make_dirs.iterkeys():
all_components.extend(get_components(make_dir))
for i in all_dependencies(*all_components, dependency_map=dependency_map):
if i not in make_dirs:
yield i, None | [
"def",
"add_extra_dependencies",
"(",
"target_pairs",
",",
"dependency_map",
")",
":",
"all_targets",
"=",
"OrderedDict",
"(",
")",
"# Used as an ordered set.",
"make_dirs",
"=",
"OrderedDict",
"(",
")",
"# Used as an ordered set.",
"for",
"make_target",
",",
"group",
... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/dumbmake/dumbmake.py#L85-L122 | ||
TheLegendAli/DeepLab-Context | fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c | scripts/cpp_lint.py | python | IsErrorSuppressedByNolint | (category, linenum) | return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment. | Returns true if the specified error category is suppressed on this line. | [
"Returns",
"true",
"if",
"the",
"specified",
"error",
"category",
"is",
"suppressed",
"on",
"this",
"line",
"."
] | def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.
"""
return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | [
"def",
"IsErrorSuppressedByNolint",
"(",
"category",
",",
"linenum",
")",
":",
"return",
"(",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"category",
",",
"set",
"(",
")",
")",
"or",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"None... | https://github.com/TheLegendAli/DeepLab-Context/blob/fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c/scripts/cpp_lint.py#L500-L513 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/lib/recfunctions.py | python | flatten_descr | (ndtype) | Flatten a structured data-type description.
Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> ndtype = np.dtype([('a', '<i4'), ('b', [('ba', '<f8'), ('bb', '<i4')])])
>>> rfn.flatten_descr(ndtype)
(('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) | Flatten a structured data-type description. | [
"Flatten",
"a",
"structured",
"data",
"-",
"type",
"description",
"."
] | def flatten_descr(ndtype):
"""
Flatten a structured data-type description.
Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> ndtype = np.dtype([('a', '<i4'), ('b', [('ba', '<f8'), ('bb', '<i4')])])
>>> rfn.flatten_descr(ndtype)
(('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32')))
"""
names = ndtype.names
if names is None:
return ndtype.descr
else:
descr = []
for field in names:
(typ, _) = ndtype.fields[field]
if typ.names:
descr.extend(flatten_descr(typ))
else:
descr.append((field, typ))
return tuple(descr) | [
"def",
"flatten_descr",
"(",
"ndtype",
")",
":",
"names",
"=",
"ndtype",
".",
"names",
"if",
"names",
"is",
"None",
":",
"return",
"ndtype",
".",
"descr",
"else",
":",
"descr",
"=",
"[",
"]",
"for",
"field",
"in",
"names",
":",
"(",
"typ",
",",
"_"... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/recfunctions.py#L135-L158 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/youtube/service.py | python | YouTubeService.YouTubeQuery | (self, query) | Performs a YouTube specific query and returns a resulting feed or entry.
Args:
query: A Query object or one if its sub-classes (YouTubeVideoQuery,
YouTubeUserQuery or YouTubePlaylistQuery).
Returns:
Depending on the type of Query object submitted returns either a
YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the
Query object provided was not YouTube-related, a tuple is returned.
On success the tuple will be in this form:
(boolean succeeded=True, ElementTree._Element result)
On failure, the tuple will be in this form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server response}) | Performs a YouTube specific query and returns a resulting feed or entry. | [
"Performs",
"a",
"YouTube",
"specific",
"query",
"and",
"returns",
"a",
"resulting",
"feed",
"or",
"entry",
"."
] | def YouTubeQuery(self, query):
"""Performs a YouTube specific query and returns a resulting feed or entry.
Args:
query: A Query object or one if its sub-classes (YouTubeVideoQuery,
YouTubeUserQuery or YouTubePlaylistQuery).
Returns:
Depending on the type of Query object submitted returns either a
YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the
Query object provided was not YouTube-related, a tuple is returned.
On success the tuple will be in this form:
(boolean succeeded=True, ElementTree._Element result)
On failure, the tuple will be in this form:
(boolean succeeded=False, {'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server response})
"""
result = self.Query(query.ToUri())
if isinstance(query, YouTubeVideoQuery):
return gdata.youtube.YouTubeVideoFeedFromString(result.ToString())
elif isinstance(query, YouTubeUserQuery):
return gdata.youtube.YouTubeUserFeedFromString(result.ToString())
elif isinstance(query, YouTubePlaylistQuery):
return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString())
else:
return result | [
"def",
"YouTubeQuery",
"(",
"self",
",",
"query",
")",
":",
"result",
"=",
"self",
".",
"Query",
"(",
"query",
".",
"ToUri",
"(",
")",
")",
"if",
"isinstance",
"(",
"query",
",",
"YouTubeVideoQuery",
")",
":",
"return",
"gdata",
".",
"youtube",
".",
... | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/youtube/service.py#L1323-L1349 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Event.GetEventCategory | (*args, **kwargs) | return _core_.Event_GetEventCategory(*args, **kwargs) | GetEventCategory(self) -> int | GetEventCategory(self) -> int | [
"GetEventCategory",
"(",
"self",
")",
"-",
">",
"int"
] | def GetEventCategory(*args, **kwargs):
"""GetEventCategory(self) -> int"""
return _core_.Event_GetEventCategory(*args, **kwargs) | [
"def",
"GetEventCategory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Event_GetEventCategory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5034-L5036 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/plat-mac/pimp.py | python | PimpPackage.downloadPackageOnly | (self, output=None) | Download a single package, if needed.
An MD5 signature is used to determine whether download is needed,
and to test that we actually downloaded what we expected.
If output is given it is a file-like object that will receive a log
of what happens.
If anything unforeseen happened the method returns an error message
string. | Download a single package, if needed. | [
"Download",
"a",
"single",
"package",
"if",
"needed",
"."
] | def downloadPackageOnly(self, output=None):
"""Download a single package, if needed.
An MD5 signature is used to determine whether download is needed,
and to test that we actually downloaded what we expected.
If output is given it is a file-like object that will receive a log
of what happens.
If anything unforeseen happened the method returns an error message
string.
"""
scheme, loc, path, query, frag = urlparse.urlsplit(self._dict['Download-URL'])
path = urllib.url2pathname(path)
filename = os.path.split(path)[1]
self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename)
if not self._archiveOK():
if scheme == 'manual':
return "Please download package manually and save as %s" % self.archiveFilename
downloader = PimpUrllibDownloader(None, self._db.preferences.downloadDir,
watcher=self._db.preferences.watcher)
if not downloader.download(self._dict['Download-URL'],
self.archiveFilename, output):
return "download command failed"
if not os.path.exists(self.archiveFilename) and not NO_EXECUTE:
return "archive not found after download"
if not self._archiveOK():
return "archive does not have correct MD5 checksum" | [
"def",
"downloadPackageOnly",
"(",
"self",
",",
"output",
"=",
"None",
")",
":",
"scheme",
",",
"loc",
",",
"path",
",",
"query",
",",
"frag",
"=",
"urlparse",
".",
"urlsplit",
"(",
"self",
".",
"_dict",
"[",
"'Download-URL'",
"]",
")",
"path",
"=",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/pimp.py#L663-L690 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/resources.py | python | read_text | (package: Package,
resource: Resource,
encoding: str = 'utf-8',
errors: str = 'strict') | Return the decoded string of the resource.
The decoding-related arguments have the same semantics as those of
bytes.decode(). | Return the decoded string of the resource. | [
"Return",
"the",
"decoded",
"string",
"of",
"the",
"resource",
"."
] | def read_text(package: Package,
resource: Resource,
encoding: str = 'utf-8',
errors: str = 'strict') -> str:
"""Return the decoded string of the resource.
The decoding-related arguments have the same semantics as those of
bytes.decode().
"""
resource = _normalize_path(resource)
package = _get_package(package)
with open_text(package, resource, encoding, errors) as fp:
return fp.read() | [
"def",
"read_text",
"(",
"package",
":",
"Package",
",",
"resource",
":",
"Resource",
",",
"encoding",
":",
"str",
"=",
"'utf-8'",
",",
"errors",
":",
"str",
"=",
"'strict'",
")",
"->",
"str",
":",
"resource",
"=",
"_normalize_path",
"(",
"resource",
")"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/resources.py#L158-L170 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | Grid.GridLinesEnabled | (*args, **kwargs) | return _grid.Grid_GridLinesEnabled(*args, **kwargs) | GridLinesEnabled(self) -> bool | GridLinesEnabled(self) -> bool | [
"GridLinesEnabled",
"(",
"self",
")",
"-",
">",
"bool"
] | def GridLinesEnabled(*args, **kwargs):
"""GridLinesEnabled(self) -> bool"""
return _grid.Grid_GridLinesEnabled(*args, **kwargs) | [
"def",
"GridLinesEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GridLinesEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1670-L1672 | |
freesurfer/freesurfer | 6dbe527d43ffa611acb2cd112e9469f9bfec8e36 | python/freesurfer/transform.py | python | Geometry.vox2ras | (self) | return LinearTransform(self.affine) | LinearTransform that maps voxel crs coordinates to ras xyz coordinates. | LinearTransform that maps voxel crs coordinates to ras xyz coordinates. | [
"LinearTransform",
"that",
"maps",
"voxel",
"crs",
"coordinates",
"to",
"ras",
"xyz",
"coordinates",
"."
] | def vox2ras(self):
'''LinearTransform that maps voxel crs coordinates to ras xyz coordinates.'''
return LinearTransform(self.affine) | [
"def",
"vox2ras",
"(",
"self",
")",
":",
"return",
"LinearTransform",
"(",
"self",
".",
"affine",
")"
] | https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/transform.py#L146-L148 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/MilitaryAI.py | python | get_concentrated_tot_mil_rating | () | return round(
combine_ratings(
get_fleet_rating(fleet_id) for fleet_id in FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY)
),
0,
) | Give an assessment of total military rating as if all fleets were merged into a single mega-fleet.
:return: a military rating value | Give an assessment of total military rating as if all fleets were merged into a single mega-fleet. | [
"Give",
"an",
"assessment",
"of",
"total",
"military",
"rating",
"as",
"if",
"all",
"fleets",
"were",
"merged",
"into",
"a",
"single",
"mega",
"-",
"fleet",
"."
] | def get_concentrated_tot_mil_rating() -> float:
"""
Give an assessment of total military rating as if all fleets were merged into a single mega-fleet.
:return: a military rating value
"""
return round(
combine_ratings(
get_fleet_rating(fleet_id) for fleet_id in FleetUtilsAI.get_empire_fleet_ids_by_role(MissionType.MILITARY)
),
0,
) | [
"def",
"get_concentrated_tot_mil_rating",
"(",
")",
"->",
"float",
":",
"return",
"round",
"(",
"combine_ratings",
"(",
"get_fleet_rating",
"(",
"fleet_id",
")",
"for",
"fleet_id",
"in",
"FleetUtilsAI",
".",
"get_empire_fleet_ids_by_role",
"(",
"MissionType",
".",
"... | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/MilitaryAI.py#L1068-L1079 | |
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/bridge_common.py | python | print_bridge_table_row | (alignments, col_widths, output, completed_count, num_bridges,
min_bridge_qual, verbosity, bridge_type) | Used for LongReadBridge and MiniasmBridge objects. | Used for LongReadBridge and MiniasmBridge objects. | [
"Used",
"for",
"LongReadBridge",
"and",
"MiniasmBridge",
"objects",
"."
] | def print_bridge_table_row(alignments, col_widths, output, completed_count, num_bridges,
min_bridge_qual, verbosity, bridge_type):
"""
Used for LongReadBridge and MiniasmBridge objects.
"""
assert bridge_type == 'LongReadBridge' or bridge_type == 'MiniasmBridge'
fraction = str(completed_count) + '/' + str(num_bridges)
start, end, read_count, consensus_length, consensus_time, target_length, path_count, \
search_type, search_time, best_path, best_path_len, best_path_raw_score, \
best_path_scaled_score, best_path_length_discrepancy, quality = output
start_to_end = (start + ' ' + get_right_arrow()).rjust(7) + ' ' + end
quality_str = float_to_str(quality, 3)
table_row = [fraction, start_to_end]
if verbosity > 1 and bridge_type == 'LongReadBridge':
table_row.append(read_count)
if verbosity > 1:
table_row.append(consensus_length)
if verbosity > 2 and bridge_type == 'LongReadBridge':
table_row += [consensus_time, target_length]
if verbosity > 1:
table_row += [search_type, search_time, path_count]
table_row += [best_path]
if verbosity > 2:
table_row += [best_path_len, best_path_raw_score, best_path_scaled_score,
best_path_length_discrepancy]
table_row += [quality_str]
sub_colour = {}
if quality < min_bridge_qual:
sub_colour[quality_str] = 'red'
print_table([table_row], col_separation=2, header_format='normal', indent=0,
left_align_header=False, alignments=alignments, fixed_col_widths=col_widths,
sub_colour=sub_colour, bottom_align_header=False) | [
"def",
"print_bridge_table_row",
"(",
"alignments",
",",
"col_widths",
",",
"output",
",",
"completed_count",
",",
"num_bridges",
",",
"min_bridge_qual",
",",
"verbosity",
",",
"bridge_type",
")",
":",
"assert",
"bridge_type",
"==",
"'LongReadBridge'",
"or",
"bridge... | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/bridge_common.py#L144-L183 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | _LoopCondShape | (op) | return [op.inputs[0].get_shape().merge_with(tensor_shape.scalar())] | Shape function for the LoopCond op. | Shape function for the LoopCond op. | [
"Shape",
"function",
"for",
"the",
"LoopCond",
"op",
"."
] | def _LoopCondShape(op):
"""Shape function for the LoopCond op."""
return [op.inputs[0].get_shape().merge_with(tensor_shape.scalar())] | [
"def",
"_LoopCondShape",
"(",
"op",
")",
":",
"return",
"[",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L2389-L2391 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/saving/saved_model/load_context.py | python | in_load_context | () | return _load_context.in_load_context | Returns whether under a load context. | Returns whether under a load context. | [
"Returns",
"whether",
"under",
"a",
"load",
"context",
"."
] | def in_load_context():
"""Returns whether under a load context."""
return _load_context.in_load_context | [
"def",
"in_load_context",
"(",
")",
":",
"return",
"_load_context",
".",
"in_load_context"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/saving/saved_model/load_context.py#L61-L63 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py | python | MercurialVCS._GetRelPath | (self, filename) | return os.path.relpath(absname) | Get relative path of a file according to the current directory,
given its logical path in the repo. | Get relative path of a file according to the current directory,
given its logical path in the repo. | [
"Get",
"relative",
"path",
"of",
"a",
"file",
"according",
"to",
"the",
"current",
"directory",
"given",
"its",
"logical",
"path",
"in",
"the",
"repo",
"."
] | def _GetRelPath(self, filename):
"""Get relative path of a file according to the current directory,
given its logical path in the repo."""
absname = os.path.join(self.repo_dir, filename)
return os.path.relpath(absname) | [
"def",
"_GetRelPath",
"(",
"self",
",",
"filename",
")",
":",
"absname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"repo_dir",
",",
"filename",
")",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"absname",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L1495-L1499 | |
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | build-support/iwyu/fix_includes.py | python | _RemoveNamespacePrefix | (fwd_decl_iwyu_line, namespace_prefix) | return fwd_decl_iwyu_line | Return a version of the input line with namespace_prefix removed, or None.
If fwd_decl_iwyu_line is
namespace ns1 { namespace ns2 { namespace ns3 { foo } } }
and namespace_prefix = 'namespace ns1 { namespace ns2 {', then
this function returns 'namespace ns3 { foo }'. It removes the
namespace_prefix, and any } }'s at the end of the line. If line
does not fit this form, then this function returns None.
Arguments:
line: a line from iwyu about a forward-declare line to add
namespace_prefix: a non-empty string of the form
namespace <ns1> { namespace <ns2> { [...]
Returns:
A version of the input line with the namespaces in namespace
prefix removed, or None if this is not possible because the input
line is not of the right form. | Return a version of the input line with namespace_prefix removed, or None. | [
"Return",
"a",
"version",
"of",
"the",
"input",
"line",
"with",
"namespace_prefix",
"removed",
"or",
"None",
"."
] | def _RemoveNamespacePrefix(fwd_decl_iwyu_line, namespace_prefix):
"""Return a version of the input line with namespace_prefix removed, or None.
If fwd_decl_iwyu_line is
namespace ns1 { namespace ns2 { namespace ns3 { foo } } }
and namespace_prefix = 'namespace ns1 { namespace ns2 {', then
this function returns 'namespace ns3 { foo }'. It removes the
namespace_prefix, and any } }'s at the end of the line. If line
does not fit this form, then this function returns None.
Arguments:
line: a line from iwyu about a forward-declare line to add
namespace_prefix: a non-empty string of the form
namespace <ns1> { namespace <ns2> { [...]
Returns:
A version of the input line with the namespaces in namespace
prefix removed, or None if this is not possible because the input
line is not of the right form.
"""
assert namespace_prefix, "_RemoveNamespaces requires a non-empty prefix"
if not fwd_decl_iwyu_line.startswith(namespace_prefix):
return None
# Remove the prefix
fwd_decl_iwyu_line = fwd_decl_iwyu_line[len(namespace_prefix):].lstrip()
# Remove the matching trailing }'s, preserving comments.
num_braces = namespace_prefix.count('{')
ending_braces_re = re.compile(r'(\s*\}){%d}\s*$' % num_braces)
m = ending_braces_re.search(fwd_decl_iwyu_line)
if not m:
return None
fwd_decl_iwyu_line = fwd_decl_iwyu_line[:m.start(0)]
return fwd_decl_iwyu_line | [
"def",
"_RemoveNamespacePrefix",
"(",
"fwd_decl_iwyu_line",
",",
"namespace_prefix",
")",
":",
"assert",
"namespace_prefix",
",",
"\"_RemoveNamespaces requires a non-empty prefix\"",
"if",
"not",
"fwd_decl_iwyu_line",
".",
"startswith",
"(",
"namespace_prefix",
")",
":",
"r... | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/iwyu/fix_includes.py#L1829-L1864 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/win/toolchain/toolchain.py | python | GetSourceImages2010 | (local_dir) | Download all distribution archives for the components we need. | Download all distribution archives for the components we need. | [
"Download",
"all",
"distribution",
"archives",
"for",
"the",
"components",
"we",
"need",
"."
] | def GetSourceImages2010(local_dir):
"""Download all distribution archives for the components we need."""
if local_dir:
return SourceImages2010(
sdk8_path=os.path.join(local_dir, 'Standalone'),
wdk_iso=os.path.join(local_dir, 'GRMWDK_EN_7600_1.ISO'),
sdk7_update=os.path.join(local_dir, 'VC-Compiler-KB2519277.exe'),
sdk7_path=os.path.join(local_dir, 'GRMSDKX_EN_DVD.ISO'),
dxsdk_path=os.path.join(local_dir, 'DXSDK_Jun10.exe'))
else:
# Note that we do the Win8 SDK first so that its silly UAC prompt
# happens before the user wanders off to get coffee.
sdk8_path = DownloadSDK8()
wdk_iso = DownloadWDKIso()
sdk7_update = DownloadSDKUpdate()
sdk7_path = DownloadSDK71Iso()
dxsdk_path = DownloadDirectXSDK()
return SourceImages2010(
sdk8_path, wdk_iso, sdk7_update, sdk7_path, dxsdk_path) | [
"def",
"GetSourceImages2010",
"(",
"local_dir",
")",
":",
"if",
"local_dir",
":",
"return",
"SourceImages2010",
"(",
"sdk8_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"local_dir",
",",
"'Standalone'",
")",
",",
"wdk_iso",
"=",
"os",
".",
"path",
".",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/win/toolchain/toolchain.py#L179-L197 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/internals/blocks.py | python | Block.where | (self, other, cond, errors="raise") | return result_blocks | evaluate the block; return result block(s) from the result
Parameters
----------
other : a ndarray/object
cond : np.ndarray[bool], SparseArray[bool], or BooleanArray
errors : str, {'raise', 'ignore'}, default 'raise'
- ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object
Returns
-------
List[Block] | evaluate the block; return result block(s) from the result | [
"evaluate",
"the",
"block",
";",
"return",
"result",
"block",
"(",
"s",
")",
"from",
"the",
"result"
] | def where(self, other, cond, errors="raise") -> list[Block]:
"""
evaluate the block; return result block(s) from the result
Parameters
----------
other : a ndarray/object
cond : np.ndarray[bool], SparseArray[bool], or BooleanArray
errors : str, {'raise', 'ignore'}, default 'raise'
- ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object
Returns
-------
List[Block]
"""
assert cond.ndim == self.ndim
assert not isinstance(other, (ABCIndex, ABCSeries, ABCDataFrame))
assert errors in ["raise", "ignore"]
transpose = self.ndim == 2
values = self.values
orig_other = other
if transpose:
values = values.T
icond, noop = validate_putmask(values, ~cond)
if is_valid_na_for_dtype(other, self.dtype) and self.dtype != _dtype_obj:
other = self.fill_value
if noop:
# TODO: avoid the downcasting at the end in this case?
# GH-39595: Always return a copy
result = values.copy()
else:
# see if we can operate on the entire block, or need item-by-item
# or if we are a single block (ndim == 1)
if not self._can_hold_element(other):
# we cannot coerce, return a compat dtype
# we are explicitly ignoring errors
block = self.coerce_to_target_dtype(other)
blocks = block.where(orig_other, cond, errors=errors)
return self._maybe_downcast(blocks, "infer")
# error: Argument 1 to "setitem_datetimelike_compat" has incompatible type
# "Union[ndarray, ExtensionArray]"; expected "ndarray"
# error: Argument 2 to "setitem_datetimelike_compat" has incompatible type
# "number[Any]"; expected "int"
alt = setitem_datetimelike_compat(
values, icond.sum(), other # type: ignore[arg-type]
)
if alt is not other:
result = values.copy()
np.putmask(result, icond, alt)
else:
# By the time we get here, we should have all Series/Index
# args extracted to ndarray
result = expressions.where(~icond, values, other)
if self._can_hold_na or self.ndim == 1:
if transpose:
result = result.T
return [self.make_block(result)]
# might need to separate out blocks
cond = ~icond
axis = cond.ndim - 1
cond = cond.swapaxes(axis, 0)
mask = cond.all(axis=1)
result_blocks: list[Block] = []
for m in [mask, ~mask]:
if m.any():
result = cast(np.ndarray, result) # EABlock overrides where
taken = result.take(m.nonzero()[0], axis=axis)
r = maybe_downcast_numeric(taken, self.dtype)
nb = self.make_block(r.T, placement=self._mgr_locs[m])
result_blocks.append(nb)
return result_blocks | [
"def",
"where",
"(",
"self",
",",
"other",
",",
"cond",
",",
"errors",
"=",
"\"raise\"",
")",
"->",
"list",
"[",
"Block",
"]",
":",
"assert",
"cond",
".",
"ndim",
"==",
"self",
".",
"ndim",
"assert",
"not",
"isinstance",
"(",
"other",
",",
"(",
"AB... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/blocks.py#L1183-L1266 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py | python | ZipExtFile.peek | (self, n=1) | return self._readbuffer[self._offset: self._offset + 512] | Returns buffered bytes without advancing the position. | Returns buffered bytes without advancing the position. | [
"Returns",
"buffered",
"bytes",
"without",
"advancing",
"the",
"position",
"."
] | def peek(self, n=1):
"""Returns buffered bytes without advancing the position."""
if n > len(self._readbuffer) - self._offset:
chunk = self.read(n)
self._offset -= len(chunk)
# Return up to 512 bytes to reduce allocation overhead for tight loops.
return self._readbuffer[self._offset: self._offset + 512] | [
"def",
"peek",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"if",
"n",
">",
"len",
"(",
"self",
".",
"_readbuffer",
")",
"-",
"self",
".",
"_offset",
":",
"chunk",
"=",
"self",
".",
"read",
"(",
"n",
")",
"self",
".",
"_offset",
"-=",
"len",
"(... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py#L605-L612 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/mstats_basic.py | python | kendalltau | (x, y, use_ties=True, use_missing=False) | return KendalltauResult(tau, prob) | Computes Kendall's rank correlation tau on two variables *x* and *y*.
Parameters
----------
x : sequence
First data list (for example, time).
y : sequence
Second data list.
use_ties : {True, False}, optional
Whether ties correction should be performed.
use_missing : {False, True}, optional
Whether missing data should be allocated a rank of 0 (False) or the
average rank (True)
Returns
-------
correlation : float
Kendall tau
pvalue : float
Approximate 2-side p-value. | Computes Kendall's rank correlation tau on two variables *x* and *y*. | [
"Computes",
"Kendall",
"s",
"rank",
"correlation",
"tau",
"on",
"two",
"variables",
"*",
"x",
"*",
"and",
"*",
"y",
"*",
"."
] | def kendalltau(x, y, use_ties=True, use_missing=False):
"""
Computes Kendall's rank correlation tau on two variables *x* and *y*.
Parameters
----------
x : sequence
First data list (for example, time).
y : sequence
Second data list.
use_ties : {True, False}, optional
Whether ties correction should be performed.
use_missing : {False, True}, optional
Whether missing data should be allocated a rank of 0 (False) or the
average rank (True)
Returns
-------
correlation : float
Kendall tau
pvalue : float
Approximate 2-side p-value.
"""
(x, y, n) = _chk_size(x, y)
(x, y) = (x.flatten(), y.flatten())
m = ma.mask_or(ma.getmask(x), ma.getmask(y))
if m is not nomask:
x = ma.array(x, mask=m, copy=True)
y = ma.array(y, mask=m, copy=True)
n -= m.sum()
if n < 2:
return KendalltauResult(np.nan, np.nan)
rx = ma.masked_equal(rankdata(x, use_missing=use_missing), 0)
ry = ma.masked_equal(rankdata(y, use_missing=use_missing), 0)
idx = rx.argsort()
(rx, ry) = (rx[idx], ry[idx])
C = np.sum([((ry[i+1:] > ry[i]) * (rx[i+1:] > rx[i])).filled(0).sum()
for i in range(len(ry)-1)], dtype=float)
D = np.sum([((ry[i+1:] < ry[i])*(rx[i+1:] > rx[i])).filled(0).sum()
for i in range(len(ry)-1)], dtype=float)
if use_ties:
xties = count_tied_groups(x)
yties = count_tied_groups(y)
corr_x = np.sum([v*k*(k-1) for (k,v) in iteritems(xties)], dtype=float)
corr_y = np.sum([v*k*(k-1) for (k,v) in iteritems(yties)], dtype=float)
denom = ma.sqrt((n*(n-1)-corr_x)/2. * (n*(n-1)-corr_y)/2.)
else:
denom = n*(n-1)/2.
tau = (C-D) / denom
var_s = n*(n-1)*(2*n+5)
if use_ties:
var_s -= np.sum(v*k*(k-1)*(2*k+5)*1. for (k,v) in iteritems(xties))
var_s -= np.sum(v*k*(k-1)*(2*k+5)*1. for (k,v) in iteritems(yties))
v1 = np.sum([v*k*(k-1) for (k, v) in iteritems(xties)], dtype=float) *\
np.sum([v*k*(k-1) for (k, v) in iteritems(yties)], dtype=float)
v1 /= 2.*n*(n-1)
if n > 2:
v2 = np.sum([v*k*(k-1)*(k-2) for (k,v) in iteritems(xties)],
dtype=float) * \
np.sum([v*k*(k-1)*(k-2) for (k,v) in iteritems(yties)],
dtype=float)
v2 /= 9.*n*(n-1)*(n-2)
else:
v2 = 0
else:
v1 = v2 = 0
var_s /= 18.
var_s += (v1 + v2)
z = (C-D)/np.sqrt(var_s)
prob = special.erfc(abs(z)/np.sqrt(2))
return KendalltauResult(tau, prob) | [
"def",
"kendalltau",
"(",
"x",
",",
"y",
",",
"use_ties",
"=",
"True",
",",
"use_missing",
"=",
"False",
")",
":",
"(",
"x",
",",
"y",
",",
"n",
")",
"=",
"_chk_size",
"(",
"x",
",",
"y",
")",
"(",
"x",
",",
"y",
")",
"=",
"(",
"x",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/mstats_basic.py#L497-L572 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/values.py | python | DistributedVariable._get_closest | (self) | return self._values[replica_id] | Return member in the same replica if possible, else the primary. | Return member in the same replica if possible, else the primary. | [
"Return",
"member",
"in",
"the",
"same",
"replica",
"if",
"possible",
"else",
"the",
"primary",
"."
] | def _get_closest(self):
"""Return member in the same replica if possible, else the primary."""
replica_context = distribution_strategy_context.get_replica_context()
if replica_context:
return self._device_map.select_for_current_replica(
self._values, replica_context)
device = distribute_lib.get_update_device()
if device is None:
device = device_util.canonicalize(device_util.current())
replica_id = self._device_map.replica_for_device(device)
if replica_id is None:
return self.primary
return self._values[replica_id] | [
"def",
"_get_closest",
"(",
"self",
")",
":",
"replica_context",
"=",
"distribution_strategy_context",
".",
"get_replica_context",
"(",
")",
"if",
"replica_context",
":",
"return",
"self",
".",
"_device_map",
".",
"select_for_current_replica",
"(",
"self",
".",
"_va... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/values.py#L656-L668 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mimetypes.py | python | guess_extension | (type, strict=True) | return _db.guess_extension(type, strict) | Guess the extension for a file based on its MIME type.
Return value is a string giving a filename extension, including the
leading dot ('.'). The extension is not guaranteed to have been
associated with any particular data stream, but would be mapped to the
MIME type `type' by guess_type(). If no extension can be guessed for
`type', None is returned.
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types. | Guess the extension for a file based on its MIME type. | [
"Guess",
"the",
"extension",
"for",
"a",
"file",
"based",
"on",
"its",
"MIME",
"type",
"."
] | def guess_extension(type, strict=True):
"""Guess the extension for a file based on its MIME type.
Return value is a string giving a filename extension, including the
leading dot ('.'). The extension is not guaranteed to have been
associated with any particular data stream, but would be mapped to the
MIME type `type' by guess_type(). If no extension can be guessed for
`type', None is returned.
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
if _db is None:
init()
return _db.guess_extension(type, strict) | [
"def",
"guess_extension",
"(",
"type",
",",
"strict",
"=",
"True",
")",
":",
"if",
"_db",
"is",
"None",
":",
"init",
"(",
")",
"return",
"_db",
".",
"guess_extension",
"(",
"type",
",",
"strict",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mimetypes.py#L314-L328 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/build/property_set.py | python | PropertySet.dependency | (self) | return self.dependency_ | Returns dependency properties. | Returns dependency properties. | [
"Returns",
"dependency",
"properties",
"."
] | def dependency (self):
""" Returns dependency properties.
"""
return self.dependency_ | [
"def",
"dependency",
"(",
"self",
")",
":",
"return",
"self",
".",
"dependency_"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/property_set.py#L256-L259 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/turtle.py | python | RawTurtle.end_poly | (self) | Stop recording the vertices of a polygon.
No argument.
Stop recording the vertices of a polygon. Current turtle position is
last point of polygon. This will be connected with the first point.
Example (for a Turtle instance named turtle):
>>> turtle.end_poly() | Stop recording the vertices of a polygon. | [
"Stop",
"recording",
"the",
"vertices",
"of",
"a",
"polygon",
"."
] | def end_poly(self):
"""Stop recording the vertices of a polygon.
No argument.
Stop recording the vertices of a polygon. Current turtle position is
last point of polygon. This will be connected with the first point.
Example (for a Turtle instance named turtle):
>>> turtle.end_poly()
"""
self._creatingPoly = False | [
"def",
"end_poly",
"(",
"self",
")",
":",
"self",
".",
"_creatingPoly",
"=",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/turtle.py#L3452-L3463 | ||
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Util.py | python | Proxy.__init__ | (self, subject) | Wrap an object as a Proxy object | Wrap an object as a Proxy object | [
"Wrap",
"an",
"object",
"as",
"a",
"Proxy",
"object"
] | def __init__(self, subject):
"""Wrap an object as a Proxy object"""
self._subject = subject | [
"def",
"__init__",
"(",
"self",
",",
"subject",
")",
":",
"self",
".",
"_subject",
"=",
"subject"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Util.py#L598-L600 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/rolling.py | python | _Window._center_window | (self, result, window) | return result | Center the result in the window. | Center the result in the window. | [
"Center",
"the",
"result",
"in",
"the",
"window",
"."
] | def _center_window(self, result, window) -> np.ndarray:
"""
Center the result in the window.
"""
if self.axis > result.ndim - 1:
raise ValueError("Requested axis is larger then no. of argument dimensions")
offset = calculate_center_offset(window)
if offset > 0:
lead_indexer = [slice(None)] * result.ndim
lead_indexer[self.axis] = slice(offset, None)
result = np.copy(result[tuple(lead_indexer)])
return result | [
"def",
"_center_window",
"(",
"self",
",",
"result",
",",
"window",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"self",
".",
"axis",
">",
"result",
".",
"ndim",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"Requested axis is larger then no. of argument dimensi... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/rolling.py#L355-L367 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/__init__.py | python | PackageFinder._find_packages_iter | (cls, where, exclude, include) | All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter. | All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter. | [
"All",
"the",
"packages",
"found",
"in",
"where",
"that",
"pass",
"the",
"include",
"filter",
"but",
"not",
"the",
"exclude",
"filter",
"."
] | def _find_packages_iter(cls, where, exclude, include):
"""
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
"""
for root, dirs, files in os.walk(where, followlinks=True):
# Copy dirs to iterate over it, then empty dirs.
all_dirs = dirs[:]
dirs[:] = []
for dir in all_dirs:
full_path = os.path.join(root, dir)
rel_path = os.path.relpath(full_path, where)
package = rel_path.replace(os.path.sep, '.')
# Skip directory trees that are not valid packages
if ('.' in dir or not cls._looks_like_package(full_path)):
continue
# Should this package be included?
if include(package) and not exclude(package):
yield package
# Keep searching subdirectories, as there may be more packages
# down there, even if the parent was excluded.
dirs.append(dir) | [
"def",
"_find_packages_iter",
"(",
"cls",
",",
"where",
",",
"exclude",
",",
"include",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"where",
",",
"followlinks",
"=",
"True",
")",
":",
"# Copy dirs to iterate over it, t... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/__init__.py#L75-L100 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/openvino/runtime/opset1/ops.py | python | sin | (node: NodeInput, name: Optional[str] = None) | return _get_node_factory_opset1().create("Sin", [node]) | Apply sine function on the input node element-wise.
@param node: One of: input node, array or scalar.
@param name: Optional new name for output node.
@return New node with sin operation applied on it. | Apply sine function on the input node element-wise. | [
"Apply",
"sine",
"function",
"on",
"the",
"input",
"node",
"element",
"-",
"wise",
"."
] | def sin(node: NodeInput, name: Optional[str] = None) -> Node:
"""Apply sine function on the input node element-wise.
@param node: One of: input node, array or scalar.
@param name: Optional new name for output node.
@return New node with sin operation applied on it.
"""
return _get_node_factory_opset1().create("Sin", [node]) | [
"def",
"sin",
"(",
"node",
":",
"NodeInput",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Node",
":",
"return",
"_get_node_factory_opset1",
"(",
")",
".",
"create",
"(",
"\"Sin\"",
",",
"[",
"node",
"]",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset1/ops.py#L2532-L2539 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/training_eager_v1.py | python | _process_single_batch | (model,
inputs,
targets,
output_loss_metrics=None,
sample_weights=None,
training=False) | Calculate the loss and gradient for one input batch.
The model weights are updated if training is set to True.
Args:
model: Model whose loss has to be calculated.
inputs: List of input arrays.
targets: List of target arrays.
output_loss_metrics: List of metrics that are used to aggregated output
loss values.
sample_weights: Optional list of sample weight arrays.
training: The boolean represents if the weights of the model are updated.
'fit' methods will set this to True while 'evaluate' methods will
set this to False.
Returns:
output of the model, total loss, the loss and the mask
associated with each output.
Raises:
ValueError: If the model has no loss to optimize. | Calculate the loss and gradient for one input batch. | [
"Calculate",
"the",
"loss",
"and",
"gradient",
"for",
"one",
"input",
"batch",
"."
] | def _process_single_batch(model,
inputs,
targets,
output_loss_metrics=None,
sample_weights=None,
training=False):
"""Calculate the loss and gradient for one input batch.
The model weights are updated if training is set to True.
Args:
model: Model whose loss has to be calculated.
inputs: List of input arrays.
targets: List of target arrays.
output_loss_metrics: List of metrics that are used to aggregated output
loss values.
sample_weights: Optional list of sample weight arrays.
training: The boolean represents if the weights of the model are updated.
'fit' methods will set this to True while 'evaluate' methods will
set this to False.
Returns:
output of the model, total loss, the loss and the mask
associated with each output.
Raises:
ValueError: If the model has no loss to optimize.
"""
with backend.eager_learning_phase_scope(1 if training else 0), \
training_utils.RespectCompiledTrainableState(model):
with GradientTape() as tape:
outs, total_loss, output_losses, masks = (
_model_loss(
model,
inputs,
targets,
output_loss_metrics=output_loss_metrics,
sample_weights=sample_weights,
training=training))
if isinstance(model.optimizer, loss_scale_optimizer.LossScaleOptimizer):
scaled_total_loss = model.optimizer.get_scaled_loss(total_loss)
else:
scaled_total_loss = total_loss
if training:
trainable_weights = model.trainable_weights
if trainable_weights:
# TODO(tanzheny) b/132690565: Provide mechanism for user to override
# model.train_on_batch.
if hasattr(model, '_backwards'):
model._backwards(tape, scaled_total_loss)
else:
grads = tape.gradient(scaled_total_loss, trainable_weights)
if isinstance(model.optimizer,
loss_scale_optimizer.LossScaleOptimizer):
grads = model.optimizer.get_unscaled_gradients(grads)
model.optimizer.apply_gradients(zip(grads, trainable_weights))
else:
logging.warning('The list of trainable weights is empty. Make sure that'
' you are not setting model.trainable to False before '
'compiling the model.')
return outs, total_loss, output_losses, masks | [
"def",
"_process_single_batch",
"(",
"model",
",",
"inputs",
",",
"targets",
",",
"output_loss_metrics",
"=",
"None",
",",
"sample_weights",
"=",
"None",
",",
"training",
"=",
"False",
")",
":",
"with",
"backend",
".",
"eager_learning_phase_scope",
"(",
"1",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/training_eager_v1.py#L220-L280 | ||
MhLiao/TextBoxes_plusplus | 39d4898de1504c53a2ed3d67966a57b3595836d0 | scripts/cpp_lint.py | python | FindStartOfExpressionInLine | (line, endpos, depth, startchar, endchar) | return (-1, depth) | Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line) | Find position at the matching startchar. | [
"Find",
"position",
"at",
"the",
"matching",
"startchar",
"."
] | def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
"""Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line)
"""
for i in xrange(endpos, -1, -1):
if line[i] == endchar:
depth += 1
elif line[i] == startchar:
depth -= 1
if depth == 0:
return (i, 0)
return (-1, depth) | [
"def",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"endpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"endpos",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"endch... | https://github.com/MhLiao/TextBoxes_plusplus/blob/39d4898de1504c53a2ed3d67966a57b3595836d0/scripts/cpp_lint.py#L1300-L1324 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/utils.py | python | _info | (obj, output=sys.stdout) | Provide information about ndarray obj.
Parameters
----------
obj : ndarray
Must be ndarray, not checked.
output
Where printed output goes.
Notes
-----
Copied over from the numarray module prior to its removal.
Adapted somewhat as only numpy is an option now.
Called by info. | Provide information about ndarray obj. | [
"Provide",
"information",
"about",
"ndarray",
"obj",
"."
] | def _info(obj, output=sys.stdout):
"""Provide information about ndarray obj.
Parameters
----------
obj : ndarray
Must be ndarray, not checked.
output
Where printed output goes.
Notes
-----
Copied over from the numarray module prior to its removal.
Adapted somewhat as only numpy is an option now.
Called by info.
"""
extra = ""
tic = ""
bp = lambda x: x
cls = getattr(obj, '__class__', type(obj))
nm = getattr(cls, '__name__', cls)
strides = obj.strides
endian = obj.dtype.byteorder
print("class: ", nm, file=output)
print("shape: ", obj.shape, file=output)
print("strides: ", strides, file=output)
print("itemsize: ", obj.itemsize, file=output)
print("aligned: ", bp(obj.flags.aligned), file=output)
print("contiguous: ", bp(obj.flags.contiguous), file=output)
print("fortran: ", obj.flags.fortran, file=output)
print(
"data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra),
file=output
)
print("byteorder: ", end=' ', file=output)
if endian in ['|', '=']:
print("%s%s%s" % (tic, sys.byteorder, tic), file=output)
byteswap = False
elif endian == '>':
print("%sbig%s" % (tic, tic), file=output)
byteswap = sys.byteorder != "big"
else:
print("%slittle%s" % (tic, tic), file=output)
byteswap = sys.byteorder != "little"
print("byteswap: ", bp(byteswap), file=output)
print("type: %s" % obj.dtype, file=output) | [
"def",
"_info",
"(",
"obj",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"extra",
"=",
"\"\"",
"tic",
"=",
"\"\"",
"bp",
"=",
"lambda",
"x",
":",
"x",
"cls",
"=",
"getattr",
"(",
"obj",
",",
"'__class__'",
",",
"type",
"(",
"obj",
")",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/utils.py#L412-L460 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | TreeListCtrl.SetItemPyData | (*args, **kwargs) | return _gizmos.TreeListCtrl_SetItemPyData(*args, **kwargs) | SetItemPyData(self, TreeItemId item, PyObject obj) | SetItemPyData(self, TreeItemId item, PyObject obj) | [
"SetItemPyData",
"(",
"self",
"TreeItemId",
"item",
"PyObject",
"obj",
")"
] | def SetItemPyData(*args, **kwargs):
"""SetItemPyData(self, TreeItemId item, PyObject obj)"""
return _gizmos.TreeListCtrl_SetItemPyData(*args, **kwargs) | [
"def",
"SetItemPyData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_SetItemPyData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L679-L681 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_config.py | python | auto_cast_partition_dtype | () | return False | Whether incompatible row-partitioning dtypes should be auto-converted.
If true, then operations that combine RaggedTensors but have different
row-partitioning tensor dtypes will be automatically cast to a
compatible dtype (`tf.int64`). If false, then such operations will result
in an error.
Returns:
`bool` | Whether incompatible row-partitioning dtypes should be auto-converted. | [
"Whether",
"incompatible",
"row",
"-",
"partitioning",
"dtypes",
"should",
"be",
"auto",
"-",
"converted",
"."
] | def auto_cast_partition_dtype():
"""Whether incompatible row-partitioning dtypes should be auto-converted.
If true, then operations that combine RaggedTensors but have different
row-partitioning tensor dtypes will be automatically cast to a
compatible dtype (`tf.int64`). If false, then such operations will result
in an error.
Returns:
`bool`
"""
return False | [
"def",
"auto_cast_partition_dtype",
"(",
")",
":",
"return",
"False"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_config.py#L18-L29 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/parallel/_auto_parallel_context.py | python | _AutoParallelContext.get_all_reduce_fusion_split_sizes | (self, group="") | return self._context_handle.get_all_reduce_fusion_split_sizes(new_group) | Get allreduce fusion split sizes.
Args:
group (str): The communication group of hccl/nccl.
Returns:
Return split sizes list according to the group.
Raises:
TypeError: If group is not a python str. | Get allreduce fusion split sizes. | [
"Get",
"allreduce",
"fusion",
"split",
"sizes",
"."
] | def get_all_reduce_fusion_split_sizes(self, group=""):
"""
Get allreduce fusion split sizes.
Args:
group (str): The communication group of hccl/nccl.
Returns:
Return split sizes list according to the group.
Raises:
TypeError: If group is not a python str.
"""
self.check_context_handle()
new_group = self._check_and_default_group(group)
return self._context_handle.get_all_reduce_fusion_split_sizes(new_group) | [
"def",
"get_all_reduce_fusion_split_sizes",
"(",
"self",
",",
"group",
"=",
"\"\"",
")",
":",
"self",
".",
"check_context_handle",
"(",
")",
"new_group",
"=",
"self",
".",
"_check_and_default_group",
"(",
"group",
")",
"return",
"self",
".",
"_context_handle",
"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/parallel/_auto_parallel_context.py#L598-L613 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/warnings.py | python | warnpy3k | (message, category=None, stacklevel=1) | Issue a deprecation warning for Python 3.x related changes.
Warnings are omitted unless Python is started with the -3 option. | Issue a deprecation warning for Python 3.x related changes. | [
"Issue",
"a",
"deprecation",
"warning",
"for",
"Python",
"3",
".",
"x",
"related",
"changes",
"."
] | def warnpy3k(message, category=None, stacklevel=1):
"""Issue a deprecation warning for Python 3.x related changes.
Warnings are omitted unless Python is started with the -3 option.
"""
if sys.py3kwarning:
if category is None:
category = DeprecationWarning
warn(message, category, stacklevel+1) | [
"def",
"warnpy3k",
"(",
"message",
",",
"category",
"=",
"None",
",",
"stacklevel",
"=",
"1",
")",
":",
"if",
"sys",
".",
"py3kwarning",
":",
"if",
"category",
"is",
"None",
":",
"category",
"=",
"DeprecationWarning",
"warn",
"(",
"message",
",",
"catego... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/warnings.py#L14-L22 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/head.py | python | _BinarySvmHead.create_model_fn_ops | (self,
features,
mode,
labels=None,
train_op_fn=None,
logits=None,
logits_input=None,
scope=None) | See `Head`. | See `Head`. | [
"See",
"Head",
"."
] | def create_model_fn_ops(self,
features,
mode,
labels=None,
train_op_fn=None,
logits=None,
logits_input=None,
scope=None):
"""See `Head`."""
with variable_scope.variable_scope(
scope,
default_name=self.head_name or "binary_svm_head",
values=(tuple(six.itervalues(features)) +
(labels, logits, logits_input))):
labels = self._transform_labels(mode=mode, labels=labels)
logits = _logits(logits_input, logits, self.logits_dimension)
return _create_model_fn_ops(
features=features,
mode=mode,
loss_fn=self._loss_fn,
logits_to_predictions_fn=self._logits_to_predictions,
metrics_fn=self._metrics,
# TODO(zakaria): Handle labels for export.
create_output_alternatives_fn=self._create_output_alternatives,
labels=labels,
train_op_fn=train_op_fn,
logits=logits,
logits_dimension=self.logits_dimension,
head_name=self.head_name,
weight_column_name=self.weight_column_name,
enable_centered_bias=self._enable_centered_bias) | [
"def",
"create_model_fn_ops",
"(",
"self",
",",
"features",
",",
"mode",
",",
"labels",
"=",
"None",
",",
"train_op_fn",
"=",
"None",
",",
"logits",
"=",
"None",
",",
"logits_input",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"with",
"variable_sco... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/head.py#L1252-L1282 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/PropertiesDescriptors.py | python | AvrgAccuracy.__get__ | (self, instance, owner=None) | return current number of significant digits | return current number of significant digits | [
"return",
"current",
"number",
"of",
"significant",
"digits"
] | def __get__(self, instance, owner=None):
""" return current number of significant digits"""
if instance is None:
return self
else:
return self._accuracy | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"owner",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"else",
":",
"return",
"self",
".",
"_accuracy"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/PropertiesDescriptors.py#L104-L109 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/session.py | python | Session.events | (self) | return self._session.get_component('event_emitter') | The event emitter for a session | The event emitter for a session | [
"The",
"event",
"emitter",
"for",
"a",
"session"
] | def events(self):
"""
The event emitter for a session
"""
return self._session.get_component('event_emitter') | [
"def",
"events",
"(",
"self",
")",
":",
"return",
"self",
".",
"_session",
".",
"get_component",
"(",
"'event_emitter'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/session.py#L103-L107 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | lite/pylite/megenginelite/tensor.py | python | LiteTensor.share_memory_with | (self, src_tensor) | share the same memory with the src_tensor, the self memory will be freed | share the same memory with the src_tensor, the self memory will be freed | [
"share",
"the",
"same",
"memory",
"with",
"the",
"src_tensor",
"the",
"self",
"memory",
"will",
"be",
"freed"
] | def share_memory_with(self, src_tensor):
"""
share the same memory with the src_tensor, the self memory will be freed
"""
assert isinstance(src_tensor, LiteTensor)
self._api.LITE_tensor_share_memory_with(self._tensor, src_tensor._tensor)
self.update() | [
"def",
"share_memory_with",
"(",
"self",
",",
"src_tensor",
")",
":",
"assert",
"isinstance",
"(",
"src_tensor",
",",
"LiteTensor",
")",
"self",
".",
"_api",
".",
"LITE_tensor_share_memory_with",
"(",
"self",
".",
"_tensor",
",",
"src_tensor",
".",
"_tensor",
... | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/lite/pylite/megenginelite/tensor.py#L239-L245 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/filters.py | python | do_min | (environment, value, case_sensitive=False, attribute=None) | return _min_or_max(environment, value, min, case_sensitive, attribute) | Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute. | Return the smallest item from the sequence. | [
"Return",
"the",
"smallest",
"item",
"from",
"the",
"sequence",
"."
] | def do_min(environment, value, case_sensitive=False, attribute=None):
"""Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, min, case_sensitive, attribute) | [
"def",
"do_min",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"return",
"_min_or_max",
"(",
"environment",
",",
"value",
",",
"min",
",",
"case_sensitive",
",",
"attribute",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/filters.py#L326-L337 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Main/glue/vboxapi.py | python | _CustomGetAttr | (self, sAttr) | Our getattr replacement for DispatchBaseClass. | Our getattr replacement for DispatchBaseClass. | [
"Our",
"getattr",
"replacement",
"for",
"DispatchBaseClass",
"."
] | def _CustomGetAttr(self, sAttr):
""" Our getattr replacement for DispatchBaseClass. """
# Fastpath.
oRet = self.__class__.__dict__.get(sAttr)
if oRet is not None:
return oRet
# Try case-insensitivity workaround for class attributes (COM methods).
sAttrLower = sAttr.lower()
for k in list(self.__class__.__dict__.keys()):
if k.lower() == sAttrLower:
setattr(self.__class__, sAttr, self.__class__.__dict__[k])
return getattr(self, k)
# Slow path.
try:
return _g_dCOMForward['getattr'](self, ComifyName(sAttr))
except AttributeError:
return _g_dCOMForward['getattr'](self, sAttr) | [
"def",
"_CustomGetAttr",
"(",
"self",
",",
"sAttr",
")",
":",
"# Fastpath.",
"oRet",
"=",
"self",
".",
"__class__",
".",
"__dict__",
".",
"get",
"(",
"sAttr",
")",
"if",
"oRet",
"is",
"not",
"None",
":",
"return",
"oRet",
"# Try case-insensitivity workaround... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Main/glue/vboxapi.py#L169-L187 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | SingleInstanceChecker.Create | (*args, **kwargs) | return _misc_.SingleInstanceChecker_Create(*args, **kwargs) | Create(self, String name, String path=EmptyString) -> bool | Create(self, String name, String path=EmptyString) -> bool | [
"Create",
"(",
"self",
"String",
"name",
"String",
"path",
"=",
"EmptyString",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""Create(self, String name, String path=EmptyString) -> bool"""
return _misc_.SingleInstanceChecker_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"SingleInstanceChecker_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L974-L976 | |
supercollider/supercollider | 42715a73ce2de4720174583e9b66a4510fe289a3 | external_libraries/simplejson-2.3.2/encoder.py | python | py_encode_basestring_ascii | (s) | return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' | Return an ASCII-only JSON representation of a Python string | Return an ASCII-only JSON representation of a Python string | [
"Return",
"an",
"ASCII",
"-",
"only",
"JSON",
"representation",
"of",
"a",
"Python",
"string"
] | def py_encode_basestring_ascii(s):
"""Return an ASCII-only JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except KeyError:
n = ord(s)
if n < 0x10000:
#return '\\u{0:04x}'.format(n)
return '\\u%04x' % (n,)
else:
# surrogate pair
n -= 0x10000
s1 = 0xd800 | ((n >> 10) & 0x3ff)
s2 = 0xdc00 | (n & 0x3ff)
#return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
return '\\u%04x\\u%04x' % (s1, s2)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' | [
"def",
"py_encode_basestring_ascii",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
"and",
"HAS_UTF8",
".",
"search",
"(",
"s",
")",
"is",
"not",
"None",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"'utf-8'",
")",
"def",
"replace",
... | https://github.com/supercollider/supercollider/blob/42715a73ce2de4720174583e9b66a4510fe289a3/external_libraries/simplejson-2.3.2/encoder.py#L47-L69 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetLdflags | (self, configname, product_dir, gyp_to_build_path, arch=None) | return ldflags | Returns flags that need to be passed to the linker.
Args:
configname: The name of the configuration to get ld flags for.
product_dir: The directory where products such static and dynamic
libraries are placed. This is added to the library search path.
gyp_to_build_path: A function that converts paths relative to the
current gyp file to paths relative to the build direcotry. | Returns flags that need to be passed to the linker. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"passed",
"to",
"the",
"linker",
"."
] | def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
"""Returns flags that need to be passed to the linker.
Args:
configname: The name of the configuration to get ld flags for.
product_dir: The directory where products such static and dynamic
libraries are placed. This is added to the library search path.
gyp_to_build_path: A function that converts paths relative to the
current gyp file to paths relative to the build direcotry.
"""
self.configname = configname
ldflags = []
# The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS
# can contain entries that depend on this. Explicitly absolutify these.
for ldflag in self._Settings().get('OTHER_LDFLAGS', []):
ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path))
if self._Test('DEAD_CODE_STRIPPING', 'YES', default='NO'):
ldflags.append('-Wl,-dead_strip')
if self._Test('PREBINDING', 'YES', default='NO'):
ldflags.append('-Wl,-prebind')
self._Appendf(
ldflags, 'DYLIB_COMPATIBILITY_VERSION', '-compatibility_version %s')
self._Appendf(
ldflags, 'DYLIB_CURRENT_VERSION', '-current_version %s')
self._AppendPlatformVersionMinFlags(ldflags)
if 'SDKROOT' in self._Settings() and self._SdkPath():
ldflags.append('-isysroot ' + self._SdkPath())
for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []):
ldflags.append('-L' + gyp_to_build_path(library_path))
if 'ORDER_FILE' in self._Settings():
ldflags.append('-Wl,-order_file ' +
'-Wl,' + gyp_to_build_path(
self._Settings()['ORDER_FILE']))
if arch is not None:
archs = [arch]
else:
assert self.configname
archs = self.GetActiveArchs(self.configname)
if len(archs) != 1:
# TODO: Supporting fat binaries will be annoying.
self._WarnUnimplemented('ARCHS')
archs = ['i386']
ldflags.append('-arch ' + archs[0])
# Xcode adds the product directory by default.
ldflags.append('-L' + product_dir)
install_name = self.GetInstallName()
if install_name and self.spec['type'] != 'loadable_module':
ldflags.append('-install_name ' + install_name.replace(' ', r'\ '))
for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []):
ldflags.append('-Wl,-rpath,' + rpath)
sdk_root = self._SdkPath()
if not sdk_root:
sdk_root = ''
config = self.spec['configurations'][self.configname]
framework_dirs = config.get('mac_framework_dirs', [])
for directory in framework_dirs:
ldflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root))
if self._IsXCTest():
platform_root = self._XcodePlatformPath(configname)
if platform_root:
cflags.append('-F' + platform_root + '/Developer/Library/Frameworks/')
is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension()
if sdk_root and is_extension:
# Adds the link flags for extensions. These flags are common for all
# extensions and provide loader and main function.
# These flags reflect the compilation options used by xcode to compile
# extensions.
ldflags.append('-lpkstart')
if XcodeVersion() < '0900':
ldflags.append(sdk_root +
'/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit')
ldflags.append('-fapplication-extension')
ldflags.append('-Xlinker -rpath '
'-Xlinker @executable_path/../../Frameworks')
self._Appendf(ldflags, 'CLANG_CXX_LIBRARY', '-stdlib=%s')
self.configname = None
return ldflags | [
"def",
"GetLdflags",
"(",
"self",
",",
"configname",
",",
"product_dir",
",",
"gyp_to_build_path",
",",
"arch",
"=",
"None",
")",
":",
"self",
".",
"configname",
"=",
"configname",
"ldflags",
"=",
"[",
"]",
"# The xcode build is relative to a gyp file's directory, a... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L771-L864 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/distributions/bijector_impl.py | python | _Mapping.merge | (self, x=None, y=None, ildj=None, kwargs=None, mapping=None) | return _Mapping(
x=self._merge(self.x, mapping.x),
y=self._merge(self.y, mapping.y),
ildj=self._merge(self.ildj, mapping.ildj),
kwargs=self._merge(self.kwargs, mapping.kwargs)) | Returns new _Mapping with args merged with self.
Args:
x: `Tensor`. Forward.
y: `Tensor`. Inverse.
ildj: `Tensor`. Inverse log det Jacobian.
kwargs: Python dictionary. Extra args supplied to
forward/inverse/etc functions.
mapping: Instance of _Mapping to merge. Can only be specified if no other
arg is specified.
Returns:
mapping: New instance of `_Mapping` which has inputs merged with self.
Raises:
ValueError: if mapping and any other arg is not `None`. | Returns new _Mapping with args merged with self. | [
"Returns",
"new",
"_Mapping",
"with",
"args",
"merged",
"with",
"self",
"."
] | def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None):
"""Returns new _Mapping with args merged with self.
Args:
x: `Tensor`. Forward.
y: `Tensor`. Inverse.
ildj: `Tensor`. Inverse log det Jacobian.
kwargs: Python dictionary. Extra args supplied to
forward/inverse/etc functions.
mapping: Instance of _Mapping to merge. Can only be specified if no other
arg is specified.
Returns:
mapping: New instance of `_Mapping` which has inputs merged with self.
Raises:
ValueError: if mapping and any other arg is not `None`.
"""
if mapping is None:
mapping = _Mapping(x=x, y=y, ildj=ildj, kwargs=kwargs)
elif not all(arg is None for arg in [x, y, ildj, kwargs]):
raise ValueError("Cannot specify mapping and individual args.")
return _Mapping(
x=self._merge(self.x, mapping.x),
y=self._merge(self.y, mapping.y),
ildj=self._merge(self.ildj, mapping.ildj),
kwargs=self._merge(self.kwargs, mapping.kwargs)) | [
"def",
"merge",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"ildj",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"mapping",
"=",
"None",
")",
":",
"if",
"mapping",
"is",
"None",
":",
"mapping",
"=",
"_Mapping",
"(",
"x",
"=... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/distributions/bijector_impl.py#L71-L97 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/combo.py | python | ComboPopup.SetStringValue | (*args, **kwargs) | return _combo.ComboPopup_SetStringValue(*args, **kwargs) | SetStringValue(self, String value)
Called just prior to displaying the popup. The derived class can
implement this to "select" the item in the popup that coresponds to
the passed in string value, if appropriate. The default
implementation does nothing. | SetStringValue(self, String value) | [
"SetStringValue",
"(",
"self",
"String",
"value",
")"
] | def SetStringValue(*args, **kwargs):
"""
SetStringValue(self, String value)
Called just prior to displaying the popup. The derived class can
implement this to "select" the item in the popup that coresponds to
the passed in string value, if appropriate. The default
implementation does nothing.
"""
return _combo.ComboPopup_SetStringValue(*args, **kwargs) | [
"def",
"SetStringValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"ComboPopup_SetStringValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/combo.py#L666-L675 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/tensor/math.py | python | broadcast_shape | (x_shape, y_shape) | return core.broadcast_shape(x_shape, y_shape) | The function returns the shape of doing operation with broadcasting on tensors of x_shape and y_shape, please refer to :ref:`user_guide_broadcasting` for more details.
Args:
x_shape (list[int]|tuple[int]): A shape of tensor.
y_shape (list[int]|tuple[int]): A shape of tensor.
Returns:
list[int], the result shape.
Examples:
.. code-block:: python
import paddle
shape = paddle.broadcast_shape([2, 1, 3], [1, 3, 1])
# [2, 3, 3]
# shape = paddle.broadcast_shape([2, 1, 3], [3, 3, 1])
# ValueError (terminated with error message). | The function returns the shape of doing operation with broadcasting on tensors of x_shape and y_shape, please refer to :ref:`user_guide_broadcasting` for more details. | [
"The",
"function",
"returns",
"the",
"shape",
"of",
"doing",
"operation",
"with",
"broadcasting",
"on",
"tensors",
"of",
"x_shape",
"and",
"y_shape",
"please",
"refer",
"to",
":",
"ref",
":",
"user_guide_broadcasting",
"for",
"more",
"details",
"."
] | def broadcast_shape(x_shape, y_shape):
"""
The function returns the shape of doing operation with broadcasting on tensors of x_shape and y_shape, please refer to :ref:`user_guide_broadcasting` for more details.
Args:
x_shape (list[int]|tuple[int]): A shape of tensor.
y_shape (list[int]|tuple[int]): A shape of tensor.
Returns:
list[int], the result shape.
Examples:
.. code-block:: python
import paddle
shape = paddle.broadcast_shape([2, 1, 3], [1, 3, 1])
# [2, 3, 3]
# shape = paddle.broadcast_shape([2, 1, 3], [3, 3, 1])
# ValueError (terminated with error message).
"""
return core.broadcast_shape(x_shape, y_shape) | [
"def",
"broadcast_shape",
"(",
"x_shape",
",",
"y_shape",
")",
":",
"return",
"core",
".",
"broadcast_shape",
"(",
"x_shape",
",",
"y_shape",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/math.py#L3089-L3114 | |
Caffe-MPI/Caffe-MPI.github.io | df5992af571a2a19981b69635115c393f18d1c76 | python/caffe/coord_map.py | python | inverse | (coord_map) | return ax, 1 / a, -b / a | Invert a coord map by de-scaling and un-shifting;
this gives the backward mapping for the gradient. | Invert a coord map by de-scaling and un-shifting;
this gives the backward mapping for the gradient. | [
"Invert",
"a",
"coord",
"map",
"by",
"de",
"-",
"scaling",
"and",
"un",
"-",
"shifting",
";",
"this",
"gives",
"the",
"backward",
"mapping",
"for",
"the",
"gradient",
"."
] | def inverse(coord_map):
"""
Invert a coord map by de-scaling and un-shifting;
this gives the backward mapping for the gradient.
"""
ax, a, b = coord_map
return ax, 1 / a, -b / a | [
"def",
"inverse",
"(",
"coord_map",
")",
":",
"ax",
",",
"a",
",",
"b",
"=",
"coord_map",
"return",
"ax",
",",
"1",
"/",
"a",
",",
"-",
"b",
"/",
"a"
] | https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/python/caffe/coord_map.py#L106-L112 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/boto3/resources/model.py | python | ResourceModel.batch_actions | (self) | return actions | Get a list of batch actions for this resource.
:type: list(:py:class:`Action`) | Get a list of batch actions for this resource. | [
"Get",
"a",
"list",
"of",
"batch",
"actions",
"for",
"this",
"resource",
"."
] | def batch_actions(self):
"""
Get a list of batch actions for this resource.
:type: list(:py:class:`Action`)
"""
actions = []
for name, item in self._definition.get('batchActions', {}).items():
name = self._get_name('batch_action', name)
actions.append(Action(name, item, self._resource_defs))
return actions | [
"def",
"batch_actions",
"(",
"self",
")",
":",
"actions",
"=",
"[",
"]",
"for",
"name",
",",
"item",
"in",
"self",
".",
"_definition",
".",
"get",
"(",
"'batchActions'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"name",
"=",
"self",
".",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/boto3/resources/model.py#L468-L480 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/position.py | python | Position.commission | (self, commission) | Sets the commission of this Position.
:param commission: The commission of this Position. # noqa: E501
:type: float | Sets the commission of this Position. | [
"Sets",
"the",
"commission",
"of",
"this",
"Position",
"."
] | def commission(self, commission):
"""Sets the commission of this Position.
:param commission: The commission of this Position. # noqa: E501
:type: float
"""
self._commission = commission | [
"def",
"commission",
"(",
"self",
",",
"commission",
")",
":",
"self",
".",
"_commission",
"=",
"commission"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L619-L627 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_v2_toggles.py | python | disable_control_flow_v2 | () | Opts out of control flow v2.
Note: v2 control flow is always enabled inside of tf.function. Calling this
function has no effect in that case.
If your code needs tf.disable_control_flow_v2() to be called to work
properly please file a bug. | Opts out of control flow v2. | [
"Opts",
"out",
"of",
"control",
"flow",
"v2",
"."
] | def disable_control_flow_v2(): # pylint: disable=invalid-name
"""Opts out of control flow v2.
Note: v2 control flow is always enabled inside of tf.function. Calling this
function has no effect in that case.
If your code needs tf.disable_control_flow_v2() to be called to work
properly please file a bug.
"""
control_flow_util.ENABLE_CONTROL_FLOW_V2 = False | [
"def",
"disable_control_flow_v2",
"(",
")",
":",
"# pylint: disable=invalid-name",
"control_flow_util",
".",
"ENABLE_CONTROL_FLOW_V2",
"=",
"False"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_v2_toggles.py#L49-L58 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/stride_tricks.py | python | broadcast_arrays | (*args, **kwargs) | return [_broadcast_to(array, shape, subok=subok, readonly=False)
for array in args] | Broadcast any number of arrays against each other.
Parameters
----------
`*args` : array_likes
The arrays to broadcast.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned arrays will be forced to be a base-class array (default).
Returns
-------
broadcasted : list of arrays
These arrays are views on the original arrays. They are typically
not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location. If you
need to write to the arrays, make copies first.
Examples
--------
>>> x = np.array([[1,2,3]])
>>> y = np.array([[4],[5]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
[1, 2, 3]]), array([[4, 4, 4],
[5, 5, 5]])]
Here is a useful idiom for getting contiguous copies instead of
non-contiguous views.
>>> [np.array(a) for a in np.broadcast_arrays(x, y)]
[array([[1, 2, 3],
[1, 2, 3]]), array([[4, 4, 4],
[5, 5, 5]])] | Broadcast any number of arrays against each other. | [
"Broadcast",
"any",
"number",
"of",
"arrays",
"against",
"each",
"other",
"."
] | def broadcast_arrays(*args, **kwargs):
"""
Broadcast any number of arrays against each other.
Parameters
----------
`*args` : array_likes
The arrays to broadcast.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned arrays will be forced to be a base-class array (default).
Returns
-------
broadcasted : list of arrays
These arrays are views on the original arrays. They are typically
not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location. If you
need to write to the arrays, make copies first.
Examples
--------
>>> x = np.array([[1,2,3]])
>>> y = np.array([[4],[5]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
[1, 2, 3]]), array([[4, 4, 4],
[5, 5, 5]])]
Here is a useful idiom for getting contiguous copies instead of
non-contiguous views.
>>> [np.array(a) for a in np.broadcast_arrays(x, y)]
[array([[1, 2, 3],
[1, 2, 3]]), array([[4, 4, 4],
[5, 5, 5]])]
"""
# nditer is not used here to avoid the limit of 32 arrays.
# Otherwise, something like the following one-liner would suffice:
# return np.nditer(args, flags=['multi_index', 'zerosize_ok'],
# order='C').itviews
subok = kwargs.pop('subok', False)
if kwargs:
raise TypeError('broadcast_arrays() got an unexpected keyword '
'argument {!r}'.format(list(kwargs.keys())[0]))
args = [np.array(_m, copy=False, subok=subok) for _m in args]
shape = _broadcast_shape(*args)
if all(array.shape == shape for array in args):
# Common case where nothing needs to be broadcasted.
return args
# TODO: consider making the results of broadcast_arrays readonly to match
# broadcast_to. This will require a deprecation cycle.
return [_broadcast_to(array, shape, subok=subok, readonly=False)
for array in args] | [
"def",
"broadcast_arrays",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# nditer is not used here to avoid the limit of 32 arrays.",
"# Otherwise, something like the following one-liner would suffice:",
"# return np.nditer(args, flags=['multi_index', 'zerosize_ok'],",
"# ... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/stride_tricks.py#L209-L268 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/codecs.py | python | getencoder | (encoding) | return lookup(encoding).encode | Lookup up the codec for the given encoding and return
its encoder function.
Raises a LookupError in case the encoding cannot be found. | Lookup up the codec for the given encoding and return
its encoder function. | [
"Lookup",
"up",
"the",
"codec",
"for",
"the",
"given",
"encoding",
"and",
"return",
"its",
"encoder",
"function",
"."
] | def getencoder(encoding):
""" Lookup up the codec for the given encoding and return
its encoder function.
Raises a LookupError in case the encoding cannot be found.
"""
return lookup(encoding).encode | [
"def",
"getencoder",
"(",
"encoding",
")",
":",
"return",
"lookup",
"(",
"encoding",
")",
".",
"encode"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/codecs.py#L956-L964 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py | python | FakeOsModule.rename | (self, old_file, new_file) | Adds a FakeFile object at new_file containing contents of old_file.
Also removes the FakeFile object for old_file, and replaces existing
new_file object, if one existed.
Args:
old_file: path to filesystem object to rename
new_file: path to where the filesystem object will live after this call
Raises:
OSError: if old_file does not exist.
IOError: if dirname(new_file) does not exist | Adds a FakeFile object at new_file containing contents of old_file. | [
"Adds",
"a",
"FakeFile",
"object",
"at",
"new_file",
"containing",
"contents",
"of",
"old_file",
"."
] | def rename(self, old_file, new_file):
"""Adds a FakeFile object at new_file containing contents of old_file.
Also removes the FakeFile object for old_file, and replaces existing
new_file object, if one existed.
Args:
old_file: path to filesystem object to rename
new_file: path to where the filesystem object will live after this call
Raises:
OSError: if old_file does not exist.
IOError: if dirname(new_file) does not exist
"""
old_file = self.filesystem.NormalizePath(old_file)
new_file = self.filesystem.NormalizePath(new_file)
if not self.filesystem.Exists(old_file):
raise OSError(errno.ENOENT,
'Fake os object: can not rename nonexistent file '
'with name',
old_file)
if self.filesystem.Exists(new_file):
if old_file == new_file:
return None # Nothing to do here.
else:
self.remove(new_file)
old_dir, old_name = self.path.split(old_file)
new_dir, new_name = self.path.split(new_file)
if not self.filesystem.Exists(new_dir):
raise IOError(errno.ENOENT, 'No such fake directory', new_dir)
old_dir_object = self.filesystem.ResolveObject(old_dir)
old_object = old_dir_object.GetEntry(old_name)
old_object_mtime = old_object.st_mtime
new_dir_object = self.filesystem.ResolveObject(new_dir)
if old_object.st_mode & stat.S_IFDIR:
old_object.name = new_name
new_dir_object.AddEntry(old_object)
old_dir_object.RemoveEntry(old_name)
else:
self.filesystem.CreateFile(new_file,
st_mode=old_object.st_mode,
contents=old_object.contents,
create_missing_dirs=False)
self.remove(old_file)
new_object = self.filesystem.GetObject(new_file)
new_object.SetMTime(old_object_mtime)
self.chown(new_file, old_object.st_uid, old_object.st_gid) | [
"def",
"rename",
"(",
"self",
",",
"old_file",
",",
"new_file",
")",
":",
"old_file",
"=",
"self",
".",
"filesystem",
".",
"NormalizePath",
"(",
"old_file",
")",
"new_file",
"=",
"self",
".",
"filesystem",
".",
"NormalizePath",
"(",
"new_file",
")",
"if",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L1559-L1605 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/io_ops.py | python | TextLineReader.__init__ | (self, skip_header_lines=None, name=None) | Create a TextLineReader.
Args:
skip_header_lines: An optional int. Defaults to 0. Number of lines
to skip from the beginning of every file.
name: A name for the operation (optional). | Create a TextLineReader. | [
"Create",
"a",
"TextLineReader",
"."
] | def __init__(self, skip_header_lines=None, name=None):
"""Create a TextLineReader.
Args:
skip_header_lines: An optional int. Defaults to 0. Number of lines
to skip from the beginning of every file.
name: A name for the operation (optional).
"""
rr = gen_io_ops._text_line_reader(skip_header_lines=skip_header_lines,
name=name)
super(TextLineReader, self).__init__(rr) | [
"def",
"__init__",
"(",
"self",
",",
"skip_header_lines",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"rr",
"=",
"gen_io_ops",
".",
"_text_line_reader",
"(",
"skip_header_lines",
"=",
"skip_header_lines",
",",
"name",
"=",
"name",
")",
"super",
"(",
"... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L478-L488 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/swig.py | python | _get_swig_version | (env, swig) | Run the SWIG command line tool to get and return the version number | Run the SWIG command line tool to get and return the version number | [
"Run",
"the",
"SWIG",
"command",
"line",
"tool",
"to",
"get",
"and",
"return",
"the",
"version",
"number"
] | def _get_swig_version(env, swig):
"""Run the SWIG command line tool to get and return the version number"""
swig = env.subst(swig)
pipe = SCons.Action._subproc(env, SCons.Util.CLVar(swig) + ['-version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
out = pipe.stdout.read()
match = re.search(r'SWIG Version\s+(\S+).*', out, re.MULTILINE)
if match:
if verbose: print "Version is:%s"%match.group(1)
return match.group(1)
else:
if verbose: print "Unable to detect version: [%s]"%out | [
"def",
"_get_swig_version",
"(",
"env",
",",
"swig",
")",
":",
"swig",
"=",
"env",
".",
"subst",
"(",
"swig",
")",
"pipe",
"=",
"SCons",
".",
"Action",
".",
"_subproc",
"(",
"env",
",",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"swig",
")",
"+",
"... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/swig.py#L134-L149 | ||
google/ion | ef47f3b824050499ce5c6f774b366f6c4dbce0af | ion/build.py | python | TargetBuilder.GypArgs | (self) | return collections.defaultdict(list, {
'-G': generator_flags,
'--depth': '{m}'.format(m=ROOT_DIR),
'--check': None,
'--suffix': '_{p}'.format(p=self.TARGET_OS),
}) | Returns a dictionary of extra arguments this builder will pass to gyp.
By default, this specifies -Goutput_dir and --depth, both of which are
necessary for gyp to work correctly. If you override this in subclasses, be
sure to call the superclass method and add additional args rather than
building a new dictionary from scratch.
If the value for a key is a list containing multiple elements, the argument
will be passed multiple times to gyp. If it is a string or a single-element
list, it will be passed only once. (And if it's an empty list, it won't be
passed at all.)
The dictionary returned by this method is actually a collections.defaultdict
that uses an empty list as the default value for any key not otherwise
specified. This means that it is okay for subclasses to blindly append
values to a given key, but note that it is still possible to clobber
existing keys by using = instead of +=, so only do that if you mean to.
Returns:
A collections.defaultdict of extra arguments to pass to gyp. | Returns a dictionary of extra arguments this builder will pass to gyp. | [
"Returns",
"a",
"dictionary",
"of",
"extra",
"arguments",
"this",
"builder",
"will",
"pass",
"to",
"gyp",
"."
] | def GypArgs(self):
"""Returns a dictionary of extra arguments this builder will pass to gyp.
By default, this specifies -Goutput_dir and --depth, both of which are
necessary for gyp to work correctly. If you override this in subclasses, be
sure to call the superclass method and add additional args rather than
building a new dictionary from scratch.
If the value for a key is a list containing multiple elements, the argument
will be passed multiple times to gyp. If it is a string or a single-element
list, it will be passed only once. (And if it's an empty list, it won't be
passed at all.)
The dictionary returned by this method is actually a collections.defaultdict
that uses an empty list as the default value for any key not otherwise
specified. This means that it is okay for subclasses to blindly append
values to a given key, but note that it is still possible to clobber
existing keys by using = instead of +=, so only do that if you mean to.
Returns:
A collections.defaultdict of extra arguments to pass to gyp.
"""
generator_flags = self.state.GetAdditionalGypGeneratorFlags()
generator_flags.append('output_dir={o}'.format(o=self.BuildOutputRootDir()))
return collections.defaultdict(list, {
'-G': generator_flags,
'--depth': '{m}'.format(m=ROOT_DIR),
'--check': None,
'--suffix': '_{p}'.format(p=self.TARGET_OS),
}) | [
"def",
"GypArgs",
"(",
"self",
")",
":",
"generator_flags",
"=",
"self",
".",
"state",
".",
"GetAdditionalGypGeneratorFlags",
"(",
")",
"generator_flags",
".",
"append",
"(",
"'output_dir={o}'",
".",
"format",
"(",
"o",
"=",
"self",
".",
"BuildOutputRootDir",
... | https://github.com/google/ion/blob/ef47f3b824050499ce5c6f774b366f6c4dbce0af/ion/build.py#L440-L469 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/logging/handlers.py | python | SocketHandler.createSocket | (self) | Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored. | Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored. | [
"Try",
"to",
"create",
"a",
"socket",
"using",
"an",
"exponential",
"backoff",
"with",
"a",
"max",
"retry",
"time",
".",
"Thanks",
"to",
"Robert",
"Olson",
"for",
"the",
"original",
"patch",
"(",
"SF",
"#815911",
")",
"which",
"has",
"been",
"slightly",
... | def createSocket(self):
"""
Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored.
"""
now = time.time()
# Either retryTime is None, in which case this
# is the first time back after a disconnect, or
# we've waited long enough.
if self.retryTime is None:
attempt = 1
else:
attempt = (now >= self.retryTime)
if attempt:
try:
self.sock = self.makeSocket()
self.retryTime = None # next time, no delay before trying
except socket.error:
#Creation failed, so set the retry time and return.
if self.retryTime is None:
self.retryPeriod = self.retryStart
else:
self.retryPeriod = self.retryPeriod * self.retryFactor
if self.retryPeriod > self.retryMax:
self.retryPeriod = self.retryMax
self.retryTime = now + self.retryPeriod | [
"def",
"createSocket",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# Either retryTime is None, in which case this",
"# is the first time back after a disconnect, or",
"# we've waited long enough.",
"if",
"self",
".",
"retryTime",
"is",
"None",
":",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/handlers.py#L477-L503 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/gluon/trainer.py | python | Trainer._init_params | (self) | Initialize parameters in the KVStore.
Parameters with incomplete initialization are ignored. | Initialize parameters in the KVStore. | [
"Initialize",
"parameters",
"in",
"the",
"KVStore",
"."
] | def _init_params(self):
"""Initialize parameters in the KVStore.
Parameters with incomplete initialization are ignored.
"""
assert self._kv_initialized, "Cannot initialize parameters in KVStore " \
"when KVStore is not initialized."
params_to_init = []
if self._kvstore:
for param in self._params_to_init:
if param._deferred_init:
params_to_init.append(param)
else:
param_arrays = param._check_and_get(param._data, list)
idx = self._param2idx[param.name]
self._kvstore.init(idx, param_arrays[0])
if param._stype == 'default':
self._kvstore.pull(idx, param_arrays, priority=-idx)
self._params_to_init = params_to_init | [
"def",
"_init_params",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_kv_initialized",
",",
"\"Cannot initialize parameters in KVStore \"",
"\"when KVStore is not initialized.\"",
"params_to_init",
"=",
"[",
"]",
"if",
"self",
".",
"_kvstore",
":",
"for",
"param",
"i... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/trainer.py#L137-L157 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py | python | _ToLocalPath | (toplevel_dir, path) | return path | Converts |path| to a path relative to |toplevel_dir|. | Converts |path| to a path relative to |toplevel_dir|. | [
"Converts",
"|path|",
"to",
"a",
"path",
"relative",
"to",
"|toplevel_dir|",
"."
] | def _ToLocalPath(toplevel_dir, path):
"""Converts |path| to a path relative to |toplevel_dir|."""
if path == toplevel_dir:
return ''
if path.startswith(toplevel_dir + '/'):
return path[len(toplevel_dir) + len('/'):]
return path | [
"def",
"_ToLocalPath",
"(",
"toplevel_dir",
",",
"path",
")",
":",
"if",
"path",
"==",
"toplevel_dir",
":",
"return",
"''",
"if",
"path",
".",
"startswith",
"(",
"toplevel_dir",
"+",
"'/'",
")",
":",
"return",
"path",
"[",
"len",
"(",
"toplevel_dir",
")"... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py#L167-L173 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py | python | rv_generic._construct_default_doc | (self, longname=None, extradoc=None,
docdict=None, discrete='continuous') | Construct instance docstring from the default template. | Construct instance docstring from the default template. | [
"Construct",
"instance",
"docstring",
"from",
"the",
"default",
"template",
"."
] | def _construct_default_doc(self, longname=None, extradoc=None,
docdict=None, discrete='continuous'):
"""Construct instance docstring from the default template."""
if longname is None:
longname = 'A'
if extradoc is None:
extradoc = ''
if extradoc.startswith('\n\n'):
extradoc = extradoc[2:]
self.__doc__ = ''.join(['%s %s random variable.' % (longname, discrete),
'\n\n%(before_notes)s\n', docheaders['notes'],
extradoc, '\n%(example)s'])
self._construct_doc(docdict) | [
"def",
"_construct_default_doc",
"(",
"self",
",",
"longname",
"=",
"None",
",",
"extradoc",
"=",
"None",
",",
"docdict",
"=",
"None",
",",
"discrete",
"=",
"'continuous'",
")",
":",
"if",
"longname",
"is",
"None",
":",
"longname",
"=",
"'A'",
"if",
"ext... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py#L738-L750 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/configure.py | python | cc_macros | (cc=None) | return k | Checks predefined macros using the C compiler command. | Checks predefined macros using the C compiler command. | [
"Checks",
"predefined",
"macros",
"using",
"the",
"C",
"compiler",
"command",
"."
] | def cc_macros(cc=None):
"""Checks predefined macros using the C compiler command."""
try:
p = subprocess.Popen(shlex.split(cc or CC) + ['-dM', '-E', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError:
error('''No acceptable C compiler found!
Please make sure you have a C compiler installed on your system and/or
consider adjusting the CC environment variable if you installed
it in a non-standard prefix.''')
p.stdin.write(b'\n')
out = to_utf8(p.communicate()[0]).split('\n')
k = {}
for line in out:
lst = shlex.split(line)
if len(lst) > 2:
key = lst[1]
val = lst[2]
k[key] = val
return k | [
"def",
"cc_macros",
"(",
"cc",
"=",
"None",
")",
":",
"try",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"shlex",
".",
"split",
"(",
"cc",
"or",
"CC",
")",
"+",
"[",
"'-dM'",
",",
"'-E'",
",",
"'-'",
"]",
",",
"stdin",
"=",
"subprocess",
".... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/configure.py#L1025-L1050 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/isis_reduction_steps.py | python | Mask_ISIS.add_outside_cylinder | (self, radius, xcentre=0.0, ycentre=0.0, ID='shape') | Mask out the outside of a cylinder or specified radius | Mask out the outside of a cylinder or specified radius | [
"Mask",
"out",
"the",
"outside",
"of",
"a",
"cylinder",
"or",
"specified",
"radius"
] | def add_outside_cylinder(self, radius, xcentre=0.0, ycentre=0.0, ID='shape'):
'''Mask out the outside of a cylinder or specified radius'''
self.add_xml_shape(
self._infinite_cylinder([xcentre, ycentre, 0.0], radius, [0, 0, 1], id=ID) + '<algebra val="#' + str(
ID) + '"/>') | [
"def",
"add_outside_cylinder",
"(",
"self",
",",
"radius",
",",
"xcentre",
"=",
"0.0",
",",
"ycentre",
"=",
"0.0",
",",
"ID",
"=",
"'shape'",
")",
":",
"self",
".",
"add_xml_shape",
"(",
"self",
".",
"_infinite_cylinder",
"(",
"[",
"xcentre",
",",
"ycent... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_reduction_steps.py#L694-L698 | ||
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/pycaffe/tools.py | python | SimpleTransformer.preprocess | (self, im) | return im | preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt. | preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt. | [
"preprocess",
"()",
"emulate",
"the",
"pre",
"-",
"processing",
"occuring",
"in",
"the",
"vgg16",
"caffe",
"prototxt",
"."
] | def preprocess(self, im):
"""
preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt.
"""
im = np.float32(im)
im = im[:, :, ::-1] # change to BGR
im -= self.mean
im *= self.scale
im = im.transpose((2, 0, 1))
return im | [
"def",
"preprocess",
"(",
"self",
",",
"im",
")",
":",
"im",
"=",
"np",
".",
"float32",
"(",
"im",
")",
"im",
"=",
"im",
"[",
":",
",",
":",
",",
":",
":",
"-",
"1",
"]",
"# change to BGR",
"im",
"-=",
"self",
".",
"mean",
"im",
"*=",
"self",... | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/pycaffe/tools.py#L63-L75 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py | python | RegenerateAppendFlag | (flag, values, predicate, env_name, options) | return flags | Regenerate a list of command line flags, for an option of action='append'.
The |env_name|, if given, is checked in the environment and used to generate
an initial list of options, then the options that were specified on the
command line (given in |values|) are appended. This matches the handling of
environment variables and command line flags where command line flags override
the environment, while not requiring the environment to be set when the flags
are used again. | Regenerate a list of command line flags, for an option of action='append'. | [
"Regenerate",
"a",
"list",
"of",
"command",
"line",
"flags",
"for",
"an",
"option",
"of",
"action",
"=",
"append",
"."
] | def RegenerateAppendFlag(flag, values, predicate, env_name, options):
"""Regenerate a list of command line flags, for an option of action='append'.
The |env_name|, if given, is checked in the environment and used to generate
an initial list of options, then the options that were specified on the
command line (given in |values|) are appended. This matches the handling of
environment variables and command line flags where command line flags override
the environment, while not requiring the environment to be set when the flags
are used again.
"""
flags = []
if options.use_environment and env_name:
for flag_value in ShlexEnv(env_name):
value = FormatOpt(flag, predicate(flag_value))
if value in flags:
flags.remove(value)
flags.append(value)
if values:
for flag_value in values:
flags.append(FormatOpt(flag, predicate(flag_value)))
return flags | [
"def",
"RegenerateAppendFlag",
"(",
"flag",
",",
"values",
",",
"predicate",
",",
"env_name",
",",
"options",
")",
":",
"flags",
"=",
"[",
"]",
"if",
"options",
".",
"use_environment",
"and",
"env_name",
":",
"for",
"flag_value",
"in",
"ShlexEnv",
"(",
"en... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py#L166-L186 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/uu.py | python | encode | (in_file, out_file, name=None, mode=None) | Uuencode file | Uuencode file | [
"Uuencode",
"file"
] | def encode(in_file, out_file, name=None, mode=None):
"""Uuencode file"""
#
# If in_file is a pathname open it and change defaults
#
opened_files = []
try:
if in_file == '-':
in_file = sys.stdin
elif isinstance(in_file, basestring):
if name is None:
name = os.path.basename(in_file)
if mode is None:
try:
mode = os.stat(in_file).st_mode
except AttributeError:
pass
in_file = open(in_file, 'rb')
opened_files.append(in_file)
#
# Open out_file if it is a pathname
#
if out_file == '-':
out_file = sys.stdout
elif isinstance(out_file, basestring):
out_file = open(out_file, 'wb')
opened_files.append(out_file)
#
# Set defaults for name and mode
#
if name is None:
name = '-'
if mode is None:
mode = 0666
#
# Write the data
#
out_file.write('begin %o %s\n' % ((mode&0777),name))
data = in_file.read(45)
while len(data) > 0:
out_file.write(binascii.b2a_uu(data))
data = in_file.read(45)
out_file.write(' \nend\n')
finally:
for f in opened_files:
f.close() | [
"def",
"encode",
"(",
"in_file",
",",
"out_file",
",",
"name",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"#",
"# If in_file is a pathname open it and change defaults",
"#",
"opened_files",
"=",
"[",
"]",
"try",
":",
"if",
"in_file",
"==",
"'-'",
":",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/uu.py#L42-L87 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/mcts.py | python | RandomRolloutEvaluator.prior | (self, state) | Returns equal probability for all actions. | Returns equal probability for all actions. | [
"Returns",
"equal",
"probability",
"for",
"all",
"actions",
"."
] | def prior(self, state):
"""Returns equal probability for all actions."""
if state.is_chance_node():
return state.chance_outcomes()
else:
legal_actions = state.legal_actions(state.current_player())
return [(action, 1.0 / len(legal_actions)) for action in legal_actions] | [
"def",
"prior",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
".",
"is_chance_node",
"(",
")",
":",
"return",
"state",
".",
"chance_outcomes",
"(",
")",
"else",
":",
"legal_actions",
"=",
"state",
".",
"legal_actions",
"(",
"state",
".",
"current_p... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/mcts.py#L76-L82 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/ecdsa/ellipticcurve.py | python | Point.__mul__ | ( self, other ) | return result | Multiply a point by an integer. | Multiply a point by an integer. | [
"Multiply",
"a",
"point",
"by",
"an",
"integer",
"."
] | def __mul__( self, other ):
"""Multiply a point by an integer."""
def leftmost_bit( x ):
assert x > 0
result = 1
while result <= x: result = 2 * result
return result // 2
e = other
if self.__order: e = e % self.__order
if e == 0: return INFINITY
if self == INFINITY: return INFINITY
assert e > 0
# From X9.62 D.3.2:
e3 = 3 * e
negative_self = Point( self.__curve, self.__x, -self.__y, self.__order )
i = leftmost_bit( e3 ) // 2
result = self
# print_("Multiplying %s by %d (e3 = %d):" % ( self, other, e3 ))
while i > 1:
result = result.double()
if ( e3 & i ) != 0 and ( e & i ) == 0: result = result + self
if ( e3 & i ) == 0 and ( e & i ) != 0: result = result + negative_self
# print_(". . . i = %d, result = %s" % ( i, result ))
i = i // 2
return result | [
"def",
"__mul__",
"(",
"self",
",",
"other",
")",
":",
"def",
"leftmost_bit",
"(",
"x",
")",
":",
"assert",
"x",
">",
"0",
"result",
"=",
"1",
"while",
"result",
"<=",
"x",
":",
"result",
"=",
"2",
"*",
"result",
"return",
"result",
"//",
"2",
"e... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/ecdsa/ellipticcurve.py#L109-L138 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.