nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py | python | IRBuilder.convert_to_fp16 | (self, a) | Convert the given FP number to an i16 | Convert the given FP number to an i16 | [
"Convert",
"the",
"given",
"FP",
"number",
"to",
"an",
"i16"
] | def convert_to_fp16(self, a):
"""
Convert the given FP number to an i16
""" | [
"def",
"convert_to_fp16",
"(",
"self",
",",
"a",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py#L1054-L1057 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/workspacedisplay/table/presenter_standard.py | python | TableWorkspaceDataPresenterStandard.create_item | (data, editable) | return create_table_item(data, editable) | Create a QStandardItemModel for the data
:param data: The typed data to store
:param editable: True if it should be editable in the view | Create a QStandardItemModel for the data
:param data: The typed data to store
:param editable: True if it should be editable in the view | [
"Create",
"a",
"QStandardItemModel",
"for",
"the",
"data",
":",
"param",
"data",
":",
"The",
"typed",
"data",
"to",
"store",
":",
"param",
"editable",
":",
"True",
"if",
"it",
"should",
"be",
"editable",
"in",
"the",
"view"
] | def create_item(data, editable):
"""Create a QStandardItemModel for the data
:param data: The typed data to store
:param editable: True if it should be editable in the view
"""
return create_table_item(data, editable) | [
"def",
"create_item",
"(",
"data",
",",
"editable",
")",
":",
"return",
"create_table_item",
"(",
"data",
",",
"editable",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/workspacedisplay/table/presenter_standard.py#L46-L51 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/autograph/operators/slices.py | python | _tf_tensorarray_set_item | (target, i, x) | return target.write(i, x) | Overload of set_item that stages a TensorArray write. | Overload of set_item that stages a TensorArray write. | [
"Overload",
"of",
"set_item",
"that",
"stages",
"a",
"TensorArray",
"write",
"."
] | def _tf_tensorarray_set_item(target, i, x):
"""Overload of set_item that stages a TensorArray write."""
return target.write(i, x) | [
"def",
"_tf_tensorarray_set_item",
"(",
"target",
",",
"i",
",",
"x",
")",
":",
"return",
"target",
".",
"write",
"(",
"i",
",",
"x",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/operators/slices.py#L124-L126 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/dataframe.py | python | DataFrame.from_pandas | (cls, dataframe, nan_as_null=None) | return result | Convert from a Pandas DataFrame.
Parameters
----------
dataframe : Pandas DataFrame object
A Pandads DataFrame object which has to be converted
to cuDF DataFrame.
nan_as_null : bool, Default True
If ``True``, converts ``np.nan`` values to ``null`` values.
If ``False``, leaves ``np.nan`` values as is.
Raises
------
TypeError for invalid input type.
Examples
--------
>>> import cudf
>>> import pandas as pd
>>> data = [[0,1], [1,2], [3,4]]
>>> pdf = pd.DataFrame(data, columns=['a', 'b'], dtype=int)
>>> cudf.from_pandas(pdf)
a b
0 0 1
1 1 2
2 3 4 | Convert from a Pandas DataFrame. | [
"Convert",
"from",
"a",
"Pandas",
"DataFrame",
"."
] | def from_pandas(cls, dataframe, nan_as_null=None):
"""
Convert from a Pandas DataFrame.
Parameters
----------
dataframe : Pandas DataFrame object
A Pandads DataFrame object which has to be converted
to cuDF DataFrame.
nan_as_null : bool, Default True
If ``True``, converts ``np.nan`` values to ``null`` values.
If ``False``, leaves ``np.nan`` values as is.
Raises
------
TypeError for invalid input type.
Examples
--------
>>> import cudf
>>> import pandas as pd
>>> data = [[0,1], [1,2], [3,4]]
>>> pdf = pd.DataFrame(data, columns=['a', 'b'], dtype=int)
>>> cudf.from_pandas(pdf)
a b
0 0 1
1 1 2
2 3 4
"""
if not isinstance(dataframe, pd.DataFrame):
raise TypeError("not a pandas.DataFrame")
if not dataframe.columns.is_unique:
raise ValueError("Duplicate column names are not allowed")
df = cls()
# Set columns
for col_name, col_value in dataframe.iteritems():
# necessary because multi-index can return multiple
# columns for a single key
if len(col_value.shape) == 1:
df[col_name] = column.as_column(
col_value.array, nan_as_null=nan_as_null
)
else:
vals = col_value.values.T
if vals.shape[0] == 1:
df[col_name] = column.as_column(
vals.flatten(), nan_as_null=nan_as_null
)
else:
if isinstance(col_name, tuple):
col_name = str(col_name)
for idx in range(len(vals.shape)):
df[col_name] = column.as_column(
vals[idx], nan_as_null=nan_as_null
)
# Set columns only if it is a MultiIndex
if isinstance(dataframe.columns, pd.MultiIndex):
df.columns = dataframe.columns
# Set index
index = cudf.from_pandas(dataframe.index, nan_as_null=nan_as_null)
result = df.set_index(index)
return result | [
"def",
"from_pandas",
"(",
"cls",
",",
"dataframe",
",",
"nan_as_null",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataframe",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"TypeError",
"(",
"\"not a pandas.DataFrame\"",
")",
"if",
"not",
"dataframe",
".",
"columns",
".",
"is_unique",
":",
"raise",
"ValueError",
"(",
"\"Duplicate column names are not allowed\"",
")",
"df",
"=",
"cls",
"(",
")",
"# Set columns",
"for",
"col_name",
",",
"col_value",
"in",
"dataframe",
".",
"iteritems",
"(",
")",
":",
"# necessary because multi-index can return multiple",
"# columns for a single key",
"if",
"len",
"(",
"col_value",
".",
"shape",
")",
"==",
"1",
":",
"df",
"[",
"col_name",
"]",
"=",
"column",
".",
"as_column",
"(",
"col_value",
".",
"array",
",",
"nan_as_null",
"=",
"nan_as_null",
")",
"else",
":",
"vals",
"=",
"col_value",
".",
"values",
".",
"T",
"if",
"vals",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
":",
"df",
"[",
"col_name",
"]",
"=",
"column",
".",
"as_column",
"(",
"vals",
".",
"flatten",
"(",
")",
",",
"nan_as_null",
"=",
"nan_as_null",
")",
"else",
":",
"if",
"isinstance",
"(",
"col_name",
",",
"tuple",
")",
":",
"col_name",
"=",
"str",
"(",
"col_name",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"vals",
".",
"shape",
")",
")",
":",
"df",
"[",
"col_name",
"]",
"=",
"column",
".",
"as_column",
"(",
"vals",
"[",
"idx",
"]",
",",
"nan_as_null",
"=",
"nan_as_null",
")",
"# Set columns only if it is a MultiIndex",
"if",
"isinstance",
"(",
"dataframe",
".",
"columns",
",",
"pd",
".",
"MultiIndex",
")",
":",
"df",
".",
"columns",
"=",
"dataframe",
".",
"columns",
"# Set index",
"index",
"=",
"cudf",
".",
"from_pandas",
"(",
"dataframe",
".",
"index",
",",
"nan_as_null",
"=",
"nan_as_null",
")",
"result",
"=",
"df",
".",
"set_index",
"(",
"index",
")",
"return",
"result"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/dataframe.py#L4461-L4527 | |
chatopera/clause | dee31153d5ffdef33deedb6bff03e7806c296968 | src/lac/python/reader.py | python | test_reader | (file_dir,
word2id_dict,
label2id_dict,
word_replace_dict,
filename_feature="") | return reader | define the reader to read test files in file_dir | define the reader to read test files in file_dir | [
"define",
"the",
"reader",
"to",
"read",
"test",
"files",
"in",
"file_dir"
] | def test_reader(file_dir,
word2id_dict,
label2id_dict,
word_replace_dict,
filename_feature=""):
"""
define the reader to read test files in file_dir
"""
word_dict_len = max(map(int, word2id_dict.values())) + 1
label_dict_len = max(map(int, label2id_dict.values())) + 1
def reader():
"""
the data generator
"""
index = 0
for root, dirs, files in os.walk(file_dir):
for filename in files:
if not filename.startswith(filename_feature):
continue
for line in io.open(os.path.join(root, filename), 'r', encoding='utf8'):
index += 1
bad_line = False
line = line.strip("\n")
if len(line) == 0:
continue
seg_tag = line.rfind("\t")
if seg_tag == -1:
seg_tag = len(line)
word_part = line[0:seg_tag]
label_part = line[seg_tag + 1:]
word_idx = []
words = word_part
for word in words:
if ord(word) < 0x20:
word = ' '
if word in word_replace_dict:
word = word_replace_dict[word]
if word in word2id_dict:
word_idx.append(int(word2id_dict[word]))
else:
word_idx.append(int(word2id_dict["OOV"]))
yield word_idx, words
return reader | [
"def",
"test_reader",
"(",
"file_dir",
",",
"word2id_dict",
",",
"label2id_dict",
",",
"word_replace_dict",
",",
"filename_feature",
"=",
"\"\"",
")",
":",
"word_dict_len",
"=",
"max",
"(",
"map",
"(",
"int",
",",
"word2id_dict",
".",
"values",
"(",
")",
")",
")",
"+",
"1",
"label_dict_len",
"=",
"max",
"(",
"map",
"(",
"int",
",",
"label2id_dict",
".",
"values",
"(",
")",
")",
")",
"+",
"1",
"def",
"reader",
"(",
")",
":",
"\"\"\"\n the data generator\n \"\"\"",
"index",
"=",
"0",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"file_dir",
")",
":",
"for",
"filename",
"in",
"files",
":",
"if",
"not",
"filename",
".",
"startswith",
"(",
"filename_feature",
")",
":",
"continue",
"for",
"line",
"in",
"io",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"index",
"+=",
"1",
"bad_line",
"=",
"False",
"line",
"=",
"line",
".",
"strip",
"(",
"\"\\n\"",
")",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"continue",
"seg_tag",
"=",
"line",
".",
"rfind",
"(",
"\"\\t\"",
")",
"if",
"seg_tag",
"==",
"-",
"1",
":",
"seg_tag",
"=",
"len",
"(",
"line",
")",
"word_part",
"=",
"line",
"[",
"0",
":",
"seg_tag",
"]",
"label_part",
"=",
"line",
"[",
"seg_tag",
"+",
"1",
":",
"]",
"word_idx",
"=",
"[",
"]",
"words",
"=",
"word_part",
"for",
"word",
"in",
"words",
":",
"if",
"ord",
"(",
"word",
")",
"<",
"0x20",
":",
"word",
"=",
"' '",
"if",
"word",
"in",
"word_replace_dict",
":",
"word",
"=",
"word_replace_dict",
"[",
"word",
"]",
"if",
"word",
"in",
"word2id_dict",
":",
"word_idx",
".",
"append",
"(",
"int",
"(",
"word2id_dict",
"[",
"word",
"]",
")",
")",
"else",
":",
"word_idx",
".",
"append",
"(",
"int",
"(",
"word2id_dict",
"[",
"\"OOV\"",
"]",
")",
")",
"yield",
"word_idx",
",",
"words",
"return",
"reader"
] | https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/src/lac/python/reader.py#L59-L101 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Protocol/SecretSharing.py | python | _Element.inverse | (self) | return _Element(s0) | Return the inverse of this element in GF(2^128). | Return the inverse of this element in GF(2^128). | [
"Return",
"the",
"inverse",
"of",
"this",
"element",
"in",
"GF",
"(",
"2^128",
")",
"."
] | def inverse(self):
"""Return the inverse of this element in GF(2^128)."""
# We use the Extended GCD algorithm
# http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor
r0, r1 = self._value, self.irr_poly
s0, s1 = 1, 0
while r1 > 0:
q = _div_gf2(r0, r1)[0]
r0, r1 = r1, r0 ^ _mult_gf2(q, r1)
s0, s1 = s1, s0 ^ _mult_gf2(q, s1)
return _Element(s0) | [
"def",
"inverse",
"(",
"self",
")",
":",
"# We use the Extended GCD algorithm",
"# http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor",
"r0",
",",
"r1",
"=",
"self",
".",
"_value",
",",
"self",
".",
"irr_poly",
"s0",
",",
"s1",
"=",
"1",
",",
"0",
"while",
"r1",
">",
"0",
":",
"q",
"=",
"_div_gf2",
"(",
"r0",
",",
"r1",
")",
"[",
"0",
"]",
"r0",
",",
"r1",
"=",
"r1",
",",
"r0",
"^",
"_mult_gf2",
"(",
"q",
",",
"r1",
")",
"s0",
",",
"s1",
"=",
"s1",
",",
"s0",
"^",
"_mult_gf2",
"(",
"q",
",",
"s1",
")",
"return",
"_Element",
"(",
"s0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Protocol/SecretSharing.py#L132-L144 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/httplib.py | python | HTTPMessage.addheader | (self, key, value) | Add header for field key handling repeats. | Add header for field key handling repeats. | [
"Add",
"header",
"for",
"field",
"key",
"handling",
"repeats",
"."
] | def addheader(self, key, value):
"""Add header for field key handling repeats."""
prev = self.dict.get(key)
if prev is None:
self.dict[key] = value
else:
combined = ", ".join((prev, value))
self.dict[key] = combined | [
"def",
"addheader",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"prev",
"=",
"self",
".",
"dict",
".",
"get",
"(",
"key",
")",
"if",
"prev",
"is",
"None",
":",
"self",
".",
"dict",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"combined",
"=",
"\", \"",
".",
"join",
"(",
"(",
"prev",
",",
"value",
")",
")",
"self",
".",
"dict",
"[",
"key",
"]",
"=",
"combined"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/httplib.py#L257-L264 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_simulation.py | python | SimulationDomain.getStopEndingVehiclesNumber | (self) | return self._getUniversal(tc.VAR_STOP_ENDING_VEHICLES_NUMBER) | getStopEndingVehiclesNumber() -> integer
. | getStopEndingVehiclesNumber() -> integer | [
"getStopEndingVehiclesNumber",
"()",
"-",
">",
"integer"
] | def getStopEndingVehiclesNumber(self):
"""getStopEndingVehiclesNumber() -> integer
.
"""
return self._getUniversal(tc.VAR_STOP_ENDING_VEHICLES_NUMBER) | [
"def",
"getStopEndingVehiclesNumber",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_STOP_ENDING_VEHICLES_NUMBER",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_simulation.py#L401-L406 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/poplib.py | python | POP3.capa | (self) | return caps | Return server capabilities (RFC 2449) as a dictionary
>>> c=poplib.POP3('localhost')
>>> c.capa()
{'IMPLEMENTATION': ['Cyrus', 'POP3', 'server', 'v2.2.12'],
'TOP': [], 'LOGIN-DELAY': ['0'], 'AUTH-RESP-CODE': [],
'EXPIRE': ['NEVER'], 'USER': [], 'STLS': [], 'PIPELINING': [],
'UIDL': [], 'RESP-CODES': []}
>>>
Really, according to RFC 2449, the cyrus folks should avoid
having the implementation split into multiple arguments... | Return server capabilities (RFC 2449) as a dictionary
>>> c=poplib.POP3('localhost')
>>> c.capa()
{'IMPLEMENTATION': ['Cyrus', 'POP3', 'server', 'v2.2.12'],
'TOP': [], 'LOGIN-DELAY': ['0'], 'AUTH-RESP-CODE': [],
'EXPIRE': ['NEVER'], 'USER': [], 'STLS': [], 'PIPELINING': [],
'UIDL': [], 'RESP-CODES': []}
>>> | [
"Return",
"server",
"capabilities",
"(",
"RFC",
"2449",
")",
"as",
"a",
"dictionary",
">>>",
"c",
"=",
"poplib",
".",
"POP3",
"(",
"localhost",
")",
">>>",
"c",
".",
"capa",
"()",
"{",
"IMPLEMENTATION",
":",
"[",
"Cyrus",
"POP3",
"server",
"v2",
".",
"2",
".",
"12",
"]",
"TOP",
":",
"[]",
"LOGIN",
"-",
"DELAY",
":",
"[",
"0",
"]",
"AUTH",
"-",
"RESP",
"-",
"CODE",
":",
"[]",
"EXPIRE",
":",
"[",
"NEVER",
"]",
"USER",
":",
"[]",
"STLS",
":",
"[]",
"PIPELINING",
":",
"[]",
"UIDL",
":",
"[]",
"RESP",
"-",
"CODES",
":",
"[]",
"}",
">>>"
] | def capa(self):
"""Return server capabilities (RFC 2449) as a dictionary
>>> c=poplib.POP3('localhost')
>>> c.capa()
{'IMPLEMENTATION': ['Cyrus', 'POP3', 'server', 'v2.2.12'],
'TOP': [], 'LOGIN-DELAY': ['0'], 'AUTH-RESP-CODE': [],
'EXPIRE': ['NEVER'], 'USER': [], 'STLS': [], 'PIPELINING': [],
'UIDL': [], 'RESP-CODES': []}
>>>
Really, according to RFC 2449, the cyrus folks should avoid
having the implementation split into multiple arguments...
"""
def _parsecap(line):
lst = line.decode('ascii').split()
return lst[0], lst[1:]
caps = {}
try:
resp = self._longcmd('CAPA')
rawcaps = resp[1]
for capline in rawcaps:
capnm, capargs = _parsecap(capline)
caps[capnm] = capargs
except error_proto as _err:
raise error_proto('-ERR CAPA not supported by server')
return caps | [
"def",
"capa",
"(",
"self",
")",
":",
"def",
"_parsecap",
"(",
"line",
")",
":",
"lst",
"=",
"line",
".",
"decode",
"(",
"'ascii'",
")",
".",
"split",
"(",
")",
"return",
"lst",
"[",
"0",
"]",
",",
"lst",
"[",
"1",
":",
"]",
"caps",
"=",
"{",
"}",
"try",
":",
"resp",
"=",
"self",
".",
"_longcmd",
"(",
"'CAPA'",
")",
"rawcaps",
"=",
"resp",
"[",
"1",
"]",
"for",
"capline",
"in",
"rawcaps",
":",
"capnm",
",",
"capargs",
"=",
"_parsecap",
"(",
"capline",
")",
"caps",
"[",
"capnm",
"]",
"=",
"capargs",
"except",
"error_proto",
"as",
"_err",
":",
"raise",
"error_proto",
"(",
"'-ERR CAPA not supported by server'",
")",
"return",
"caps"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/poplib.py#L361-L387 | |
borglab/gtsam | a5bee157efce6a0563704bce6a5d188c29817f39 | gtsam/3rdparty/GeographicLib/python/geographiclib/accumulator.py | python | Accumulator.Negate | (self) | Negate sum | Negate sum | [
"Negate",
"sum"
] | def Negate(self):
"""Negate sum"""
self._s *= -1
self._t *= -1 | [
"def",
"Negate",
"(",
"self",
")",
":",
"self",
".",
"_s",
"*=",
"-",
"1",
"self",
".",
"_t",
"*=",
"-",
"1"
] | https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/gtsam/3rdparty/GeographicLib/python/geographiclib/accumulator.py#L79-L82 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix.py | python | PosixEventLoop.call_from_executor | (self, callback, _max_postpone_until=None) | Call this function in the main event loop.
Similar to Twisted's ``callFromThread``.
:param _max_postpone_until: `None` or `time.time` value. For interal
use. If the eventloop is saturated, consider this task to be low
priority and postpone maximum until this timestamp. (For instance,
repaint is done using low priority.) | Call this function in the main event loop.
Similar to Twisted's ``callFromThread``. | [
"Call",
"this",
"function",
"in",
"the",
"main",
"event",
"loop",
".",
"Similar",
"to",
"Twisted",
"s",
"callFromThread",
"."
] | def call_from_executor(self, callback, _max_postpone_until=None):
"""
Call this function in the main event loop.
Similar to Twisted's ``callFromThread``.
:param _max_postpone_until: `None` or `time.time` value. For interal
use. If the eventloop is saturated, consider this task to be low
priority and postpone maximum until this timestamp. (For instance,
repaint is done using low priority.)
"""
assert _max_postpone_until is None or isinstance(_max_postpone_until, float)
self._calls_from_executor.append((callback, _max_postpone_until))
if self._schedule_pipe:
try:
os.write(self._schedule_pipe[1], b'x')
except (AttributeError, IndexError, OSError):
# Handle race condition. We're in a different thread.
# - `_schedule_pipe` could have become None in the meantime.
# - We catch `OSError` (actually BrokenPipeError), because the
# main thread could have closed the pipe already.
pass | [
"def",
"call_from_executor",
"(",
"self",
",",
"callback",
",",
"_max_postpone_until",
"=",
"None",
")",
":",
"assert",
"_max_postpone_until",
"is",
"None",
"or",
"isinstance",
"(",
"_max_postpone_until",
",",
"float",
")",
"self",
".",
"_calls_from_executor",
".",
"append",
"(",
"(",
"callback",
",",
"_max_postpone_until",
")",
")",
"if",
"self",
".",
"_schedule_pipe",
":",
"try",
":",
"os",
".",
"write",
"(",
"self",
".",
"_schedule_pipe",
"[",
"1",
"]",
",",
"b'x'",
")",
"except",
"(",
"AttributeError",
",",
"IndexError",
",",
"OSError",
")",
":",
"# Handle race condition. We're in a different thread.",
"# - `_schedule_pipe` could have become None in the meantime.",
"# - We catch `OSError` (actually BrokenPipeError), because the",
"# main thread could have closed the pipe already.",
"pass"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix.py#L228-L249 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/python_gflags/gflags.py | python | FlagValues.KeyFlagsByModuleDict | (self) | return self.__dict__['__key_flags_by_module'] | Returns the dictionary of module_name -> list of key flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects. | Returns the dictionary of module_name -> list of key flags. | [
"Returns",
"the",
"dictionary",
"of",
"module_name",
"-",
">",
"list",
"of",
"key",
"flags",
"."
] | def KeyFlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of key flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__key_flags_by_module'] | [
"def",
"KeyFlagsByModuleDict",
"(",
"self",
")",
":",
"return",
"self",
".",
"__dict__",
"[",
"'__key_flags_by_module'",
"]"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/python_gflags/gflags.py#L867-L874 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_grad.py | python | _FractionalMaxPoolGrad | (op, grad_0, unused_grad_1, unused_grad_2) | return gen_nn_ops.fractional_max_pool_grad(
op.inputs[0], op.outputs[0], grad_0, op.outputs[1], op.outputs[2],
op.get_attr("overlapping")) | Returns gradient for FractionalMaxPool.
Since FractionalMaxPool has three outputs, there are three gradients passed in
for each of the outputs. Only the first one is useful, the other two gradients
are empty.
Args:
op: The FractionalMaxPoolOp.
grad_0: Gradient with respect to op.outputs[0]
unused_grad_1: Gradient with respect to op.outputs[1]/row_seq. It is empty.
unused_grad_2: Gradient with respect to op.outputs[2]/col_seq. It is empty.
Returns:
Input backprop for FractionalMaxPool op. | Returns gradient for FractionalMaxPool. | [
"Returns",
"gradient",
"for",
"FractionalMaxPool",
"."
] | def _FractionalMaxPoolGrad(op, grad_0, unused_grad_1, unused_grad_2):
"""Returns gradient for FractionalMaxPool.
Since FractionalMaxPool has three outputs, there are three gradients passed in
for each of the outputs. Only the first one is useful, the other two gradients
are empty.
Args:
op: The FractionalMaxPoolOp.
grad_0: Gradient with respect to op.outputs[0]
unused_grad_1: Gradient with respect to op.outputs[1]/row_seq. It is empty.
unused_grad_2: Gradient with respect to op.outputs[2]/col_seq. It is empty.
Returns:
Input backprop for FractionalMaxPool op.
"""
return gen_nn_ops.fractional_max_pool_grad(
op.inputs[0], op.outputs[0], grad_0, op.outputs[1], op.outputs[2],
op.get_attr("overlapping")) | [
"def",
"_FractionalMaxPoolGrad",
"(",
"op",
",",
"grad_0",
",",
"unused_grad_1",
",",
"unused_grad_2",
")",
":",
"return",
"gen_nn_ops",
".",
"fractional_max_pool_grad",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
",",
"op",
".",
"outputs",
"[",
"0",
"]",
",",
"grad_0",
",",
"op",
".",
"outputs",
"[",
"1",
"]",
",",
"op",
".",
"outputs",
"[",
"2",
"]",
",",
"op",
".",
"get_attr",
"(",
"\"overlapping\"",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_grad.py#L770-L788 | |
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | api/ctpx/ctptd.py | python | CtpTd.onErrRtnQuoteInsert | (self, InputQuoteField, RspInfoField) | 报价录入错误回报 | 报价录入错误回报 | [
"报价录入错误回报"
] | def onErrRtnQuoteInsert(self, InputQuoteField, RspInfoField):
"""报价录入错误回报"""
pass | [
"def",
"onErrRtnQuoteInsert",
"(",
"self",
",",
"InputQuoteField",
",",
"RspInfoField",
")",
":",
"pass"
] | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L403-L405 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/redshift/layer1.py | python | RedshiftConnection.revoke_cluster_security_group_ingress | (self,
cluster_security_group_name,
cidrip=None,
ec2_security_group_name=None,
ec2_security_group_owner_id=None) | return self._make_request(
action='RevokeClusterSecurityGroupIngress',
verb='POST',
path='/', params=params) | Revokes an ingress rule in an Amazon Redshift security group
for a previously authorized IP range or Amazon EC2 security
group. To add an ingress rule, see
AuthorizeClusterSecurityGroupIngress. For information about
managing security groups, go to `Amazon Redshift Cluster
Security Groups`_ in the Amazon Redshift Management Guide .
:type cluster_security_group_name: string
:param cluster_security_group_name: The name of the security Group from
which to revoke the ingress rule.
:type cidrip: string
:param cidrip: The IP range for which to revoke access. This range must
be a valid Classless Inter-Domain Routing (CIDR) block of IP
addresses. If `CIDRIP` is specified, `EC2SecurityGroupName` and
`EC2SecurityGroupOwnerId` cannot be provided.
:type ec2_security_group_name: string
:param ec2_security_group_name: The name of the EC2 Security Group
whose access is to be revoked. If `EC2SecurityGroupName` is
specified, `EC2SecurityGroupOwnerId` must also be provided and
`CIDRIP` cannot be provided.
:type ec2_security_group_owner_id: string
:param ec2_security_group_owner_id: The AWS account number of the owner
of the security group specified in the `EC2SecurityGroupName`
parameter. The AWS access key ID is not an acceptable value. If
`EC2SecurityGroupOwnerId` is specified, `EC2SecurityGroupName` must
also be provided. and `CIDRIP` cannot be provided.
Example: `111122223333` | Revokes an ingress rule in an Amazon Redshift security group
for a previously authorized IP range or Amazon EC2 security
group. To add an ingress rule, see
AuthorizeClusterSecurityGroupIngress. For information about
managing security groups, go to `Amazon Redshift Cluster
Security Groups`_ in the Amazon Redshift Management Guide . | [
"Revokes",
"an",
"ingress",
"rule",
"in",
"an",
"Amazon",
"Redshift",
"security",
"group",
"for",
"a",
"previously",
"authorized",
"IP",
"range",
"or",
"Amazon",
"EC2",
"security",
"group",
".",
"To",
"add",
"an",
"ingress",
"rule",
"see",
"AuthorizeClusterSecurityGroupIngress",
".",
"For",
"information",
"about",
"managing",
"security",
"groups",
"go",
"to",
"Amazon",
"Redshift",
"Cluster",
"Security",
"Groups",
"_",
"in",
"the",
"Amazon",
"Redshift",
"Management",
"Guide",
"."
] | def revoke_cluster_security_group_ingress(self,
cluster_security_group_name,
cidrip=None,
ec2_security_group_name=None,
ec2_security_group_owner_id=None):
"""
Revokes an ingress rule in an Amazon Redshift security group
for a previously authorized IP range or Amazon EC2 security
group. To add an ingress rule, see
AuthorizeClusterSecurityGroupIngress. For information about
managing security groups, go to `Amazon Redshift Cluster
Security Groups`_ in the Amazon Redshift Management Guide .
:type cluster_security_group_name: string
:param cluster_security_group_name: The name of the security Group from
which to revoke the ingress rule.
:type cidrip: string
:param cidrip: The IP range for which to revoke access. This range must
be a valid Classless Inter-Domain Routing (CIDR) block of IP
addresses. If `CIDRIP` is specified, `EC2SecurityGroupName` and
`EC2SecurityGroupOwnerId` cannot be provided.
:type ec2_security_group_name: string
:param ec2_security_group_name: The name of the EC2 Security Group
whose access is to be revoked. If `EC2SecurityGroupName` is
specified, `EC2SecurityGroupOwnerId` must also be provided and
`CIDRIP` cannot be provided.
:type ec2_security_group_owner_id: string
:param ec2_security_group_owner_id: The AWS account number of the owner
of the security group specified in the `EC2SecurityGroupName`
parameter. The AWS access key ID is not an acceptable value. If
`EC2SecurityGroupOwnerId` is specified, `EC2SecurityGroupName` must
also be provided. and `CIDRIP` cannot be provided.
Example: `111122223333`
"""
params = {
'ClusterSecurityGroupName': cluster_security_group_name,
}
if cidrip is not None:
params['CIDRIP'] = cidrip
if ec2_security_group_name is not None:
params['EC2SecurityGroupName'] = ec2_security_group_name
if ec2_security_group_owner_id is not None:
params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id
return self._make_request(
action='RevokeClusterSecurityGroupIngress',
verb='POST',
path='/', params=params) | [
"def",
"revoke_cluster_security_group_ingress",
"(",
"self",
",",
"cluster_security_group_name",
",",
"cidrip",
"=",
"None",
",",
"ec2_security_group_name",
"=",
"None",
",",
"ec2_security_group_owner_id",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'ClusterSecurityGroupName'",
":",
"cluster_security_group_name",
",",
"}",
"if",
"cidrip",
"is",
"not",
"None",
":",
"params",
"[",
"'CIDRIP'",
"]",
"=",
"cidrip",
"if",
"ec2_security_group_name",
"is",
"not",
"None",
":",
"params",
"[",
"'EC2SecurityGroupName'",
"]",
"=",
"ec2_security_group_name",
"if",
"ec2_security_group_owner_id",
"is",
"not",
"None",
":",
"params",
"[",
"'EC2SecurityGroupOwnerId'",
"]",
"=",
"ec2_security_group_owner_id",
"return",
"self",
".",
"_make_request",
"(",
"action",
"=",
"'RevokeClusterSecurityGroupIngress'",
",",
"verb",
"=",
"'POST'",
",",
"path",
"=",
"'/'",
",",
"params",
"=",
"params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/redshift/layer1.py#L2977-L3027 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/contact.py | python | contact_map | (contacts,fixed=None) | return paircontacts | Given an unordered list of ContactPoints, computes a canonical dict
from (obj1,obj2) pairs to a list of contacts on those objects.
The resulting dict is also regularized so that objects are sorted in
increasing getID(), so that (obj1,obj2) is not duplicated as (obj2,obj1).
If fixed is provided, all objects for which fixed(x) returns true will be
set to None. The most common example, which fixes terrains, is::
lambda x: x is None or isinstance(x,TerrainModel) | Given an unordered list of ContactPoints, computes a canonical dict
from (obj1,obj2) pairs to a list of contacts on those objects.
The resulting dict is also regularized so that objects are sorted in
increasing getID(), so that (obj1,obj2) is not duplicated as (obj2,obj1).
If fixed is provided, all objects for which fixed(x) returns true will be
set to None. The most common example, which fixes terrains, is::
lambda x: x is None or isinstance(x,TerrainModel) | [
"Given",
"an",
"unordered",
"list",
"of",
"ContactPoints",
"computes",
"a",
"canonical",
"dict",
"from",
"(",
"obj1",
"obj2",
")",
"pairs",
"to",
"a",
"list",
"of",
"contacts",
"on",
"those",
"objects",
".",
"The",
"resulting",
"dict",
"is",
"also",
"regularized",
"so",
"that",
"objects",
"are",
"sorted",
"in",
"increasing",
"getID",
"()",
"so",
"that",
"(",
"obj1",
"obj2",
")",
"is",
"not",
"duplicated",
"as",
"(",
"obj2",
"obj1",
")",
".",
"If",
"fixed",
"is",
"provided",
"all",
"objects",
"for",
"which",
"fixed",
"(",
"x",
")",
"returns",
"true",
"will",
"be",
"set",
"to",
"None",
".",
"The",
"most",
"common",
"example",
"which",
"fixes",
"terrains",
"is",
"::",
"lambda",
"x",
":",
"x",
"is",
"None",
"or",
"isinstance",
"(",
"x",
"TerrainModel",
")"
] | def contact_map(contacts,fixed=None):
"""Given an unordered list of ContactPoints, computes a canonical dict
from (obj1,obj2) pairs to a list of contacts on those objects.
The resulting dict is also regularized so that objects are sorted in
increasing getID(), so that (obj1,obj2) is not duplicated as (obj2,obj1).
If fixed is provided, all objects for which fixed(x) returns true will be
set to None. The most common example, which fixes terrains, is::
lambda x: x is None or isinstance(x,TerrainModel)
"""
worlds = set()
robots = set()
objects = set()
#check which worlds, robots, and objects are used
for c in contacts:
assert(c.object1.world == c.object2.world),"Contacts need to be in the same world"
worlds.insert(c.object1.world)
assert(len(worlds)<=1),"Only one world is supported"
if len(worlds)==0: return dict()
for c in contacts:
if hasattr(c.object1,'robot'):
assert(hasattr(c.object1,'robotIndex')),"Contact pairs must be RobotModelLink's"
robots.insert(c.object1.robot)
elif hasattr(c.object1,'object'):
objects.insert(c.object1.object)
if hasattr(c.object2,'robot'):
assert(hasattr(c.object2,'robotIndex')),"Contact pairs must be RobotModelLink's"
robots.insert(c.object2.robot)
elif hasattr(c.object2,'object'):
objects.insert(c.object2.object)
#first sort out all the collision pairs
paircontacts = dict()
for c in contacts:
reflect = False
#treat all non RigidObjectModel or RobotModelLink objects as fixed
o1 = c.object1 if not fixed(c.object1) else None
o2 = c.object2 if not fixed(c.object2) else None
if hasattr(o1,'getID'):
if hasattr(o2,'getID'):
if o2.getID() < o1.getID():
reflect=True
elif o2.getID() == o1.getID():
raise RuntimeError("Contacts specified on object to itself")
elif hasattr(o2,'getID'):
reflect = True
if o1 == o2:
raise RuntimeError("Contact specified between an object and itself")
if reflect:
paircontacts.getdefault((o2,o1),[]).append(c.reflect())
else:
paircontacts.getdefault((o1,o2),[]).append(c)
return paircontacts | [
"def",
"contact_map",
"(",
"contacts",
",",
"fixed",
"=",
"None",
")",
":",
"worlds",
"=",
"set",
"(",
")",
"robots",
"=",
"set",
"(",
")",
"objects",
"=",
"set",
"(",
")",
"#check which worlds, robots, and objects are used",
"for",
"c",
"in",
"contacts",
":",
"assert",
"(",
"c",
".",
"object1",
".",
"world",
"==",
"c",
".",
"object2",
".",
"world",
")",
",",
"\"Contacts need to be in the same world\"",
"worlds",
".",
"insert",
"(",
"c",
".",
"object1",
".",
"world",
")",
"assert",
"(",
"len",
"(",
"worlds",
")",
"<=",
"1",
")",
",",
"\"Only one world is supported\"",
"if",
"len",
"(",
"worlds",
")",
"==",
"0",
":",
"return",
"dict",
"(",
")",
"for",
"c",
"in",
"contacts",
":",
"if",
"hasattr",
"(",
"c",
".",
"object1",
",",
"'robot'",
")",
":",
"assert",
"(",
"hasattr",
"(",
"c",
".",
"object1",
",",
"'robotIndex'",
")",
")",
",",
"\"Contact pairs must be RobotModelLink's\"",
"robots",
".",
"insert",
"(",
"c",
".",
"object1",
".",
"robot",
")",
"elif",
"hasattr",
"(",
"c",
".",
"object1",
",",
"'object'",
")",
":",
"objects",
".",
"insert",
"(",
"c",
".",
"object1",
".",
"object",
")",
"if",
"hasattr",
"(",
"c",
".",
"object2",
",",
"'robot'",
")",
":",
"assert",
"(",
"hasattr",
"(",
"c",
".",
"object2",
",",
"'robotIndex'",
")",
")",
",",
"\"Contact pairs must be RobotModelLink's\"",
"robots",
".",
"insert",
"(",
"c",
".",
"object2",
".",
"robot",
")",
"elif",
"hasattr",
"(",
"c",
".",
"object2",
",",
"'object'",
")",
":",
"objects",
".",
"insert",
"(",
"c",
".",
"object2",
".",
"object",
")",
"#first sort out all the collision pairs",
"paircontacts",
"=",
"dict",
"(",
")",
"for",
"c",
"in",
"contacts",
":",
"reflect",
"=",
"False",
"#treat all non RigidObjectModel or RobotModelLink objects as fixed",
"o1",
"=",
"c",
".",
"object1",
"if",
"not",
"fixed",
"(",
"c",
".",
"object1",
")",
"else",
"None",
"o2",
"=",
"c",
".",
"object2",
"if",
"not",
"fixed",
"(",
"c",
".",
"object2",
")",
"else",
"None",
"if",
"hasattr",
"(",
"o1",
",",
"'getID'",
")",
":",
"if",
"hasattr",
"(",
"o2",
",",
"'getID'",
")",
":",
"if",
"o2",
".",
"getID",
"(",
")",
"<",
"o1",
".",
"getID",
"(",
")",
":",
"reflect",
"=",
"True",
"elif",
"o2",
".",
"getID",
"(",
")",
"==",
"o1",
".",
"getID",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Contacts specified on object to itself\"",
")",
"elif",
"hasattr",
"(",
"o2",
",",
"'getID'",
")",
":",
"reflect",
"=",
"True",
"if",
"o1",
"==",
"o2",
":",
"raise",
"RuntimeError",
"(",
"\"Contact specified between an object and itself\"",
")",
"if",
"reflect",
":",
"paircontacts",
".",
"getdefault",
"(",
"(",
"o2",
",",
"o1",
")",
",",
"[",
"]",
")",
".",
"append",
"(",
"c",
".",
"reflect",
"(",
")",
")",
"else",
":",
"paircontacts",
".",
"getdefault",
"(",
"(",
"o1",
",",
"o2",
")",
",",
"[",
"]",
")",
".",
"append",
"(",
"c",
")",
"return",
"paircontacts"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/contact.py#L222-L279 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/NTableWidget.py | python | NTableWidget.__init__ | (self, parent) | return | :param parent:
:return: | [] | def __init__(self, parent):
"""
:param parent:
:return:
"""
QTableWidget.__init__(self, parent)
self._myParent = parent
self._myColumnNameList = None
self._myColumnTypeList = None
self._editableList = list()
self._statusColName = 'Status'
self._colIndexSelect = None
return | [
"def",
"__init__",
"(",
"self",
",",
"parent",
")",
":",
"QTableWidget",
".",
"__init__",
"(",
"self",
",",
"parent",
")",
"self",
".",
"_myParent",
"=",
"parent",
"self",
".",
"_myColumnNameList",
"=",
"None",
"self",
".",
"_myColumnTypeList",
"=",
"None",
"self",
".",
"_editableList",
"=",
"list",
"(",
")",
"self",
".",
"_statusColName",
"=",
"'Status'",
"self",
".",
"_colIndexSelect",
"=",
"None",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/NTableWidget.py#L28-L45 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py | python | streaming_mean_iou | (predictions,
labels,
num_classes,
ignore_mask=None,
metrics_collections=None,
updates_collections=None,
name=None) | Calculate per-step mean Intersection-Over-Union (mIOU).
Mean Intersection-Over-Union is a common evaluation metric for
semantic image segmentation, which first computes the IOU for each
semantic class and then computes the average over classes.
IOU is defined as follows:
IOU = true_positive / (true_positive + false_positive + false_negative).
The predictions are accumulated in a confusion matrix, and mIOU is then
calculated from it.
Args:
predictions: A tensor of prediction results for semantic labels, whose
shape is [batch size] and type `int32` or `int64`. The tensor will be
flattened, if its rank > 1.
labels: A tensor of ground truth labels with shape [batch size] and of
type `int32` or `int64`. The tensor will be flattened, if its rank > 1.
num_classes: The possible number of labels the prediction task can
have. This value must be provided, since a confusion matrix of
dimension = [num_classes, num_classes] will be allocated.
ignore_mask: An optional, boolean tensor whose size matches `labels`. If an
element of `ignore_mask` is True, the corresponding prediction and label
pair is NOT used to compute the metrics. Otherwise, the pair is included.
metrics_collections: An optional list of collections that `mean_iou`
should be added to.
updates_collections: An optional list of collections `update_op` should be
added to.
name: An optional variable_op_scope name.
Returns:
mean_iou: A tensor representing the mean intersection-over-union.
update_op: An operation that increments the confusion matrix.
Raises:
ValueError: If the dimensions of `predictions` and `labels` don't match or
if `ignore_mask` is not `None` and its shape doesn't match `labels`
or if either `metrics_collections` or `updates_collections` are not a list
or tuple. | Calculate per-step mean Intersection-Over-Union (mIOU). | [
"Calculate",
"per",
"-",
"step",
"mean",
"Intersection",
"-",
"Over",
"-",
"Union",
"(",
"mIOU",
")",
"."
] | def streaming_mean_iou(predictions,
labels,
num_classes,
ignore_mask=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Calculate per-step mean Intersection-Over-Union (mIOU).
Mean Intersection-Over-Union is a common evaluation metric for
semantic image segmentation, which first computes the IOU for each
semantic class and then computes the average over classes.
IOU is defined as follows:
IOU = true_positive / (true_positive + false_positive + false_negative).
The predictions are accumulated in a confusion matrix, and mIOU is then
calculated from it.
Args:
predictions: A tensor of prediction results for semantic labels, whose
shape is [batch size] and type `int32` or `int64`. The tensor will be
flattened, if its rank > 1.
labels: A tensor of ground truth labels with shape [batch size] and of
type `int32` or `int64`. The tensor will be flattened, if its rank > 1.
num_classes: The possible number of labels the prediction task can
have. This value must be provided, since a confusion matrix of
dimension = [num_classes, num_classes] will be allocated.
ignore_mask: An optional, boolean tensor whose size matches `labels`. If an
element of `ignore_mask` is True, the corresponding prediction and label
pair is NOT used to compute the metrics. Otherwise, the pair is included.
metrics_collections: An optional list of collections that `mean_iou`
should be added to.
updates_collections: An optional list of collections `update_op` should be
added to.
name: An optional variable_op_scope name.
Returns:
mean_iou: A tensor representing the mean intersection-over-union.
update_op: An operation that increments the confusion matrix.
Raises:
ValueError: If the dimensions of `predictions` and `labels` don't match or
if `ignore_mask` is not `None` and its shape doesn't match `labels`
or if either `metrics_collections` or `updates_collections` are not a list
or tuple.
"""
with variable_scope.variable_op_scope(
[predictions, labels], name, 'mean_iou'):
# Check if shape is compatible.
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
if ignore_mask is not None:
labels.get_shape().assert_is_compatible_with(ignore_mask.get_shape())
# Local variable to accumulate the predictions in the confusion matrix.
total_cm = _create_local('total_confusion_matrix',
shape=[num_classes, num_classes],
dtype=dtypes.int64)
# Cast the type to int64 required by confusion_matrix_ops.
predictions = math_ops.to_int64(predictions)
labels = math_ops.to_int64(labels)
num_classes = math_ops.to_int64(num_classes)
# Flatten the input if its rank > 1.
predictions_rank = predictions.get_shape().ndims
if predictions_rank > 1:
predictions = array_ops.reshape(predictions, [-1])
labels_rank = labels.get_shape().ndims
if labels_rank > 1:
labels = array_ops.reshape(labels, [-1])
if ignore_mask is not None:
ignore_mask_rank = ignore_mask.get_shape().ndims
if ignore_mask_rank > 1:
ignore_mask = array_ops.reshape(ignore_mask, [-1])
check_ops.assert_type(ignore_mask, dtypes.bool)
not_ignore_mask = math_ops.logical_not(ignore_mask)
predictions = array_ops.boolean_mask(predictions, not_ignore_mask)
labels = array_ops.boolean_mask(labels, not_ignore_mask)
# Accumulate the prediction to current confusion matrix.
current_cm = confusion_matrix_ops.confusion_matrix(
predictions, labels, num_classes, dtype=dtypes.int64)
update_op = state_ops.assign_add(total_cm, current_cm)
def compute_mean_iou(name):
"""Compute the mean intersection-over-union via the confusion matrix."""
sum_over_row = math_ops.to_float(math_ops.reduce_sum(total_cm, 0))
sum_over_col = math_ops.to_float(math_ops.reduce_sum(total_cm, 1))
cm_diag = math_ops.to_float(array_ops.diag_part(total_cm))
denominator = sum_over_row + sum_over_col - cm_diag
# If the value of the denominator is 0, set it to 1 to avoid
# zero division.
denominator = math_ops.select(
math_ops.greater(denominator, 0),
denominator,
array_ops.ones_like(denominator))
iou = math_ops.div(cm_diag, denominator)
return math_ops.reduce_mean(iou, name=name)
mean_iou = compute_mean_iou('mean_iou')
if metrics_collections:
ops.add_to_collections(metrics_collections, mean_iou)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return mean_iou, update_op | [
"def",
"streaming_mean_iou",
"(",
"predictions",
",",
"labels",
",",
"num_classes",
",",
"ignore_mask",
"=",
"None",
",",
"metrics_collections",
"=",
"None",
",",
"updates_collections",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"variable_scope",
".",
"variable_op_scope",
"(",
"[",
"predictions",
",",
"labels",
"]",
",",
"name",
",",
"'mean_iou'",
")",
":",
"# Check if shape is compatible.",
"predictions",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"labels",
".",
"get_shape",
"(",
")",
")",
"if",
"ignore_mask",
"is",
"not",
"None",
":",
"labels",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"ignore_mask",
".",
"get_shape",
"(",
")",
")",
"# Local variable to accumulate the predictions in the confusion matrix.",
"total_cm",
"=",
"_create_local",
"(",
"'total_confusion_matrix'",
",",
"shape",
"=",
"[",
"num_classes",
",",
"num_classes",
"]",
",",
"dtype",
"=",
"dtypes",
".",
"int64",
")",
"# Cast the type to int64 required by confusion_matrix_ops.",
"predictions",
"=",
"math_ops",
".",
"to_int64",
"(",
"predictions",
")",
"labels",
"=",
"math_ops",
".",
"to_int64",
"(",
"labels",
")",
"num_classes",
"=",
"math_ops",
".",
"to_int64",
"(",
"num_classes",
")",
"# Flatten the input if its rank > 1.",
"predictions_rank",
"=",
"predictions",
".",
"get_shape",
"(",
")",
".",
"ndims",
"if",
"predictions_rank",
">",
"1",
":",
"predictions",
"=",
"array_ops",
".",
"reshape",
"(",
"predictions",
",",
"[",
"-",
"1",
"]",
")",
"labels_rank",
"=",
"labels",
".",
"get_shape",
"(",
")",
".",
"ndims",
"if",
"labels_rank",
">",
"1",
":",
"labels",
"=",
"array_ops",
".",
"reshape",
"(",
"labels",
",",
"[",
"-",
"1",
"]",
")",
"if",
"ignore_mask",
"is",
"not",
"None",
":",
"ignore_mask_rank",
"=",
"ignore_mask",
".",
"get_shape",
"(",
")",
".",
"ndims",
"if",
"ignore_mask_rank",
">",
"1",
":",
"ignore_mask",
"=",
"array_ops",
".",
"reshape",
"(",
"ignore_mask",
",",
"[",
"-",
"1",
"]",
")",
"check_ops",
".",
"assert_type",
"(",
"ignore_mask",
",",
"dtypes",
".",
"bool",
")",
"not_ignore_mask",
"=",
"math_ops",
".",
"logical_not",
"(",
"ignore_mask",
")",
"predictions",
"=",
"array_ops",
".",
"boolean_mask",
"(",
"predictions",
",",
"not_ignore_mask",
")",
"labels",
"=",
"array_ops",
".",
"boolean_mask",
"(",
"labels",
",",
"not_ignore_mask",
")",
"# Accumulate the prediction to current confusion matrix.",
"current_cm",
"=",
"confusion_matrix_ops",
".",
"confusion_matrix",
"(",
"predictions",
",",
"labels",
",",
"num_classes",
",",
"dtype",
"=",
"dtypes",
".",
"int64",
")",
"update_op",
"=",
"state_ops",
".",
"assign_add",
"(",
"total_cm",
",",
"current_cm",
")",
"def",
"compute_mean_iou",
"(",
"name",
")",
":",
"\"\"\"Compute the mean intersection-over-union via the confusion matrix.\"\"\"",
"sum_over_row",
"=",
"math_ops",
".",
"to_float",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"total_cm",
",",
"0",
")",
")",
"sum_over_col",
"=",
"math_ops",
".",
"to_float",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"total_cm",
",",
"1",
")",
")",
"cm_diag",
"=",
"math_ops",
".",
"to_float",
"(",
"array_ops",
".",
"diag_part",
"(",
"total_cm",
")",
")",
"denominator",
"=",
"sum_over_row",
"+",
"sum_over_col",
"-",
"cm_diag",
"# If the value of the denominator is 0, set it to 1 to avoid",
"# zero division.",
"denominator",
"=",
"math_ops",
".",
"select",
"(",
"math_ops",
".",
"greater",
"(",
"denominator",
",",
"0",
")",
",",
"denominator",
",",
"array_ops",
".",
"ones_like",
"(",
"denominator",
")",
")",
"iou",
"=",
"math_ops",
".",
"div",
"(",
"cm_diag",
",",
"denominator",
")",
"return",
"math_ops",
".",
"reduce_mean",
"(",
"iou",
",",
"name",
"=",
"name",
")",
"mean_iou",
"=",
"compute_mean_iou",
"(",
"'mean_iou'",
")",
"if",
"metrics_collections",
":",
"ops",
".",
"add_to_collections",
"(",
"metrics_collections",
",",
"mean_iou",
")",
"if",
"updates_collections",
":",
"ops",
".",
"add_to_collections",
"(",
"updates_collections",
",",
"update_op",
")",
"return",
"mean_iou",
",",
"update_op"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py#L1750-L1860 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/docbook/__init__.py | python | DocbookXslt | (env, target, source=None, *args, **kw) | return result | A pseudo-Builder, applying a simple XSL transformation to the input file. | A pseudo-Builder, applying a simple XSL transformation to the input file. | [
"A",
"pseudo",
"-",
"Builder",
"applying",
"a",
"simple",
"XSL",
"transformation",
"to",
"the",
"input",
"file",
"."
] | def DocbookXslt(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, applying a simple XSL transformation to the input file.
"""
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
kw['DOCBOOK_XSL'] = kw.get('xsl', 'transform.xsl')
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
r = __builder.__call__(env, t, s, **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
return result | [
"def",
"DocbookXslt",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"target",
",",
"source",
"=",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
"# Init XSL stylesheet",
"kw",
"[",
"'DOCBOOK_XSL'",
"]",
"=",
"kw",
".",
"get",
"(",
"'xsl'",
",",
"'transform.xsl'",
")",
"# Setup builder",
"__builder",
"=",
"__select_builder",
"(",
"__lxml_builder",
",",
"__libxml2_builder",
",",
"__xsltproc_builder",
")",
"# Create targets",
"result",
"=",
"[",
"]",
"for",
"t",
",",
"s",
"in",
"zip",
"(",
"target",
",",
"source",
")",
":",
"r",
"=",
"__builder",
".",
"__call__",
"(",
"env",
",",
"t",
",",
"s",
",",
"*",
"*",
"kw",
")",
"env",
".",
"Depends",
"(",
"r",
",",
"kw",
"[",
"'DOCBOOK_XSL'",
"]",
")",
"result",
".",
"extend",
"(",
"r",
")",
"return",
"result"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/docbook/__init__.py#L794-L814 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/feature_extraction/image.py | python | grid_to_graph | (n_x, n_y, n_z=1, mask=None, return_as=sparse.coo_matrix,
dtype=np.int) | return _to_graph(n_x, n_y, n_z, mask=mask, return_as=return_as,
dtype=dtype) | Graph of the pixel-to-pixel connections
Edges exist if 2 voxels are connected.
Parameters
----------
n_x : int
Dimension in x axis
n_y : int
Dimension in y axis
n_z : int, optional, default 1
Dimension in z axis
mask : ndarray of booleans, optional
An optional mask of the image, to consider only part of the
pixels.
return_as : np.ndarray or a sparse matrix class, optional
The class to use to build the returned adjacency matrix.
dtype : dtype, optional, default int
The data of the returned sparse matrix. By default it is int
Notes
-----
For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was
handled by returning a dense np.matrix instance. Going forward, np.ndarray
returns an np.ndarray, as expected.
For compatibility, user code relying on this method should wrap its
calls in ``np.asarray`` to avoid type issues. | Graph of the pixel-to-pixel connections | [
"Graph",
"of",
"the",
"pixel",
"-",
"to",
"-",
"pixel",
"connections"
] | def grid_to_graph(n_x, n_y, n_z=1, mask=None, return_as=sparse.coo_matrix,
dtype=np.int):
"""Graph of the pixel-to-pixel connections
Edges exist if 2 voxels are connected.
Parameters
----------
n_x : int
Dimension in x axis
n_y : int
Dimension in y axis
n_z : int, optional, default 1
Dimension in z axis
mask : ndarray of booleans, optional
An optional mask of the image, to consider only part of the
pixels.
return_as : np.ndarray or a sparse matrix class, optional
The class to use to build the returned adjacency matrix.
dtype : dtype, optional, default int
The data of the returned sparse matrix. By default it is int
Notes
-----
For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was
handled by returning a dense np.matrix instance. Going forward, np.ndarray
returns an np.ndarray, as expected.
For compatibility, user code relying on this method should wrap its
calls in ``np.asarray`` to avoid type issues.
"""
return _to_graph(n_x, n_y, n_z, mask=mask, return_as=return_as,
dtype=dtype) | [
"def",
"grid_to_graph",
"(",
"n_x",
",",
"n_y",
",",
"n_z",
"=",
"1",
",",
"mask",
"=",
"None",
",",
"return_as",
"=",
"sparse",
".",
"coo_matrix",
",",
"dtype",
"=",
"np",
".",
"int",
")",
":",
"return",
"_to_graph",
"(",
"n_x",
",",
"n_y",
",",
"n_z",
",",
"mask",
"=",
"mask",
",",
"return_as",
"=",
"return_as",
",",
"dtype",
"=",
"dtype",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_extraction/image.py#L166-L198 | |
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | libs/EXTERNAL/libcatch2/.conan/build.py | python | BuilderSettings._branch | (self) | return ci_manager.get_branch() | Get branch name from CI manager | Get branch name from CI manager | [
"Get",
"branch",
"name",
"from",
"CI",
"manager"
] | def _branch(self):
""" Get branch name from CI manager
"""
printer = Printer(None)
ci_manager = CIManager(printer)
return ci_manager.get_branch() | [
"def",
"_branch",
"(",
"self",
")",
":",
"printer",
"=",
"Printer",
"(",
"None",
")",
"ci_manager",
"=",
"CIManager",
"(",
"printer",
")",
"return",
"ci_manager",
".",
"get_branch",
"(",
")"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/libs/EXTERNAL/libcatch2/.conan/build.py#L74-L79 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/npyimpl.py | python | _ufunc_db_function | (ufunc) | return _KernelImpl | Use the ufunc loop type information to select the code generation
function from the table provided by the dict_of_kernels. The dict
of kernels maps the loop identifier to a function with the
following signature: (context, builder, signature, args).
The loop type information has the form 'AB->C'. The letters to the
left of '->' are the input types (specified as NumPy letter
types). The letters to the right of '->' are the output
types. There must be 'ufunc.nin' letters to the left of '->', and
'ufunc.nout' letters to the right.
For example, a binary float loop resulting in a float, will have
the following signature: 'ff->f'.
A given ufunc implements many loops. The list of loops implemented
for a given ufunc can be accessed using the 'types' attribute in
the ufunc object. The NumPy machinery selects the first loop that
fits a given calling signature (in our case, what we call the
outer_sig). This logic is mimicked by 'ufunc_find_matching_loop'. | Use the ufunc loop type information to select the code generation
function from the table provided by the dict_of_kernels. The dict
of kernels maps the loop identifier to a function with the
following signature: (context, builder, signature, args). | [
"Use",
"the",
"ufunc",
"loop",
"type",
"information",
"to",
"select",
"the",
"code",
"generation",
"function",
"from",
"the",
"table",
"provided",
"by",
"the",
"dict_of_kernels",
".",
"The",
"dict",
"of",
"kernels",
"maps",
"the",
"loop",
"identifier",
"to",
"a",
"function",
"with",
"the",
"following",
"signature",
":",
"(",
"context",
"builder",
"signature",
"args",
")",
"."
] | def _ufunc_db_function(ufunc):
"""Use the ufunc loop type information to select the code generation
function from the table provided by the dict_of_kernels. The dict
of kernels maps the loop identifier to a function with the
following signature: (context, builder, signature, args).
The loop type information has the form 'AB->C'. The letters to the
left of '->' are the input types (specified as NumPy letter
types). The letters to the right of '->' are the output
types. There must be 'ufunc.nin' letters to the left of '->', and
'ufunc.nout' letters to the right.
For example, a binary float loop resulting in a float, will have
the following signature: 'ff->f'.
A given ufunc implements many loops. The list of loops implemented
for a given ufunc can be accessed using the 'types' attribute in
the ufunc object. The NumPy machinery selects the first loop that
fits a given calling signature (in our case, what we call the
outer_sig). This logic is mimicked by 'ufunc_find_matching_loop'.
"""
class _KernelImpl(_Kernel):
def __init__(self, context, builder, outer_sig):
super(_KernelImpl, self).__init__(context, builder, outer_sig)
loop = ufunc_find_matching_loop(
ufunc, outer_sig.args + (outer_sig.return_type,))
self.fn = ufunc_db.get_ufunc_info(ufunc).get(loop.ufunc_sig)
self.inner_sig = typing.signature(
*(loop.outputs + loop.inputs))
if self.fn is None:
msg = "Don't know how to lower ufunc '{0}' for loop '{1}'"
raise NotImplementedError(msg.format(ufunc.__name__, loop))
def generate(self, *args):
isig = self.inner_sig
osig = self.outer_sig
cast_args = [self.cast(val, inty, outty)
for val, inty, outty in zip(args, osig.args,
isig.args)]
with force_error_model(self.context, 'numpy'):
res = self.fn(self.context, self.builder, isig, cast_args)
dmm = self.context.data_model_manager
res = dmm[isig.return_type].from_return(self.builder, res)
return self.cast(res, isig.return_type, osig.return_type)
return _KernelImpl | [
"def",
"_ufunc_db_function",
"(",
"ufunc",
")",
":",
"class",
"_KernelImpl",
"(",
"_Kernel",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"context",
",",
"builder",
",",
"outer_sig",
")",
":",
"super",
"(",
"_KernelImpl",
",",
"self",
")",
".",
"__init__",
"(",
"context",
",",
"builder",
",",
"outer_sig",
")",
"loop",
"=",
"ufunc_find_matching_loop",
"(",
"ufunc",
",",
"outer_sig",
".",
"args",
"+",
"(",
"outer_sig",
".",
"return_type",
",",
")",
")",
"self",
".",
"fn",
"=",
"ufunc_db",
".",
"get_ufunc_info",
"(",
"ufunc",
")",
".",
"get",
"(",
"loop",
".",
"ufunc_sig",
")",
"self",
".",
"inner_sig",
"=",
"typing",
".",
"signature",
"(",
"*",
"(",
"loop",
".",
"outputs",
"+",
"loop",
".",
"inputs",
")",
")",
"if",
"self",
".",
"fn",
"is",
"None",
":",
"msg",
"=",
"\"Don't know how to lower ufunc '{0}' for loop '{1}'\"",
"raise",
"NotImplementedError",
"(",
"msg",
".",
"format",
"(",
"ufunc",
".",
"__name__",
",",
"loop",
")",
")",
"def",
"generate",
"(",
"self",
",",
"*",
"args",
")",
":",
"isig",
"=",
"self",
".",
"inner_sig",
"osig",
"=",
"self",
".",
"outer_sig",
"cast_args",
"=",
"[",
"self",
".",
"cast",
"(",
"val",
",",
"inty",
",",
"outty",
")",
"for",
"val",
",",
"inty",
",",
"outty",
"in",
"zip",
"(",
"args",
",",
"osig",
".",
"args",
",",
"isig",
".",
"args",
")",
"]",
"with",
"force_error_model",
"(",
"self",
".",
"context",
",",
"'numpy'",
")",
":",
"res",
"=",
"self",
".",
"fn",
"(",
"self",
".",
"context",
",",
"self",
".",
"builder",
",",
"isig",
",",
"cast_args",
")",
"dmm",
"=",
"self",
".",
"context",
".",
"data_model_manager",
"res",
"=",
"dmm",
"[",
"isig",
".",
"return_type",
"]",
".",
"from_return",
"(",
"self",
".",
"builder",
",",
"res",
")",
"return",
"self",
".",
"cast",
"(",
"res",
",",
"isig",
".",
"return_type",
",",
"osig",
".",
"return_type",
")",
"return",
"_KernelImpl"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/npyimpl.py#L389-L437 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/egg_info.py | python | FileList.recursive_exclude | (self, dir, pattern) | return self._remove_files(match.match) | Exclude any file anywhere in 'dir/' that match the pattern. | Exclude any file anywhere in 'dir/' that match the pattern. | [
"Exclude",
"any",
"file",
"anywhere",
"in",
"dir",
"/",
"that",
"match",
"the",
"pattern",
"."
] | def recursive_exclude(self, dir, pattern):
"""
Exclude any file anywhere in 'dir/' that match the pattern.
"""
match = translate_pattern(os.path.join(dir, '**', pattern))
return self._remove_files(match.match) | [
"def",
"recursive_exclude",
"(",
"self",
",",
"dir",
",",
"pattern",
")",
":",
"match",
"=",
"translate_pattern",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"'**'",
",",
"pattern",
")",
")",
"return",
"self",
".",
"_remove_files",
"(",
"match",
".",
"match",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/egg_info.py#L433-L438 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/os.py | python | execlp | (file, *args) | execlp(file, *args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process. | execlp(file, *args) | [
"execlp",
"(",
"file",
"*",
"args",
")"
] | def execlp(file, *args):
"""execlp(file, *args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process. """
execvp(file, args) | [
"def",
"execlp",
"(",
"file",
",",
"*",
"args",
")",
":",
"execvp",
"(",
"file",
",",
"args",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/os.py#L552-L557 | ||
infinit/elle | a8154593c42743f45b9df09daf62b44630c24a02 | drake/src/drake/ocaml/menhir.py | python | Menhir.source | (self) | return self.__source | The menhir source file. | The menhir source file. | [
"The",
"menhir",
"source",
"file",
"."
] | def source(self):
'''The menhir source file.'''
return self.__source | [
"def",
"source",
"(",
"self",
")",
":",
"return",
"self",
".",
"__source"
] | https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/ocaml/menhir.py#L48-L50 | |
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/MSVSNew.py | python | MSVSSolution.__init__ | (self, path, version, entries=None, variants=None,
websiteProperties=True) | Initializes the solution.
Args:
path: Path to solution file.
version: Format version to emit.
entries: List of entries in solution. May contain Folder or Project
objects. May be None, if the folder is empty.
variants: List of build variant strings. If none, a default list will
be used.
websiteProperties: Flag to decide if the website properties section
is generated. | Initializes the solution. | [
"Initializes",
"the",
"solution",
"."
] | def __init__(self, path, version, entries=None, variants=None,
websiteProperties=True):
"""Initializes the solution.
Args:
path: Path to solution file.
version: Format version to emit.
entries: List of entries in solution. May contain Folder or Project
objects. May be None, if the folder is empty.
variants: List of build variant strings. If none, a default list will
be used.
websiteProperties: Flag to decide if the website properties section
is generated.
"""
self.path = path
self.websiteProperties = websiteProperties
self.version = version
# Copy passed lists (or set to empty lists)
self.entries = list(entries or [])
if variants:
# Copy passed list
self.variants = variants[:]
else:
# Use default
self.variants = ['Debug|Win32', 'Release|Win32']
# TODO(rspangler): Need to be able to handle a mapping of solution config
# to project config. Should we be able to handle variants being a dict,
# or add a separate variant_map variable? If it's a dict, we can't
# guarantee the order of variants since dict keys aren't ordered.
# TODO(rspangler): Automatically write to disk for now; should delay until
# node-evaluation time.
self.Write() | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"version",
",",
"entries",
"=",
"None",
",",
"variants",
"=",
"None",
",",
"websiteProperties",
"=",
"True",
")",
":",
"self",
".",
"path",
"=",
"path",
"self",
".",
"websiteProperties",
"=",
"websiteProperties",
"self",
".",
"version",
"=",
"version",
"# Copy passed lists (or set to empty lists)",
"self",
".",
"entries",
"=",
"list",
"(",
"entries",
"or",
"[",
"]",
")",
"if",
"variants",
":",
"# Copy passed list",
"self",
".",
"variants",
"=",
"variants",
"[",
":",
"]",
"else",
":",
"# Use default",
"self",
".",
"variants",
"=",
"[",
"'Debug|Win32'",
",",
"'Release|Win32'",
"]",
"# TODO(rspangler): Need to be able to handle a mapping of solution config",
"# to project config. Should we be able to handle variants being a dict,",
"# or add a separate variant_map variable? If it's a dict, we can't",
"# guarantee the order of variants since dict keys aren't ordered.",
"# TODO(rspangler): Automatically write to disk for now; should delay until",
"# node-evaluation time.",
"self",
".",
"Write",
"(",
")"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/MSVSNew.py#L172-L207 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/Pharm2D/LazyGenerator.py | python | Generator.__init__ | (self, sigFactory, mol, dMat=None, bitCache=True) | constructor
**Arguments**
- sigFactory: a signature factory, see class docs
- mol: a molecule, see class docs
- dMat: (optional) a distance matrix for the molecule. If this
is not provided, one will be calculated
- bitCache: (optional) if nonzero, a local cache of which bits
have been queried will be maintained. Otherwise things must
be recalculate each time a bit is queried. | constructor | [
"constructor"
] | def __init__(self, sigFactory, mol, dMat=None, bitCache=True):
""" constructor
**Arguments**
- sigFactory: a signature factory, see class docs
- mol: a molecule, see class docs
- dMat: (optional) a distance matrix for the molecule. If this
is not provided, one will be calculated
- bitCache: (optional) if nonzero, a local cache of which bits
have been queried will be maintained. Otherwise things must
be recalculate each time a bit is queried.
"""
if not isinstance(sigFactory, SigFactory.SigFactory):
raise ValueError('bad factory')
self.sigFactory = sigFactory
self.mol = mol
if dMat is None:
useBO = sigFactory.includeBondOrder
dMat = Chem.GetDistanceMatrix(mol, useBO)
self.dMat = dMat
if bitCache:
self.bits = {}
else:
self.bits = None
featFamilies = [fam for fam in sigFactory.featFactory.GetFeatureFamilies()
if fam not in sigFactory.skipFeats]
nFeats = len(featFamilies)
featMatches = {}
for fam in featFamilies:
featMatches[fam] = []
feats = sigFactory.featFactory.GetFeaturesForMol(mol)
for feat in feats:
if feat.GetFamily() not in sigFactory.skipFeats:
featMatches[feat.GetFamily()].append(feat.GetAtomIds())
featMatches = [None] * nFeats
for i in range(nFeats):
featMatches[i] = sigFactory.featFactory.GetMolFeature()
self.pattMatches = pattMatches | [
"def",
"__init__",
"(",
"self",
",",
"sigFactory",
",",
"mol",
",",
"dMat",
"=",
"None",
",",
"bitCache",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"sigFactory",
",",
"SigFactory",
".",
"SigFactory",
")",
":",
"raise",
"ValueError",
"(",
"'bad factory'",
")",
"self",
".",
"sigFactory",
"=",
"sigFactory",
"self",
".",
"mol",
"=",
"mol",
"if",
"dMat",
"is",
"None",
":",
"useBO",
"=",
"sigFactory",
".",
"includeBondOrder",
"dMat",
"=",
"Chem",
".",
"GetDistanceMatrix",
"(",
"mol",
",",
"useBO",
")",
"self",
".",
"dMat",
"=",
"dMat",
"if",
"bitCache",
":",
"self",
".",
"bits",
"=",
"{",
"}",
"else",
":",
"self",
".",
"bits",
"=",
"None",
"featFamilies",
"=",
"[",
"fam",
"for",
"fam",
"in",
"sigFactory",
".",
"featFactory",
".",
"GetFeatureFamilies",
"(",
")",
"if",
"fam",
"not",
"in",
"sigFactory",
".",
"skipFeats",
"]",
"nFeats",
"=",
"len",
"(",
"featFamilies",
")",
"featMatches",
"=",
"{",
"}",
"for",
"fam",
"in",
"featFamilies",
":",
"featMatches",
"[",
"fam",
"]",
"=",
"[",
"]",
"feats",
"=",
"sigFactory",
".",
"featFactory",
".",
"GetFeaturesForMol",
"(",
"mol",
")",
"for",
"feat",
"in",
"feats",
":",
"if",
"feat",
".",
"GetFamily",
"(",
")",
"not",
"in",
"sigFactory",
".",
"skipFeats",
":",
"featMatches",
"[",
"feat",
".",
"GetFamily",
"(",
")",
"]",
".",
"append",
"(",
"feat",
".",
"GetAtomIds",
"(",
")",
")",
"featMatches",
"=",
"[",
"None",
"]",
"*",
"nFeats",
"for",
"i",
"in",
"range",
"(",
"nFeats",
")",
":",
"featMatches",
"[",
"i",
"]",
"=",
"sigFactory",
".",
"featFactory",
".",
"GetMolFeature",
"(",
")",
"self",
".",
"pattMatches",
"=",
"pattMatches"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/Pharm2D/LazyGenerator.py#L36-L83 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py | python | MH.__init__ | (self, path = None, profile = None) | Constructor. | Constructor. | [
"Constructor",
"."
] | def __init__(self, path = None, profile = None):
"""Constructor."""
if profile is None: profile = MH_PROFILE
self.profile = os.path.expanduser(profile)
if path is None: path = self.getprofile('Path')
if not path: path = PATH
if not os.path.isabs(path) and path[0] != '~':
path = os.path.join('~', path)
path = os.path.expanduser(path)
if not os.path.isdir(path): raise Error, 'MH() path not found'
self.path = path | [
"def",
"__init__",
"(",
"self",
",",
"path",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"profile",
"is",
"None",
":",
"profile",
"=",
"MH_PROFILE",
"self",
".",
"profile",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"profile",
")",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"getprofile",
"(",
"'Path'",
")",
"if",
"not",
"path",
":",
"path",
"=",
"PATH",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
"and",
"path",
"[",
"0",
"]",
"!=",
"'~'",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'~'",
",",
"path",
")",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"raise",
"Error",
",",
"'MH() path not found'",
"self",
".",
"path",
"=",
"path"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py#L102-L112 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/message.py | python | Message.ParseFromString | (self, serialized) | return self.MergeFromString(serialized) | Parse serialized protocol buffer data into this message.
Like :func:`MergeFromString()`, except we clear the object first. | Parse serialized protocol buffer data into this message. | [
"Parse",
"serialized",
"protocol",
"buffer",
"data",
"into",
"this",
"message",
"."
] | def ParseFromString(self, serialized):
"""Parse serialized protocol buffer data into this message.
Like :func:`MergeFromString()`, except we clear the object first.
"""
self.Clear()
return self.MergeFromString(serialized) | [
"def",
"ParseFromString",
"(",
"self",
",",
"serialized",
")",
":",
"self",
".",
"Clear",
"(",
")",
"return",
"self",
".",
"MergeFromString",
"(",
"serialized",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/message.py#L193-L199 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/arg_max.py | python | _arg_max_tbe | () | return | Argmax TBE register | Argmax TBE register | [
"Argmax",
"TBE",
"register"
] | def _arg_max_tbe():
"""Argmax TBE register"""
return | [
"def",
"_arg_max_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/arg_max.py#L36-L38 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/lib/clipboard.py | python | tkinter_clipboard_get | () | return text | Get the clipboard's text using Tkinter.
This is the default on systems that are not Windows or OS X. It may
interfere with other UI toolkits and should be replaced with an
implementation that uses that toolkit. | Get the clipboard's text using Tkinter. | [
"Get",
"the",
"clipboard",
"s",
"text",
"using",
"Tkinter",
"."
] | def tkinter_clipboard_get():
""" Get the clipboard's text using Tkinter.
This is the default on systems that are not Windows or OS X. It may
interfere with other UI toolkits and should be replaced with an
implementation that uses that toolkit.
"""
try:
from tkinter import Tk, TclError # Py 3
except ImportError:
try:
from Tkinter import Tk, TclError # Py 2
except ImportError:
raise TryNext("Getting text from the clipboard on this platform "
"requires Tkinter.")
root = Tk()
root.withdraw()
try:
text = root.clipboard_get()
except TclError:
raise ClipboardEmpty
finally:
root.destroy()
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
return text | [
"def",
"tkinter_clipboard_get",
"(",
")",
":",
"try",
":",
"from",
"tkinter",
"import",
"Tk",
",",
"TclError",
"# Py 3",
"except",
"ImportError",
":",
"try",
":",
"from",
"Tkinter",
"import",
"Tk",
",",
"TclError",
"# Py 2",
"except",
"ImportError",
":",
"raise",
"TryNext",
"(",
"\"Getting text from the clipboard on this platform \"",
"\"requires Tkinter.\"",
")",
"root",
"=",
"Tk",
"(",
")",
"root",
".",
"withdraw",
"(",
")",
"try",
":",
"text",
"=",
"root",
".",
"clipboard_get",
"(",
")",
"except",
"TclError",
":",
"raise",
"ClipboardEmpty",
"finally",
":",
"root",
".",
"destroy",
"(",
")",
"text",
"=",
"py3compat",
".",
"cast_unicode",
"(",
"text",
",",
"py3compat",
".",
"DEFAULT_ENCODING",
")",
"return",
"text"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/lib/clipboard.py#L46-L70 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/f2py/f2py2e.py | python | run_main | (comline_list) | return ret | Equivalent to running::
f2py <args>
where ``<args>=string.join(<list>,' ')``, but in Python. Unless
``-h`` is used, this function returns a dictionary containing
information on generated modules and their dependencies on source
files. For example, the command ``f2py -m scalar scalar.f`` can be
executed from Python as follows
You cannot build extension modules with this function, that is,
using ``-c`` is not allowed. Use ``compile`` command instead
Examples
--------
.. include:: run_main_session.dat
:literal: | Equivalent to running:: | [
"Equivalent",
"to",
"running",
"::"
] | def run_main(comline_list):
"""
Equivalent to running::
f2py <args>
where ``<args>=string.join(<list>,' ')``, but in Python. Unless
``-h`` is used, this function returns a dictionary containing
information on generated modules and their dependencies on source
files. For example, the command ``f2py -m scalar scalar.f`` can be
executed from Python as follows
You cannot build extension modules with this function, that is,
using ``-c`` is not allowed. Use ``compile`` command instead
Examples
--------
.. include:: run_main_session.dat
:literal:
"""
crackfortran.reset_global_f2py_vars()
f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__))
fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h')
fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c')
files, options = scaninputline(comline_list)
auxfuncs.options = options
postlist = callcrackfortran(files, options)
isusedby = {}
for i in range(len(postlist)):
if 'use' in postlist[i]:
for u in postlist[i]['use'].keys():
if u not in isusedby:
isusedby[u] = []
isusedby[u].append(postlist[i]['name'])
for i in range(len(postlist)):
if postlist[i]['block'] == 'python module' and '__user__' in postlist[i]['name']:
if postlist[i]['name'] in isusedby:
# if not quiet:
outmess('Skipping Makefile build for module "%s" which is used by %s\n' % (
postlist[i]['name'], ','.join(['"%s"' % s for s in isusedby[postlist[i]['name']]])))
if 'signsfile' in options:
if options['verbose'] > 1:
outmess(
'Stopping. Edit the signature file and then run f2py on the signature file: ')
outmess('%s %s\n' %
(os.path.basename(sys.argv[0]), options['signsfile']))
return
for i in range(len(postlist)):
if postlist[i]['block'] != 'python module':
if 'python module' not in options:
errmess(
'Tip: If your original code is Fortran source then you must use -m option.\n')
raise TypeError('All blocks must be python module blocks but got %s' % (
repr(postlist[i]['block'])))
auxfuncs.debugoptions = options['debug']
f90mod_rules.options = options
auxfuncs.wrapfuncs = options['wrapfuncs']
ret = buildmodules(postlist)
for mn in ret.keys():
dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc})
return ret | [
"def",
"run_main",
"(",
"comline_list",
")",
":",
"crackfortran",
".",
"reset_global_f2py_vars",
"(",
")",
"f2pydir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"cfuncs",
".",
"__file__",
")",
")",
"fobjhsrc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"f2pydir",
",",
"'src'",
",",
"'fortranobject.h'",
")",
"fobjcsrc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"f2pydir",
",",
"'src'",
",",
"'fortranobject.c'",
")",
"files",
",",
"options",
"=",
"scaninputline",
"(",
"comline_list",
")",
"auxfuncs",
".",
"options",
"=",
"options",
"postlist",
"=",
"callcrackfortran",
"(",
"files",
",",
"options",
")",
"isusedby",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"postlist",
")",
")",
":",
"if",
"'use'",
"in",
"postlist",
"[",
"i",
"]",
":",
"for",
"u",
"in",
"postlist",
"[",
"i",
"]",
"[",
"'use'",
"]",
".",
"keys",
"(",
")",
":",
"if",
"u",
"not",
"in",
"isusedby",
":",
"isusedby",
"[",
"u",
"]",
"=",
"[",
"]",
"isusedby",
"[",
"u",
"]",
".",
"append",
"(",
"postlist",
"[",
"i",
"]",
"[",
"'name'",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"postlist",
")",
")",
":",
"if",
"postlist",
"[",
"i",
"]",
"[",
"'block'",
"]",
"==",
"'python module'",
"and",
"'__user__'",
"in",
"postlist",
"[",
"i",
"]",
"[",
"'name'",
"]",
":",
"if",
"postlist",
"[",
"i",
"]",
"[",
"'name'",
"]",
"in",
"isusedby",
":",
"# if not quiet:",
"outmess",
"(",
"'Skipping Makefile build for module \"%s\" which is used by %s\\n'",
"%",
"(",
"postlist",
"[",
"i",
"]",
"[",
"'name'",
"]",
",",
"','",
".",
"join",
"(",
"[",
"'\"%s\"'",
"%",
"s",
"for",
"s",
"in",
"isusedby",
"[",
"postlist",
"[",
"i",
"]",
"[",
"'name'",
"]",
"]",
"]",
")",
")",
")",
"if",
"'signsfile'",
"in",
"options",
":",
"if",
"options",
"[",
"'verbose'",
"]",
">",
"1",
":",
"outmess",
"(",
"'Stopping. Edit the signature file and then run f2py on the signature file: '",
")",
"outmess",
"(",
"'%s %s\\n'",
"%",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
",",
"options",
"[",
"'signsfile'",
"]",
")",
")",
"return",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"postlist",
")",
")",
":",
"if",
"postlist",
"[",
"i",
"]",
"[",
"'block'",
"]",
"!=",
"'python module'",
":",
"if",
"'python module'",
"not",
"in",
"options",
":",
"errmess",
"(",
"'Tip: If your original code is Fortran source then you must use -m option.\\n'",
")",
"raise",
"TypeError",
"(",
"'All blocks must be python module blocks but got %s'",
"%",
"(",
"repr",
"(",
"postlist",
"[",
"i",
"]",
"[",
"'block'",
"]",
")",
")",
")",
"auxfuncs",
".",
"debugoptions",
"=",
"options",
"[",
"'debug'",
"]",
"f90mod_rules",
".",
"options",
"=",
"options",
"auxfuncs",
".",
"wrapfuncs",
"=",
"options",
"[",
"'wrapfuncs'",
"]",
"ret",
"=",
"buildmodules",
"(",
"postlist",
")",
"for",
"mn",
"in",
"ret",
".",
"keys",
"(",
")",
":",
"dict_append",
"(",
"ret",
"[",
"mn",
"]",
",",
"{",
"'csrc'",
":",
"fobjcsrc",
",",
"'h'",
":",
"fobjhsrc",
"}",
")",
"return",
"ret"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/f2py/f2py2e.py#L398-L461 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py | python | Beta.name | (self) | return self._name | Name to prepend to all ops. | Name to prepend to all ops. | [
"Name",
"to",
"prepend",
"to",
"all",
"ops",
"."
] | def name(self):
"""Name to prepend to all ops."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py#L164-L166 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pretty_annotate.py | python | reform_code | (annotation) | return s | Extract the code from the Numba annotation datastructure.
Pygments can only highlight full multi-line strings, the Numba
annotation is list of single lines, with indentation removed. | Extract the code from the Numba annotation datastructure. | [
"Extract",
"the",
"code",
"from",
"the",
"Numba",
"annotation",
"datastructure",
"."
] | def reform_code(annotation):
"""
Extract the code from the Numba annotation datastructure.
Pygments can only highlight full multi-line strings, the Numba
annotation is list of single lines, with indentation removed.
"""
ident_dict = annotation['python_indent']
s= ''
for n,l in annotation['python_lines']:
s = s+' '*ident_dict[n]+l+'\n'
return s | [
"def",
"reform_code",
"(",
"annotation",
")",
":",
"ident_dict",
"=",
"annotation",
"[",
"'python_indent'",
"]",
"s",
"=",
"''",
"for",
"n",
",",
"l",
"in",
"annotation",
"[",
"'python_lines'",
"]",
":",
"s",
"=",
"s",
"+",
"' '",
"*",
"ident_dict",
"[",
"n",
"]",
"+",
"l",
"+",
"'\\n'",
"return",
"s"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pretty_annotate.py#L210-L221 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.PositionFromPointClose | (*args, **kwargs) | return _stc.StyledTextCtrl_PositionFromPointClose(*args, **kwargs) | PositionFromPointClose(self, int x, int y) -> int
Find the position from a point within the window but return
INVALID_POSITION if not close to text. | PositionFromPointClose(self, int x, int y) -> int | [
"PositionFromPointClose",
"(",
"self",
"int",
"x",
"int",
"y",
")",
"-",
">",
"int"
] | def PositionFromPointClose(*args, **kwargs):
"""
PositionFromPointClose(self, int x, int y) -> int
Find the position from a point within the window but return
INVALID_POSITION if not close to text.
"""
return _stc.StyledTextCtrl_PositionFromPointClose(*args, **kwargs) | [
"def",
"PositionFromPointClose",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_PositionFromPointClose",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2194-L2201 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/lti_conversion.py | python | tf2ss | (num, den) | return A, B, C, D | r"""Transfer function to state-space representation.
Parameters
----------
num, den : array_like
Sequences representing the coefficients of the numerator and
denominator polynomials, in order of descending degree. The
denominator needs to be at least as long as the numerator.
Returns
-------
A, B, C, D : ndarray
State space representation of the system, in controller canonical
form.
Examples
--------
Convert the transfer function:
.. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
>>> num = [1, 3, 3]
>>> den = [1, 2, 1]
to the state-space representation:
.. math::
\dot{\textbf{x}}(t) =
\begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
\begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
\textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
\begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
>>> from scipy.signal import tf2ss
>>> A, B, C, D = tf2ss(num, den)
>>> A
array([[-2., -1.],
[ 1., 0.]])
>>> B
array([[ 1.],
[ 0.]])
>>> C
array([[ 1., 2.]])
>>> D
array([[ 1.]]) | r"""Transfer function to state-space representation. | [
"r",
"Transfer",
"function",
"to",
"state",
"-",
"space",
"representation",
"."
] | def tf2ss(num, den):
r"""Transfer function to state-space representation.
Parameters
----------
num, den : array_like
Sequences representing the coefficients of the numerator and
denominator polynomials, in order of descending degree. The
denominator needs to be at least as long as the numerator.
Returns
-------
A, B, C, D : ndarray
State space representation of the system, in controller canonical
form.
Examples
--------
Convert the transfer function:
.. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
>>> num = [1, 3, 3]
>>> den = [1, 2, 1]
to the state-space representation:
.. math::
\dot{\textbf{x}}(t) =
\begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
\begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
\textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
\begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
>>> from scipy.signal import tf2ss
>>> A, B, C, D = tf2ss(num, den)
>>> A
array([[-2., -1.],
[ 1., 0.]])
>>> B
array([[ 1.],
[ 0.]])
>>> C
array([[ 1., 2.]])
>>> D
array([[ 1.]])
"""
# Controller canonical state-space representation.
# if M+1 = len(num) and K+1 = len(den) then we must have M <= K
# states are found by asserting that X(s) = U(s) / D(s)
# then Y(s) = N(s) * X(s)
#
# A, B, C, and D follow quite naturally.
#
num, den = normalize(num, den) # Strips zeros, checks arrays
nn = len(num.shape)
if nn == 1:
num = asarray([num], num.dtype)
M = num.shape[1]
K = len(den)
if M > K:
msg = "Improper transfer function. `num` is longer than `den`."
raise ValueError(msg)
if M == 0 or K == 0: # Null system
return (array([], float), array([], float), array([], float),
array([], float))
# pad numerator to have same number of columns has denominator
num = r_['-1', zeros((num.shape[0], K - M), num.dtype), num]
if num.shape[-1] > 0:
D = atleast_2d(num[:, 0])
else:
# We don't assign it an empty array because this system
# is not 'null'. It just doesn't have a non-zero D
# matrix. Thus, it should have a non-zero shape so that
# it can be operated on by functions like 'ss2tf'
D = array([[0]], float)
if K == 1:
D = D.reshape(num.shape)
return (zeros((1, 1)), zeros((1, D.shape[1])),
zeros((D.shape[0], 1)), D)
frow = -array([den[1:]])
A = r_[frow, eye(K - 2, K - 1)]
B = eye(K - 1, 1)
C = num[:, 1:] - outer(num[:, 0], den[1:])
D = D.reshape((C.shape[0], B.shape[1]))
return A, B, C, D | [
"def",
"tf2ss",
"(",
"num",
",",
"den",
")",
":",
"# Controller canonical state-space representation.",
"# if M+1 = len(num) and K+1 = len(den) then we must have M <= K",
"# states are found by asserting that X(s) = U(s) / D(s)",
"# then Y(s) = N(s) * X(s)",
"#",
"# A, B, C, and D follow quite naturally.",
"#",
"num",
",",
"den",
"=",
"normalize",
"(",
"num",
",",
"den",
")",
"# Strips zeros, checks arrays",
"nn",
"=",
"len",
"(",
"num",
".",
"shape",
")",
"if",
"nn",
"==",
"1",
":",
"num",
"=",
"asarray",
"(",
"[",
"num",
"]",
",",
"num",
".",
"dtype",
")",
"M",
"=",
"num",
".",
"shape",
"[",
"1",
"]",
"K",
"=",
"len",
"(",
"den",
")",
"if",
"M",
">",
"K",
":",
"msg",
"=",
"\"Improper transfer function. `num` is longer than `den`.\"",
"raise",
"ValueError",
"(",
"msg",
")",
"if",
"M",
"==",
"0",
"or",
"K",
"==",
"0",
":",
"# Null system",
"return",
"(",
"array",
"(",
"[",
"]",
",",
"float",
")",
",",
"array",
"(",
"[",
"]",
",",
"float",
")",
",",
"array",
"(",
"[",
"]",
",",
"float",
")",
",",
"array",
"(",
"[",
"]",
",",
"float",
")",
")",
"# pad numerator to have same number of columns has denominator",
"num",
"=",
"r_",
"[",
"'-1'",
",",
"zeros",
"(",
"(",
"num",
".",
"shape",
"[",
"0",
"]",
",",
"K",
"-",
"M",
")",
",",
"num",
".",
"dtype",
")",
",",
"num",
"]",
"if",
"num",
".",
"shape",
"[",
"-",
"1",
"]",
">",
"0",
":",
"D",
"=",
"atleast_2d",
"(",
"num",
"[",
":",
",",
"0",
"]",
")",
"else",
":",
"# We don't assign it an empty array because this system",
"# is not 'null'. It just doesn't have a non-zero D",
"# matrix. Thus, it should have a non-zero shape so that",
"# it can be operated on by functions like 'ss2tf'",
"D",
"=",
"array",
"(",
"[",
"[",
"0",
"]",
"]",
",",
"float",
")",
"if",
"K",
"==",
"1",
":",
"D",
"=",
"D",
".",
"reshape",
"(",
"num",
".",
"shape",
")",
"return",
"(",
"zeros",
"(",
"(",
"1",
",",
"1",
")",
")",
",",
"zeros",
"(",
"(",
"1",
",",
"D",
".",
"shape",
"[",
"1",
"]",
")",
")",
",",
"zeros",
"(",
"(",
"D",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
",",
"D",
")",
"frow",
"=",
"-",
"array",
"(",
"[",
"den",
"[",
"1",
":",
"]",
"]",
")",
"A",
"=",
"r_",
"[",
"frow",
",",
"eye",
"(",
"K",
"-",
"2",
",",
"K",
"-",
"1",
")",
"]",
"B",
"=",
"eye",
"(",
"K",
"-",
"1",
",",
"1",
")",
"C",
"=",
"num",
"[",
":",
",",
"1",
":",
"]",
"-",
"outer",
"(",
"num",
"[",
":",
",",
"0",
"]",
",",
"den",
"[",
"1",
":",
"]",
")",
"D",
"=",
"D",
".",
"reshape",
"(",
"(",
"C",
".",
"shape",
"[",
"0",
"]",
",",
"B",
".",
"shape",
"[",
"1",
"]",
")",
")",
"return",
"A",
",",
"B",
",",
"C",
",",
"D"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/lti_conversion.py#L20-L114 | |
OpenGenus/quark | 225ad96efdfcc66cb6584a756c17eb3871e6eb62 | code/code/graph_algorithms/src/maximum_bipartite_matching/max_bipartite_matching.py | python | Graph.maxBPM | (self) | return result | An array to keep track of the applicants assigned to
jobs. The value of matchR[i] is the applicant number
assigned to job i, the value -1 indicates nobody is
assigned. | An array to keep track of the applicants assigned to
jobs. The value of matchR[i] is the applicant number
assigned to job i, the value -1 indicates nobody is
assigned. | [
"An",
"array",
"to",
"keep",
"track",
"of",
"the",
"applicants",
"assigned",
"to",
"jobs",
".",
"The",
"value",
"of",
"matchR",
"[",
"i",
"]",
"is",
"the",
"applicant",
"number",
"assigned",
"to",
"job",
"i",
"the",
"value",
"-",
"1",
"indicates",
"nobody",
"is",
"assigned",
"."
] | def maxBPM(self):
'''An array to keep track of the applicants assigned to
jobs. The value of matchR[i] is the applicant number
assigned to job i, the value -1 indicates nobody is
assigned.'''
matchR = [-1] * self.jobs
result = 0 # Count of jobs assigned to applicants
for i in range(self.ppl):
# Mark all jobs as not seen for next applicant.
seen = [False] * self.jobs
# Find if the applicant 'u' can get a job
if self.bpm(i, matchR, seen):
result += 1
return result | [
"def",
"maxBPM",
"(",
"self",
")",
":",
"matchR",
"=",
"[",
"-",
"1",
"]",
"*",
"self",
".",
"jobs",
"result",
"=",
"0",
"# Count of jobs assigned to applicants",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"ppl",
")",
":",
"# Mark all jobs as not seen for next applicant.",
"seen",
"=",
"[",
"False",
"]",
"*",
"self",
".",
"jobs",
"# Find if the applicant 'u' can get a job",
"if",
"self",
".",
"bpm",
"(",
"i",
",",
"matchR",
",",
"seen",
")",
":",
"result",
"+=",
"1",
"return",
"result"
] | https://github.com/OpenGenus/quark/blob/225ad96efdfcc66cb6584a756c17eb3871e6eb62/code/code/graph_algorithms/src/maximum_bipartite_matching/max_bipartite_matching.py#L38-L51 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | libcxx/utils/libcxx/util.py | python | executeCommandOrDie | (cmd, *args, **kwargs) | return out, err, exitCode | Execute a command and print its output on failure. | Execute a command and print its output on failure. | [
"Execute",
"a",
"command",
"and",
"print",
"its",
"output",
"on",
"failure",
"."
] | def executeCommandOrDie(cmd, *args, **kwargs):
"""
Execute a command and print its output on failure.
"""
out, err, exitCode = executeCommand(cmd, *args, **kwargs)
if exitCode != 0:
report = makeReport(cmd, out, err, exitCode)
report += "\n\nFailed!"
sys.stderr.write('%s\n' % report)
sys.exit(exitCode)
return out, err, exitCode | [
"def",
"executeCommandOrDie",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
",",
"err",
",",
"exitCode",
"=",
"executeCommand",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"exitCode",
"!=",
"0",
":",
"report",
"=",
"makeReport",
"(",
"cmd",
",",
"out",
",",
"err",
",",
"exitCode",
")",
"report",
"+=",
"\"\\n\\nFailed!\"",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s\\n'",
"%",
"report",
")",
"sys",
".",
"exit",
"(",
"exitCode",
")",
"return",
"out",
",",
"err",
",",
"exitCode"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/libcxx/utils/libcxx/util.py#L288-L298 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/_header_value_parser.py | python | _find_mime_parameters | (tokenlist, value) | Do our best to find the parameters in an invalid MIME header | Do our best to find the parameters in an invalid MIME header | [
"Do",
"our",
"best",
"to",
"find",
"the",
"parameters",
"in",
"an",
"invalid",
"MIME",
"header"
] | def _find_mime_parameters(tokenlist, value):
"""Do our best to find the parameters in an invalid MIME header
"""
while value and value[0] != ';':
if value[0] in PHRASE_ENDS:
tokenlist.append(ValueTerminal(value[0], 'misplaced-special'))
value = value[1:]
else:
token, value = get_phrase(value)
tokenlist.append(token)
if not value:
return
tokenlist.append(ValueTerminal(';', 'parameter-separator'))
tokenlist.append(parse_mime_parameters(value[1:])) | [
"def",
"_find_mime_parameters",
"(",
"tokenlist",
",",
"value",
")",
":",
"while",
"value",
"and",
"value",
"[",
"0",
"]",
"!=",
"';'",
":",
"if",
"value",
"[",
"0",
"]",
"in",
"PHRASE_ENDS",
":",
"tokenlist",
".",
"append",
"(",
"ValueTerminal",
"(",
"value",
"[",
"0",
"]",
",",
"'misplaced-special'",
")",
")",
"value",
"=",
"value",
"[",
"1",
":",
"]",
"else",
":",
"token",
",",
"value",
"=",
"get_phrase",
"(",
"value",
")",
"tokenlist",
".",
"append",
"(",
"token",
")",
"if",
"not",
"value",
":",
"return",
"tokenlist",
".",
"append",
"(",
"ValueTerminal",
"(",
"';'",
",",
"'parameter-separator'",
")",
")",
"tokenlist",
".",
"append",
"(",
"parse_mime_parameters",
"(",
"value",
"[",
"1",
":",
"]",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/_header_value_parser.py#L2486-L2500 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/util/cloudpickle.py | python | CloudPickler.extract_code_globals | (co) | return out_names | Find all globals names read or written to by codeblock co | Find all globals names read or written to by codeblock co | [
"Find",
"all",
"globals",
"names",
"read",
"or",
"written",
"to",
"by",
"codeblock",
"co"
] | def extract_code_globals(co):
"""
Find all globals names read or written to by codeblock co
"""
code = co.co_code
if not PY3:
code = [ord(c) for c in code]
names = co.co_names
out_names = set()
n = len(code)
i = 0
extended_arg = 0
while i < n:
op = code[i]
i += 1
if op >= HAVE_ARGUMENT:
oparg = code[i] + code[i+1] * 256 + extended_arg
extended_arg = 0
i += 2
if op == EXTENDED_ARG:
extended_arg = oparg*65536
if op in GLOBAL_OPS:
out_names.add(names[oparg])
# see if nested function have any global refs
if co.co_consts:
for const in co.co_consts:
if type(const) is types.CodeType:
out_names |= CloudPickler.extract_code_globals(const)
return out_names | [
"def",
"extract_code_globals",
"(",
"co",
")",
":",
"code",
"=",
"co",
".",
"co_code",
"if",
"not",
"PY3",
":",
"code",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"code",
"]",
"names",
"=",
"co",
".",
"co_names",
"out_names",
"=",
"set",
"(",
")",
"n",
"=",
"len",
"(",
"code",
")",
"i",
"=",
"0",
"extended_arg",
"=",
"0",
"while",
"i",
"<",
"n",
":",
"op",
"=",
"code",
"[",
"i",
"]",
"i",
"+=",
"1",
"if",
"op",
">=",
"HAVE_ARGUMENT",
":",
"oparg",
"=",
"code",
"[",
"i",
"]",
"+",
"code",
"[",
"i",
"+",
"1",
"]",
"*",
"256",
"+",
"extended_arg",
"extended_arg",
"=",
"0",
"i",
"+=",
"2",
"if",
"op",
"==",
"EXTENDED_ARG",
":",
"extended_arg",
"=",
"oparg",
"*",
"65536",
"if",
"op",
"in",
"GLOBAL_OPS",
":",
"out_names",
".",
"add",
"(",
"names",
"[",
"oparg",
"]",
")",
"# see if nested function have any global refs",
"if",
"co",
".",
"co_consts",
":",
"for",
"const",
"in",
"co",
".",
"co_consts",
":",
"if",
"type",
"(",
"const",
")",
"is",
"types",
".",
"CodeType",
":",
"out_names",
"|=",
"CloudPickler",
".",
"extract_code_globals",
"(",
"const",
")",
"return",
"out_names"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/util/cloudpickle.py#L249-L281 | |
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | python/caffe/detector.py | python | Detector.detect_selective_search | (self, image_fnames) | return self.detect_windows(zip(image_fnames, windows_list)) | Do windowed detection over Selective Search proposals by extracting
the crop and warping to the input dimensions of the net.
Parameters
----------
image_fnames: list
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts. | Do windowed detection over Selective Search proposals by extracting
the crop and warping to the input dimensions of the net. | [
"Do",
"windowed",
"detection",
"over",
"Selective",
"Search",
"proposals",
"by",
"extracting",
"the",
"crop",
"and",
"warping",
"to",
"the",
"input",
"dimensions",
"of",
"the",
"net",
"."
] | def detect_selective_search(self, image_fnames):
"""
Do windowed detection over Selective Search proposals by extracting
the crop and warping to the input dimensions of the net.
Parameters
----------
image_fnames: list
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts.
"""
import selective_search_ijcv_with_python as selective_search
# Make absolute paths so MATLAB can find the files.
image_fnames = [os.path.abspath(f) for f in image_fnames]
windows_list = selective_search.get_windows(
image_fnames,
cmd='selective_search_rcnn'
)
# Run windowed detection on the selective search list.
return self.detect_windows(zip(image_fnames, windows_list)) | [
"def",
"detect_selective_search",
"(",
"self",
",",
"image_fnames",
")",
":",
"import",
"selective_search_ijcv_with_python",
"as",
"selective_search",
"# Make absolute paths so MATLAB can find the files.",
"image_fnames",
"=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"f",
")",
"for",
"f",
"in",
"image_fnames",
"]",
"windows_list",
"=",
"selective_search",
".",
"get_windows",
"(",
"image_fnames",
",",
"cmd",
"=",
"'selective_search_rcnn'",
")",
"# Run windowed detection on the selective search list.",
"return",
"self",
".",
"detect_windows",
"(",
"zip",
"(",
"image_fnames",
",",
"windows_list",
")",
")"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/python/caffe/detector.py#L101-L123 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_distutils/text_file.py | python | TextFile.readlines | (self) | Read and return the list of all logical lines remaining in the
current file. | Read and return the list of all logical lines remaining in the
current file. | [
"Read",
"and",
"return",
"the",
"list",
"of",
"all",
"logical",
"lines",
"remaining",
"in",
"the",
"current",
"file",
"."
] | def readlines(self):
"""Read and return the list of all logical lines remaining in the
current file."""
lines = []
while True:
line = self.readline()
if line is None:
return lines
lines.append(line) | [
"def",
"readlines",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"line",
"is",
"None",
":",
"return",
"lines",
"lines",
".",
"append",
"(",
"line",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/text_file.py#L272-L280 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PGProperty.RefreshEditor | (*args, **kwargs) | return _propgrid.PGProperty_RefreshEditor(*args, **kwargs) | RefreshEditor(self) | RefreshEditor(self) | [
"RefreshEditor",
"(",
"self",
")"
] | def RefreshEditor(*args, **kwargs):
"""RefreshEditor(self)"""
return _propgrid.PGProperty_RefreshEditor(*args, **kwargs) | [
"def",
"RefreshEditor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_RefreshEditor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L671-L673 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/yply/yparse.py | python | p_empty | (p) | empty : | empty : | [
"empty",
":"
] | def p_empty(p):
'''empty : ''' | [
"def",
"p_empty",
"(",
"p",
")",
":"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/yply/yparse.py#L204-L205 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | util/minorview/model.py | python | find_colour_decoder | (stripSpace, decoderName, dataName, picPairs) | Make a colour decoder from some picture file blob attributes | Make a colour decoder from some picture file blob attributes | [
"Make",
"a",
"colour",
"decoder",
"from",
"some",
"picture",
"file",
"blob",
"attributes"
] | def find_colour_decoder(stripSpace, decoderName, dataName, picPairs):
"""Make a colour decoder from some picture file blob attributes"""
if decoderName == 'frame':
return FrameColours.decoder(Counts, stripSpace, dataName)
elif decoderName in decoder_element_classes:
return TwoDColours.decoder(decoder_element_classes[decoderName],
dataName)
elif decoderName in indexed_decoder_element_classes:
return TwoDColours.indexed_decoder(
indexed_decoder_element_classes[decoderName], dataName, picPairs)
else:
return None | [
"def",
"find_colour_decoder",
"(",
"stripSpace",
",",
"decoderName",
",",
"dataName",
",",
"picPairs",
")",
":",
"if",
"decoderName",
"==",
"'frame'",
":",
"return",
"FrameColours",
".",
"decoder",
"(",
"Counts",
",",
"stripSpace",
",",
"dataName",
")",
"elif",
"decoderName",
"in",
"decoder_element_classes",
":",
"return",
"TwoDColours",
".",
"decoder",
"(",
"decoder_element_classes",
"[",
"decoderName",
"]",
",",
"dataName",
")",
"elif",
"decoderName",
"in",
"indexed_decoder_element_classes",
":",
"return",
"TwoDColours",
".",
"indexed_decoder",
"(",
"indexed_decoder_element_classes",
"[",
"decoderName",
"]",
",",
"dataName",
",",
"picPairs",
")",
"else",
":",
"return",
"None"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/minorview/model.py#L407-L418 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nntplib.py | python | _NNTPBase._putcmd | (self, line) | Internal: send one command to the server (through _putline()).
The `line` must be a unicode string. | Internal: send one command to the server (through _putline()).
The `line` must be a unicode string. | [
"Internal",
":",
"send",
"one",
"command",
"to",
"the",
"server",
"(",
"through",
"_putline",
"()",
")",
".",
"The",
"line",
"must",
"be",
"a",
"unicode",
"string",
"."
] | def _putcmd(self, line):
"""Internal: send one command to the server (through _putline()).
The `line` must be a unicode string."""
if self.debugging: print('*cmd*', repr(line))
line = line.encode(self.encoding, self.errors)
self._putline(line) | [
"def",
"_putcmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"debugging",
":",
"print",
"(",
"'*cmd*'",
",",
"repr",
"(",
"line",
")",
")",
"line",
"=",
"line",
".",
"encode",
"(",
"self",
".",
"encoding",
",",
"self",
".",
"errors",
")",
"self",
".",
"_putline",
"(",
"line",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nntplib.py#L421-L426 | ||
bryanyzhu/Hidden-Two-Stream | f7f684adbdacb6df6b1cf196c3a476cd23484a0f | python/caffe/io.py | python | array_to_datum | (arr, label=None) | return datum | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | [
"Converts",
"a",
"3",
"-",
"dimensional",
"array",
"to",
"datum",
".",
"If",
"the",
"array",
"has",
"dtype",
"uint8",
"the",
"output",
"data",
"will",
"be",
"encoded",
"as",
"a",
"string",
".",
"Otherwise",
"the",
"output",
"data",
"will",
"be",
"stored",
"in",
"float",
"format",
"."
] | def array_to_datum(arr, label=None):
"""Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format.
"""
if arr.ndim != 3:
raise ValueError('Incorrect array shape.')
datum = caffe_pb2.Datum()
datum.channels, datum.height, datum.width = arr.shape
if arr.dtype == np.uint8:
datum.data = arr.tostring()
else:
datum.float_data.extend(arr.flat)
if label is not None:
datum.label = label
return datum | [
"def",
"array_to_datum",
"(",
"arr",
",",
"label",
"=",
"None",
")",
":",
"if",
"arr",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Incorrect array shape.'",
")",
"datum",
"=",
"caffe_pb2",
".",
"Datum",
"(",
")",
"datum",
".",
"channels",
",",
"datum",
".",
"height",
",",
"datum",
".",
"width",
"=",
"arr",
".",
"shape",
"if",
"arr",
".",
"dtype",
"==",
"np",
".",
"uint8",
":",
"datum",
".",
"data",
"=",
"arr",
".",
"tostring",
"(",
")",
"else",
":",
"datum",
".",
"float_data",
".",
"extend",
"(",
"arr",
".",
"flat",
")",
"if",
"label",
"is",
"not",
"None",
":",
"datum",
".",
"label",
"=",
"label",
"return",
"datum"
] | https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/python/caffe/io.py#L66-L81 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/morestats.py | python | shapiro | (x, a=None, reta=False) | Perform the Shapiro-Wilk test for normality.
The Shapiro-Wilk test tests the null hypothesis that the
data was drawn from a normal distribution.
Parameters
----------
x : array_like
Array of sample data.
a : array_like, optional
Array of internal parameters used in the calculation. If these
are not given, they will be computed internally. If x has length
n, then a must have length n/2.
reta : bool, optional
Whether or not to return the internally computed a values. The
default is False.
Returns
-------
W : float
The test statistic.
p-value : float
The p-value for the hypothesis test.
a : array_like, optional
If `reta` is True, then these are the internally computed "a"
values that may be passed into this function on future calls.
See Also
--------
anderson : The Anderson-Darling test for normality
kstest : The Kolmogorov-Smirnov test for goodness of fit.
Notes
-----
The algorithm used is described in [4]_ but censoring parameters as
described are not implemented. For N > 5000 the W test statistic is accurate
but the p-value may not be.
The chance of rejecting the null hypothesis when it is true is close to 5%
regardless of sample size.
References
----------
.. [1] http://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
.. [2] Shapiro, S. S. & Wilk, M.B (1965). An analysis of variance test for
normality (complete samples), Biometrika, Vol. 52, pp. 591-611.
.. [3] Razali, N. M. & Wah, Y. B. (2011) Power comparisons of Shapiro-Wilk,
Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests, Journal of
Statistical Modeling and Analytics, Vol. 2, pp. 21-33.
.. [4] ALGORITHM AS R94 APPL. STATIST. (1995) VOL. 44, NO. 4.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678)
>>> x = stats.norm.rvs(loc=5, scale=3, size=100)
>>> stats.shapiro(x)
(0.9772805571556091, 0.08144091814756393) | Perform the Shapiro-Wilk test for normality. | [
"Perform",
"the",
"Shapiro",
"-",
"Wilk",
"test",
"for",
"normality",
"."
] | def shapiro(x, a=None, reta=False):
"""
Perform the Shapiro-Wilk test for normality.
The Shapiro-Wilk test tests the null hypothesis that the
data was drawn from a normal distribution.
Parameters
----------
x : array_like
Array of sample data.
a : array_like, optional
Array of internal parameters used in the calculation. If these
are not given, they will be computed internally. If x has length
n, then a must have length n/2.
reta : bool, optional
Whether or not to return the internally computed a values. The
default is False.
Returns
-------
W : float
The test statistic.
p-value : float
The p-value for the hypothesis test.
a : array_like, optional
If `reta` is True, then these are the internally computed "a"
values that may be passed into this function on future calls.
See Also
--------
anderson : The Anderson-Darling test for normality
kstest : The Kolmogorov-Smirnov test for goodness of fit.
Notes
-----
The algorithm used is described in [4]_ but censoring parameters as
described are not implemented. For N > 5000 the W test statistic is accurate
but the p-value may not be.
The chance of rejecting the null hypothesis when it is true is close to 5%
regardless of sample size.
References
----------
.. [1] http://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
.. [2] Shapiro, S. S. & Wilk, M.B (1965). An analysis of variance test for
normality (complete samples), Biometrika, Vol. 52, pp. 591-611.
.. [3] Razali, N. M. & Wah, Y. B. (2011) Power comparisons of Shapiro-Wilk,
Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests, Journal of
Statistical Modeling and Analytics, Vol. 2, pp. 21-33.
.. [4] ALGORITHM AS R94 APPL. STATIST. (1995) VOL. 44, NO. 4.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678)
>>> x = stats.norm.rvs(loc=5, scale=3, size=100)
>>> stats.shapiro(x)
(0.9772805571556091, 0.08144091814756393)
"""
if a is not None or reta:
warnings.warn("input parameters 'a' and 'reta' are scheduled to be "
"removed in version 0.18.0", FutureWarning)
x = np.ravel(x)
N = len(x)
if N < 3:
raise ValueError("Data must be at least length 3.")
if a is None:
a = zeros(N, 'f')
init = 0
else:
if len(a) != N // 2:
raise ValueError("len(a) must equal len(x)/2")
init = 1
y = sort(x)
a, w, pw, ifault = statlib.swilk(y, a[:N//2], init)
if ifault not in [0, 2]:
warnings.warn("Input data for shapiro has range zero. The results "
"may not be accurate.")
if N > 5000:
warnings.warn("p-value may not be accurate for N > 5000.")
if reta:
return w, pw, a
else:
return w, pw | [
"def",
"shapiro",
"(",
"x",
",",
"a",
"=",
"None",
",",
"reta",
"=",
"False",
")",
":",
"if",
"a",
"is",
"not",
"None",
"or",
"reta",
":",
"warnings",
".",
"warn",
"(",
"\"input parameters 'a' and 'reta' are scheduled to be \"",
"\"removed in version 0.18.0\"",
",",
"FutureWarning",
")",
"x",
"=",
"np",
".",
"ravel",
"(",
"x",
")",
"N",
"=",
"len",
"(",
"x",
")",
"if",
"N",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"\"Data must be at least length 3.\"",
")",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"zeros",
"(",
"N",
",",
"'f'",
")",
"init",
"=",
"0",
"else",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"N",
"//",
"2",
":",
"raise",
"ValueError",
"(",
"\"len(a) must equal len(x)/2\"",
")",
"init",
"=",
"1",
"y",
"=",
"sort",
"(",
"x",
")",
"a",
",",
"w",
",",
"pw",
",",
"ifault",
"=",
"statlib",
".",
"swilk",
"(",
"y",
",",
"a",
"[",
":",
"N",
"//",
"2",
"]",
",",
"init",
")",
"if",
"ifault",
"not",
"in",
"[",
"0",
",",
"2",
"]",
":",
"warnings",
".",
"warn",
"(",
"\"Input data for shapiro has range zero. The results \"",
"\"may not be accurate.\"",
")",
"if",
"N",
">",
"5000",
":",
"warnings",
".",
"warn",
"(",
"\"p-value may not be accurate for N > 5000.\"",
")",
"if",
"reta",
":",
"return",
"w",
",",
"pw",
",",
"a",
"else",
":",
"return",
"w",
",",
"pw"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/morestats.py#L1247-L1334 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py | python | HtmlDiff.make_table | (self,fromlines,tolines,fromdesc='',todesc='',context=False,
numlines=5) | return table.replace('\0+','<span class="diff_add">'). \
replace('\0-','<span class="diff_sub">'). \
replace('\0^','<span class="diff_chg">'). \
replace('\1','</span>'). \
replace('\t',' ') | Returns HTML table of side by side comparison with change highlights
Arguments:
fromlines -- list of "from" lines
tolines -- list of "to" lines
fromdesc -- "from" file column header string
todesc -- "to" file column header string
context -- set to True for contextual differences (defaults to False
which shows full differences).
numlines -- number of context lines. When context is set True,
controls number of lines displayed before and after the change.
When context is False, controls the number of lines to place
the "next" link anchors before the next change (so click of
"next" link jumps to just before the change). | Returns HTML table of side by side comparison with change highlights | [
"Returns",
"HTML",
"table",
"of",
"side",
"by",
"side",
"comparison",
"with",
"change",
"highlights"
] | def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
numlines=5):
"""Returns HTML table of side by side comparison with change highlights
Arguments:
fromlines -- list of "from" lines
tolines -- list of "to" lines
fromdesc -- "from" file column header string
todesc -- "to" file column header string
context -- set to True for contextual differences (defaults to False
which shows full differences).
numlines -- number of context lines. When context is set True,
controls number of lines displayed before and after the change.
When context is False, controls the number of lines to place
the "next" link anchors before the next change (so click of
"next" link jumps to just before the change).
"""
# make unique anchor prefixes so that multiple tables may exist
# on the same page without conflict.
self._make_prefix()
# change tabs to spaces before it gets more difficult after we insert
# markup
fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
# create diffs iterator which generates side by side from/to data
if context:
context_lines = numlines
else:
context_lines = None
diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
charjunk=self._charjunk)
# set up iterator to wrap lines that exceed desired width
if self._wrapcolumn:
diffs = self._line_wrapper(diffs)
# collect up from/to lines and flags into lists (also format the lines)
fromlist,tolist,flaglist = self._collect_lines(diffs)
# process change flags, generating middle column of next anchors/links
fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
fromlist,tolist,flaglist,context,numlines)
s = []
fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
'<td class="diff_next">%s</td>%s</tr>\n'
for i in range(len(flaglist)):
if flaglist[i] is None:
# mdiff yields None on separator lines skip the bogus ones
# generated for the first line
if i > 0:
s.append(' </tbody> \n <tbody>\n')
else:
s.append( fmt % (next_id[i],next_href[i],fromlist[i],
next_href[i],tolist[i]))
if fromdesc or todesc:
header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
'<th class="diff_next"><br /></th>',
'<th colspan="2" class="diff_header">%s</th>' % fromdesc,
'<th class="diff_next"><br /></th>',
'<th colspan="2" class="diff_header">%s</th>' % todesc)
else:
header_row = ''
table = self._table_template % dict(
data_rows=''.join(s),
header_row=header_row,
prefix=self._prefix[1])
return table.replace('\0+','<span class="diff_add">'). \
replace('\0-','<span class="diff_sub">'). \
replace('\0^','<span class="diff_chg">'). \
replace('\1','</span>'). \
replace('\t',' ') | [
"def",
"make_table",
"(",
"self",
",",
"fromlines",
",",
"tolines",
",",
"fromdesc",
"=",
"''",
",",
"todesc",
"=",
"''",
",",
"context",
"=",
"False",
",",
"numlines",
"=",
"5",
")",
":",
"# make unique anchor prefixes so that multiple tables may exist",
"# on the same page without conflict.",
"self",
".",
"_make_prefix",
"(",
")",
"# change tabs to spaces before it gets more difficult after we insert",
"# markup",
"fromlines",
",",
"tolines",
"=",
"self",
".",
"_tab_newline_replace",
"(",
"fromlines",
",",
"tolines",
")",
"# create diffs iterator which generates side by side from/to data",
"if",
"context",
":",
"context_lines",
"=",
"numlines",
"else",
":",
"context_lines",
"=",
"None",
"diffs",
"=",
"_mdiff",
"(",
"fromlines",
",",
"tolines",
",",
"context_lines",
",",
"linejunk",
"=",
"self",
".",
"_linejunk",
",",
"charjunk",
"=",
"self",
".",
"_charjunk",
")",
"# set up iterator to wrap lines that exceed desired width",
"if",
"self",
".",
"_wrapcolumn",
":",
"diffs",
"=",
"self",
".",
"_line_wrapper",
"(",
"diffs",
")",
"# collect up from/to lines and flags into lists (also format the lines)",
"fromlist",
",",
"tolist",
",",
"flaglist",
"=",
"self",
".",
"_collect_lines",
"(",
"diffs",
")",
"# process change flags, generating middle column of next anchors/links",
"fromlist",
",",
"tolist",
",",
"flaglist",
",",
"next_href",
",",
"next_id",
"=",
"self",
".",
"_convert_flags",
"(",
"fromlist",
",",
"tolist",
",",
"flaglist",
",",
"context",
",",
"numlines",
")",
"s",
"=",
"[",
"]",
"fmt",
"=",
"' <tr><td class=\"diff_next\"%s>%s</td>%s'",
"+",
"'<td class=\"diff_next\">%s</td>%s</tr>\\n'",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"flaglist",
")",
")",
":",
"if",
"flaglist",
"[",
"i",
"]",
"is",
"None",
":",
"# mdiff yields None on separator lines skip the bogus ones",
"# generated for the first line",
"if",
"i",
">",
"0",
":",
"s",
".",
"append",
"(",
"' </tbody> \\n <tbody>\\n'",
")",
"else",
":",
"s",
".",
"append",
"(",
"fmt",
"%",
"(",
"next_id",
"[",
"i",
"]",
",",
"next_href",
"[",
"i",
"]",
",",
"fromlist",
"[",
"i",
"]",
",",
"next_href",
"[",
"i",
"]",
",",
"tolist",
"[",
"i",
"]",
")",
")",
"if",
"fromdesc",
"or",
"todesc",
":",
"header_row",
"=",
"'<thead><tr>%s%s%s%s</tr></thead>'",
"%",
"(",
"'<th class=\"diff_next\"><br /></th>'",
",",
"'<th colspan=\"2\" class=\"diff_header\">%s</th>'",
"%",
"fromdesc",
",",
"'<th class=\"diff_next\"><br /></th>'",
",",
"'<th colspan=\"2\" class=\"diff_header\">%s</th>'",
"%",
"todesc",
")",
"else",
":",
"header_row",
"=",
"''",
"table",
"=",
"self",
".",
"_table_template",
"%",
"dict",
"(",
"data_rows",
"=",
"''",
".",
"join",
"(",
"s",
")",
",",
"header_row",
"=",
"header_row",
",",
"prefix",
"=",
"self",
".",
"_prefix",
"[",
"1",
"]",
")",
"return",
"table",
".",
"replace",
"(",
"'\\0+'",
",",
"'<span class=\"diff_add\">'",
")",
".",
"replace",
"(",
"'\\0-'",
",",
"'<span class=\"diff_sub\">'",
")",
".",
"replace",
"(",
"'\\0^'",
",",
"'<span class=\"diff_chg\">'",
")",
".",
"replace",
"(",
"'\\1'",
",",
"'</span>'",
")",
".",
"replace",
"(",
"'\\t'",
",",
"' '",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py#L1981-L2056 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | TextAttr.HasFontItalic | (*args, **kwargs) | return _controls_.TextAttr_HasFontItalic(*args, **kwargs) | HasFontItalic(self) -> bool | HasFontItalic(self) -> bool | [
"HasFontItalic",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasFontItalic(*args, **kwargs):
"""HasFontItalic(self) -> bool"""
return _controls_.TextAttr_HasFontItalic(*args, **kwargs) | [
"def",
"HasFontItalic",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasFontItalic",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L1800-L1802 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Image.GetWidth | (*args, **kwargs) | return _core_.Image_GetWidth(*args, **kwargs) | GetWidth(self) -> int
Gets the width of the image in pixels. | GetWidth(self) -> int | [
"GetWidth",
"(",
"self",
")",
"-",
">",
"int"
] | def GetWidth(*args, **kwargs):
"""
GetWidth(self) -> int
Gets the width of the image in pixels.
"""
return _core_.Image_GetWidth(*args, **kwargs) | [
"def",
"GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L3266-L3272 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | htmlReadDoc | (cur, URL, encoding, options) | return xmlDoc(_obj=ret) | parse an XML in-memory document and build a tree. | parse an XML in-memory document and build a tree. | [
"parse",
"an",
"XML",
"in",
"-",
"memory",
"document",
"and",
"build",
"a",
"tree",
"."
] | def htmlReadDoc(cur, URL, encoding, options):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.htmlReadDoc(cur, URL, encoding, options)
if ret is None:raise treeError('htmlReadDoc() failed')
return xmlDoc(_obj=ret) | [
"def",
"htmlReadDoc",
"(",
"cur",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlReadDoc",
"(",
"cur",
",",
"URL",
",",
"encoding",
",",
"options",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'htmlReadDoc() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L828-L832 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py | python | Context.min | (self, a, b) | return a.min(b, context=self) | min compares two values numerically and returns the minimum.
If either operand is a NaN then the general rules apply.
Otherwise, the operands are compared as though by the compare
operation. If they are numerically equal then the left-hand operand
is chosen as the result. Otherwise the minimum (closer to negative
infinity) of the two operands is chosen as the result.
>>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Decimal('2')
>>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Decimal('-10')
>>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Decimal('1.0')
>>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Decimal('7')
>>> ExtendedContext.min(1, 2)
Decimal('1')
>>> ExtendedContext.min(Decimal(1), 2)
Decimal('1')
>>> ExtendedContext.min(1, Decimal(29))
Decimal('1') | min compares two values numerically and returns the minimum. | [
"min",
"compares",
"two",
"values",
"numerically",
"and",
"returns",
"the",
"minimum",
"."
] | def min(self, a, b):
"""min compares two values numerically and returns the minimum.
If either operand is a NaN then the general rules apply.
Otherwise, the operands are compared as though by the compare
operation. If they are numerically equal then the left-hand operand
is chosen as the result. Otherwise the minimum (closer to negative
infinity) of the two operands is chosen as the result.
>>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Decimal('2')
>>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Decimal('-10')
>>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Decimal('1.0')
>>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Decimal('7')
>>> ExtendedContext.min(1, 2)
Decimal('1')
>>> ExtendedContext.min(Decimal(1), 2)
Decimal('1')
>>> ExtendedContext.min(1, Decimal(29))
Decimal('1')
"""
a = _convert_other(a, raiseit=True)
return a.min(b, context=self) | [
"def",
"min",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"min",
"(",
"b",
",",
"context",
"=",
"self",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L4706-L4731 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Layer.SetSpatialFilterRect | (self, *args) | return _ogr.Layer_SetSpatialFilterRect(self, *args) | r"""
SetSpatialFilterRect(Layer self, double minx, double miny, double maxx, double maxy)
SetSpatialFilterRect(Layer self, int iGeomField, double minx, double miny, double maxx, double maxy)
void
OGR_L_SetSpatialFilterRect(OGRLayerH hLayer, double dfMinX, double
dfMinY, double dfMaxX, double dfMaxY)
Set a new rectangular spatial filter.
This method set rectangle to be used as a spatial filter when fetching
features via the OGR_L_GetNextFeature() method. Only features that
geometrically intersect the given rectangle will be returned.
The x/y values should be in the same coordinate system as the layer as
a whole (as returned by OGRLayer::GetSpatialRef()). Internally this
method is normally implemented as creating a 5 vertex closed
rectangular polygon and passing it to OGRLayer::SetSpatialFilter(). It
exists as a convenience.
The only way to clear a spatial filter set with this method is to call
OGRLayer::SetSpatialFilter(NULL).
This method is the same as the C++ method
OGRLayer::SetSpatialFilterRect().
Parameters:
-----------
hLayer: handle to the layer on which to set the spatial filter.
dfMinX: the minimum X coordinate for the rectangular region.
dfMinY: the minimum Y coordinate for the rectangular region.
dfMaxX: the maximum X coordinate for the rectangular region.
dfMaxY: the maximum Y coordinate for the rectangular region. | r"""
SetSpatialFilterRect(Layer self, double minx, double miny, double maxx, double maxy)
SetSpatialFilterRect(Layer self, int iGeomField, double minx, double miny, double maxx, double maxy)
void
OGR_L_SetSpatialFilterRect(OGRLayerH hLayer, double dfMinX, double
dfMinY, double dfMaxX, double dfMaxY) | [
"r",
"SetSpatialFilterRect",
"(",
"Layer",
"self",
"double",
"minx",
"double",
"miny",
"double",
"maxx",
"double",
"maxy",
")",
"SetSpatialFilterRect",
"(",
"Layer",
"self",
"int",
"iGeomField",
"double",
"minx",
"double",
"miny",
"double",
"maxx",
"double",
"maxy",
")",
"void",
"OGR_L_SetSpatialFilterRect",
"(",
"OGRLayerH",
"hLayer",
"double",
"dfMinX",
"double",
"dfMinY",
"double",
"dfMaxX",
"double",
"dfMaxY",
")"
] | def SetSpatialFilterRect(self, *args):
r"""
SetSpatialFilterRect(Layer self, double minx, double miny, double maxx, double maxy)
SetSpatialFilterRect(Layer self, int iGeomField, double minx, double miny, double maxx, double maxy)
void
OGR_L_SetSpatialFilterRect(OGRLayerH hLayer, double dfMinX, double
dfMinY, double dfMaxX, double dfMaxY)
Set a new rectangular spatial filter.
This method set rectangle to be used as a spatial filter when fetching
features via the OGR_L_GetNextFeature() method. Only features that
geometrically intersect the given rectangle will be returned.
The x/y values should be in the same coordinate system as the layer as
a whole (as returned by OGRLayer::GetSpatialRef()). Internally this
method is normally implemented as creating a 5 vertex closed
rectangular polygon and passing it to OGRLayer::SetSpatialFilter(). It
exists as a convenience.
The only way to clear a spatial filter set with this method is to call
OGRLayer::SetSpatialFilter(NULL).
This method is the same as the C++ method
OGRLayer::SetSpatialFilterRect().
Parameters:
-----------
hLayer: handle to the layer on which to set the spatial filter.
dfMinX: the minimum X coordinate for the rectangular region.
dfMinY: the minimum Y coordinate for the rectangular region.
dfMaxX: the maximum X coordinate for the rectangular region.
dfMaxY: the maximum Y coordinate for the rectangular region.
"""
return _ogr.Layer_SetSpatialFilterRect(self, *args) | [
"def",
"SetSpatialFilterRect",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Layer_SetSpatialFilterRect",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L1079-L1118 | |
MtnViewJohn/context-free | 757d7bde9742f201cec61bd195dda98093edd1e8 | src-scintilla/scripts/FileGenerator.py | python | Regenerate | (filename, commentPrefix, *lists) | Regenerate the given file. | Regenerate the given file. | [
"Regenerate",
"the",
"given",
"file",
"."
] | def Regenerate(filename, commentPrefix, *lists):
"""Regenerate the given file.
"""
Generate(filename, filename, commentPrefix, *lists) | [
"def",
"Regenerate",
"(",
"filename",
",",
"commentPrefix",
",",
"*",
"lists",
")",
":",
"Generate",
"(",
"filename",
",",
"filename",
",",
"commentPrefix",
",",
"*",
"lists",
")"
] | https://github.com/MtnViewJohn/context-free/blob/757d7bde9742f201cec61bd195dda98093edd1e8/src-scintilla/scripts/FileGenerator.py#L135-L138 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PyPreviewFrame._setCallbackInfo | (*args, **kwargs) | return _windows_.PyPreviewFrame__setCallbackInfo(*args, **kwargs) | _setCallbackInfo(self, PyObject self, PyObject _class) | _setCallbackInfo(self, PyObject self, PyObject _class) | [
"_setCallbackInfo",
"(",
"self",
"PyObject",
"self",
"PyObject",
"_class",
")"
] | def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _windows_.PyPreviewFrame__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PyPreviewFrame__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L5744-L5746 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Scrollbar.get | (self) | return self._getdoubles(self.tk.call(self._w, 'get')) | Return the current fractional values (upper and lower end)
of the slider position. | Return the current fractional values (upper and lower end)
of the slider position. | [
"Return",
"the",
"current",
"fractional",
"values",
"(",
"upper",
"and",
"lower",
"end",
")",
"of",
"the",
"slider",
"position",
"."
] | def get(self):
"""Return the current fractional values (upper and lower end)
of the slider position."""
return self._getdoubles(self.tk.call(self._w, 'get')) | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getdoubles",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'get'",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2853-L2856 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | .ci/openvino-onnx/watchdog/src/git_wrapper.py | python | GitWrapper._get_pull_requests | (self) | return self.git.get_organization(self.repository).get_repo(self.project).get_pulls() | Private method retrieving pull requests from GitHub.
:return: Paginated list of Pull Requests in GitHub repo
:rtype: github.PaginatedList.PaginatedList of github.PullRequest.PullRequest | Private method retrieving pull requests from GitHub. | [
"Private",
"method",
"retrieving",
"pull",
"requests",
"from",
"GitHub",
"."
] | def _get_pull_requests(self):
"""Private method retrieving pull requests from GitHub.
:return: Paginated list of Pull Requests in GitHub repo
:rtype: github.PaginatedList.PaginatedList of github.PullRequest.PullRequest
"""
return self.git.get_organization(self.repository).get_repo(self.project).get_pulls() | [
"def",
"_get_pull_requests",
"(",
"self",
")",
":",
"return",
"self",
".",
"git",
".",
"get_organization",
"(",
"self",
".",
"repository",
")",
".",
"get_repo",
"(",
"self",
".",
"project",
")",
".",
"get_pulls",
"(",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/.ci/openvino-onnx/watchdog/src/git_wrapper.py#L91-L97 | |
shogun-toolbox/shogun | 9b8d856971af5a295dd6ad70623ae45647a6334c | examples/meta/generator/parse.py | python | FastParser.p_float | (self, p) | float : FLOATLITERAL | float : FLOATLITERAL | [
"float",
":",
"FLOATLITERAL"
] | def p_float(self, p):
"float : FLOATLITERAL"
p[0] = {"FloatLiteral": p[1][:-1]} | [
"def",
"p_float",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"{",
"\"FloatLiteral\"",
":",
"p",
"[",
"1",
"]",
"[",
":",
"-",
"1",
"]",
"}"
] | https://github.com/shogun-toolbox/shogun/blob/9b8d856971af5a295dd6ad70623ae45647a6334c/examples/meta/generator/parse.py#L276-L278 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/tensor_array_ops.py | python | TensorArray.flow | (self) | return self._flow | The flow `Tensor` forcing ops leading to this TensorArray state. | The flow `Tensor` forcing ops leading to this TensorArray state. | [
"The",
"flow",
"Tensor",
"forcing",
"ops",
"leading",
"to",
"this",
"TensorArray",
"state",
"."
] | def flow(self):
"""The flow `Tensor` forcing ops leading to this TensorArray state."""
return self._flow | [
"def",
"flow",
"(",
"self",
")",
":",
"return",
"self",
".",
"_flow"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/tensor_array_ops.py#L150-L152 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/variables.py | python | local_variables | (scope=None) | return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES, scope) | Returns local variables.
Local variables - per process variables, usually not saved/restored to
checkpoint and used for temporary or intermediate values.
For example, they can be used as counters for metrics computation or
number of epochs this machine has read data.
The `tf.contrib.framework.local_variable()` function automatically adds the
new variable to `GraphKeys.LOCAL_VARIABLES`.
This convenience function returns the contents of that collection.
An alternative to local variables are global variables. See
`tf.compat.v1.global_variables`
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered to
include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a scope
is supplied. The choice of `re.match` means that a `scope` without special
tokens filters by prefix.
Returns:
A list of local `Variable` objects. | Returns local variables. | [
"Returns",
"local",
"variables",
"."
] | def local_variables(scope=None):
"""Returns local variables.
Local variables - per process variables, usually not saved/restored to
checkpoint and used for temporary or intermediate values.
For example, they can be used as counters for metrics computation or
number of epochs this machine has read data.
The `tf.contrib.framework.local_variable()` function automatically adds the
new variable to `GraphKeys.LOCAL_VARIABLES`.
This convenience function returns the contents of that collection.
An alternative to local variables are global variables. See
`tf.compat.v1.global_variables`
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered to
include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a scope
is supplied. The choice of `re.match` means that a `scope` without special
tokens filters by prefix.
Returns:
A list of local `Variable` objects.
"""
return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES, scope) | [
"def",
"local_variables",
"(",
"scope",
"=",
"None",
")",
":",
"return",
"ops",
".",
"get_collection",
"(",
"ops",
".",
"GraphKeys",
".",
"LOCAL_VARIABLES",
",",
"scope",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/variables.py#L3164-L3188 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/kernels/transpose.py | python | transpose | (a, b=None) | return b | Compute the transpose of 'a' and store it into 'b', if given,
and return it. If 'b' is not given, allocate a new array
and return that.
This implements the algorithm documented in
http://devblogs.nvidia.com/parallelforall/efficient-matrix-transpose-cuda-cc/
:param a: an `np.ndarray` or a `DeviceNDArrayBase` subclass. If already on
the device its stream will be used to perform the transpose (and to copy
`b` to the device if necessary). | Compute the transpose of 'a' and store it into 'b', if given,
and return it. If 'b' is not given, allocate a new array
and return that. | [
"Compute",
"the",
"transpose",
"of",
"a",
"and",
"store",
"it",
"into",
"b",
"if",
"given",
"and",
"return",
"it",
".",
"If",
"b",
"is",
"not",
"given",
"allocate",
"a",
"new",
"array",
"and",
"return",
"that",
"."
] | def transpose(a, b=None):
"""Compute the transpose of 'a' and store it into 'b', if given,
and return it. If 'b' is not given, allocate a new array
and return that.
This implements the algorithm documented in
http://devblogs.nvidia.com/parallelforall/efficient-matrix-transpose-cuda-cc/
:param a: an `np.ndarray` or a `DeviceNDArrayBase` subclass. If already on
the device its stream will be used to perform the transpose (and to copy
`b` to the device if necessary).
"""
# prefer `a`'s stream if
stream = getattr(a, 'stream', 0)
if not b:
cols, rows = a.shape
strides = a.dtype.itemsize * cols, a.dtype.itemsize
b = cuda.cudadrv.devicearray.DeviceNDArray(
(rows, cols),
strides,
dtype=a.dtype,
stream=stream)
dt=nps.from_dtype(a.dtype)
tpb = driver.get_device().MAX_THREADS_PER_BLOCK
# we need to factor available threads into x and y axis
tile_width = int(math.pow(2, math.log(tpb, 2)/2))
tile_height = int(tpb / tile_width)
tile_shape=(tile_height, tile_width + 1)
@cuda.jit
def kernel(input, output):
tile = cuda.shared.array(shape=tile_shape, dtype=dt)
tx = cuda.threadIdx.x
ty = cuda.threadIdx.y
bx = cuda.blockIdx.x * cuda.blockDim.x
by = cuda.blockIdx.y * cuda.blockDim.y
x = by + tx
y = bx + ty
if by+ty < input.shape[0] and bx+tx < input.shape[1]:
tile[ty, tx] = input[by+ty, bx+tx]
cuda.syncthreads()
if y < output.shape[0] and x < output.shape[1]:
output[y, x] = tile[tx, ty]
# one block per tile, plus one for remainders
blocks = int(b.shape[0]/tile_height + 1), int(b.shape[1]/tile_width + 1)
# one thread per tile element
threads = tile_height, tile_width
kernel[blocks, threads, stream](a, b)
return b | [
"def",
"transpose",
"(",
"a",
",",
"b",
"=",
"None",
")",
":",
"# prefer `a`'s stream if",
"stream",
"=",
"getattr",
"(",
"a",
",",
"'stream'",
",",
"0",
")",
"if",
"not",
"b",
":",
"cols",
",",
"rows",
"=",
"a",
".",
"shape",
"strides",
"=",
"a",
".",
"dtype",
".",
"itemsize",
"*",
"cols",
",",
"a",
".",
"dtype",
".",
"itemsize",
"b",
"=",
"cuda",
".",
"cudadrv",
".",
"devicearray",
".",
"DeviceNDArray",
"(",
"(",
"rows",
",",
"cols",
")",
",",
"strides",
",",
"dtype",
"=",
"a",
".",
"dtype",
",",
"stream",
"=",
"stream",
")",
"dt",
"=",
"nps",
".",
"from_dtype",
"(",
"a",
".",
"dtype",
")",
"tpb",
"=",
"driver",
".",
"get_device",
"(",
")",
".",
"MAX_THREADS_PER_BLOCK",
"# we need to factor available threads into x and y axis",
"tile_width",
"=",
"int",
"(",
"math",
".",
"pow",
"(",
"2",
",",
"math",
".",
"log",
"(",
"tpb",
",",
"2",
")",
"/",
"2",
")",
")",
"tile_height",
"=",
"int",
"(",
"tpb",
"/",
"tile_width",
")",
"tile_shape",
"=",
"(",
"tile_height",
",",
"tile_width",
"+",
"1",
")",
"@",
"cuda",
".",
"jit",
"def",
"kernel",
"(",
"input",
",",
"output",
")",
":",
"tile",
"=",
"cuda",
".",
"shared",
".",
"array",
"(",
"shape",
"=",
"tile_shape",
",",
"dtype",
"=",
"dt",
")",
"tx",
"=",
"cuda",
".",
"threadIdx",
".",
"x",
"ty",
"=",
"cuda",
".",
"threadIdx",
".",
"y",
"bx",
"=",
"cuda",
".",
"blockIdx",
".",
"x",
"*",
"cuda",
".",
"blockDim",
".",
"x",
"by",
"=",
"cuda",
".",
"blockIdx",
".",
"y",
"*",
"cuda",
".",
"blockDim",
".",
"y",
"x",
"=",
"by",
"+",
"tx",
"y",
"=",
"bx",
"+",
"ty",
"if",
"by",
"+",
"ty",
"<",
"input",
".",
"shape",
"[",
"0",
"]",
"and",
"bx",
"+",
"tx",
"<",
"input",
".",
"shape",
"[",
"1",
"]",
":",
"tile",
"[",
"ty",
",",
"tx",
"]",
"=",
"input",
"[",
"by",
"+",
"ty",
",",
"bx",
"+",
"tx",
"]",
"cuda",
".",
"syncthreads",
"(",
")",
"if",
"y",
"<",
"output",
".",
"shape",
"[",
"0",
"]",
"and",
"x",
"<",
"output",
".",
"shape",
"[",
"1",
"]",
":",
"output",
"[",
"y",
",",
"x",
"]",
"=",
"tile",
"[",
"tx",
",",
"ty",
"]",
"# one block per tile, plus one for remainders",
"blocks",
"=",
"int",
"(",
"b",
".",
"shape",
"[",
"0",
"]",
"/",
"tile_height",
"+",
"1",
")",
",",
"int",
"(",
"b",
".",
"shape",
"[",
"1",
"]",
"/",
"tile_width",
"+",
"1",
")",
"# one thread per tile element",
"threads",
"=",
"tile_height",
",",
"tile_width",
"kernel",
"[",
"blocks",
",",
"threads",
",",
"stream",
"]",
"(",
"a",
",",
"b",
")",
"return",
"b"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/kernels/transpose.py#L6-L65 | |
tinyobjloader/tinyobjloader | 8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93 | deps/cpplint.py | python | CheckParenthesisSpacing | (filename, clean_lines, linenum, error) | Checks for horizontal spacing around parentheses.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for horizontal spacing around parentheses. | [
"Checks",
"for",
"horizontal",
"spacing",
"around",
"parentheses",
"."
] | def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing around parentheses.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# No spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1)) | [
"def",
"CheckParenthesisSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# No spaces after an if, while, switch, or for",
"match",
"=",
"Search",
"(",
"r' (if\\(|for\\(|while\\(|switch\\()'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"5",
",",
"'Missing space before ( in %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# For if/for/while/switch, the left and right parens should be",
"# consistent about how many spaces are inside the parens, and",
"# there should either be zero or one spaces inside the parens.",
"# We don't want: \"if ( foo)\" or \"if ( foo )\".",
"# Exception: \"for ( ; foo; bar)\" and \"for (foo; bar; )\" are allowed.",
"match",
"=",
"Search",
"(",
"r'\\b(if|for|while|switch)\\s*'",
"r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$'",
",",
"line",
")",
"if",
"match",
":",
"if",
"len",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"!=",
"len",
"(",
"match",
".",
"group",
"(",
"4",
")",
")",
":",
"if",
"not",
"(",
"match",
".",
"group",
"(",
"3",
")",
"==",
"';'",
"and",
"len",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"==",
"1",
"+",
"len",
"(",
"match",
".",
"group",
"(",
"4",
")",
")",
"or",
"not",
"match",
".",
"group",
"(",
"2",
")",
"and",
"Search",
"(",
"r'\\bfor\\s*\\(.*; \\)'",
",",
"line",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"5",
",",
"'Mismatching spaces inside () in %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"if",
"len",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"not",
"in",
"[",
"0",
",",
"1",
"]",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"5",
",",
"'Should have zero or one spaces inside ( and ) in %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")"
] | https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L3242-L3277 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ntpath.py | python | basename | (p) | return split(p)[1] | Returns the final component of a pathname | Returns the final component of a pathname | [
"Returns",
"the",
"final",
"component",
"of",
"a",
"pathname"
] | def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1] | [
"def",
"basename",
"(",
"p",
")",
":",
"return",
"split",
"(",
"p",
")",
"[",
"1",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ntpath.py#L212-L214 | |
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | doorbell/python/iot_doorbell/hardware/grove.py | python | GroveBoard.detect_touch | (self) | return self.touch.isPressed() | Detect touch state. | Detect touch state. | [
"Detect",
"touch",
"state",
"."
] | def detect_touch(self):
"""
Detect touch state.
"""
return self.touch.isPressed() | [
"def",
"detect_touch",
"(",
"self",
")",
":",
"return",
"self",
".",
"touch",
".",
"isPressed",
"(",
")"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/doorbell/python/iot_doorbell/hardware/grove.py#L78-L84 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py | python | SinglePtIntegrationTable.set_peak_height | (self, scan_number, pt_number, peak_height, roi_name) | return | set the intensity of single measurement from the counts on the detector.
In the view as 3D peak, it is the cut on the center plane as the peak shape can be modeled by 3D Gaussian.
Thus the integrated value is used as the Gaussian's height.
:param scan_number:
:param pt_number:
:param peak_height:
:param roi_name: ROI is closed related to how a peak/single measurement's intensity is calculated
:return: | set the intensity of single measurement from the counts on the detector.
In the view as 3D peak, it is the cut on the center plane as the peak shape can be modeled by 3D Gaussian.
Thus the integrated value is used as the Gaussian's height.
:param scan_number:
:param pt_number:
:param peak_height:
:param roi_name: ROI is closed related to how a peak/single measurement's intensity is calculated
:return: | [
"set",
"the",
"intensity",
"of",
"single",
"measurement",
"from",
"the",
"counts",
"on",
"the",
"detector",
".",
"In",
"the",
"view",
"as",
"3D",
"peak",
"it",
"is",
"the",
"cut",
"on",
"the",
"center",
"plane",
"as",
"the",
"peak",
"shape",
"can",
"be",
"modeled",
"by",
"3D",
"Gaussian",
".",
"Thus",
"the",
"integrated",
"value",
"is",
"used",
"as",
"the",
"Gaussian",
"s",
"height",
".",
":",
"param",
"scan_number",
":",
":",
"param",
"pt_number",
":",
":",
"param",
"peak_height",
":",
":",
"param",
"roi_name",
":",
"ROI",
"is",
"closed",
"related",
"to",
"how",
"a",
"peak",
"/",
"single",
"measurement",
"s",
"intensity",
"is",
"calculated",
":",
"return",
":"
] | def set_peak_height(self, scan_number, pt_number, peak_height, roi_name):
""" set the intensity of single measurement from the counts on the detector.
In the view as 3D peak, it is the cut on the center plane as the peak shape can be modeled by 3D Gaussian.
Thus the integrated value is used as the Gaussian's height.
:param scan_number:
:param pt_number:
:param peak_height:
:param roi_name: ROI is closed related to how a peak/single measurement's intensity is calculated
:return:
"""
row_number = self._pt_row_dict[scan_number, pt_number]
self.update_cell_value(row_number, self._height_index, peak_height)
self.update_cell_value(row_number, self._roi_index, roi_name)
return | [
"def",
"set_peak_height",
"(",
"self",
",",
"scan_number",
",",
"pt_number",
",",
"peak_height",
",",
"roi_name",
")",
":",
"row_number",
"=",
"self",
".",
"_pt_row_dict",
"[",
"scan_number",
",",
"pt_number",
"]",
"self",
".",
"update_cell_value",
"(",
"row_number",
",",
"self",
".",
"_height_index",
",",
"peak_height",
")",
"self",
".",
"update_cell_value",
"(",
"row_number",
",",
"self",
".",
"_roi_index",
",",
"roi_name",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L1650-L1665 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | MacPrefixHeader.GetInclude | (self, lang, arch=None) | Gets the cflags to include the prefix header for language |lang|. | Gets the cflags to include the prefix header for language |lang|. | [
"Gets",
"the",
"cflags",
"to",
"include",
"the",
"prefix",
"header",
"for",
"language",
"|lang|",
"."
] | def GetInclude(self, lang, arch=None):
"""Gets the cflags to include the prefix header for language |lang|."""
if self.compile_headers and lang in self.compiled_headers:
return "-include %s" % self._CompiledHeader(lang, arch)
elif self.header:
return "-include %s" % self.header
else:
return "" | [
"def",
"GetInclude",
"(",
"self",
",",
"lang",
",",
"arch",
"=",
"None",
")",
":",
"if",
"self",
".",
"compile_headers",
"and",
"lang",
"in",
"self",
".",
"compiled_headers",
":",
"return",
"\"-include %s\"",
"%",
"self",
".",
"_CompiledHeader",
"(",
"lang",
",",
"arch",
")",
"elif",
"self",
".",
"header",
":",
"return",
"\"-include %s\"",
"%",
"self",
".",
"header",
"else",
":",
"return",
"\"\""
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L1435-L1442 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/ops.py | python | _assert_same_graph | (original_item, item) | Fail if the 2 items are from different graphs.
Args:
original_item: Original item to check against.
item: Item to check.
Raises:
ValueError: if graphs do not match. | Fail if the 2 items are from different graphs. | [
"Fail",
"if",
"the",
"2",
"items",
"are",
"from",
"different",
"graphs",
"."
] | def _assert_same_graph(original_item, item):
"""Fail if the 2 items are from different graphs.
Args:
original_item: Original item to check against.
item: Item to check.
Raises:
ValueError: if graphs do not match.
"""
if original_item.graph is not item.graph:
raise ValueError(
"%s must be from the same graph as %s." % (item, original_item)) | [
"def",
"_assert_same_graph",
"(",
"original_item",
",",
"item",
")",
":",
"if",
"original_item",
".",
"graph",
"is",
"not",
"item",
".",
"graph",
":",
"raise",
"ValueError",
"(",
"\"%s must be from the same graph as %s.\"",
"%",
"(",
"item",
",",
"original_item",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L3754-L3766 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.update_node_aux_icon | (self, tree_iter) | Set Aux Icon to node | Set Aux Icon to node | [
"Set",
"Aux",
"Icon",
"to",
"node"
] | def update_node_aux_icon(self, tree_iter):
"""Set Aux Icon to node"""
node_id = self.get_node_id_from_tree_iter(tree_iter)
is_bookmarked = str(node_id) in self.bookmarks
is_ro = self.get_node_read_only(tree_iter)
if is_bookmarked and is_ro:
stock_id = "lockpin"
elif is_bookmarked:
stock_id = "pin"
elif is_ro:
stock_id = "locked"
else:
stock_id = None
self.treestore[tree_iter][8] = stock_id | [
"def",
"update_node_aux_icon",
"(",
"self",
",",
"tree_iter",
")",
":",
"node_id",
"=",
"self",
".",
"get_node_id_from_tree_iter",
"(",
"tree_iter",
")",
"is_bookmarked",
"=",
"str",
"(",
"node_id",
")",
"in",
"self",
".",
"bookmarks",
"is_ro",
"=",
"self",
".",
"get_node_read_only",
"(",
"tree_iter",
")",
"if",
"is_bookmarked",
"and",
"is_ro",
":",
"stock_id",
"=",
"\"lockpin\"",
"elif",
"is_bookmarked",
":",
"stock_id",
"=",
"\"pin\"",
"elif",
"is_ro",
":",
"stock_id",
"=",
"\"locked\"",
"else",
":",
"stock_id",
"=",
"None",
"self",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"8",
"]",
"=",
"stock_id"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L5199-L5212 | ||
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | python/pyarrow/types.py | python | is_duration | (t) | return t.id == lib.Type_DURATION | Return True if value is an instance of a duration type.
Parameters
----------
t : DataType | Return True if value is an instance of a duration type. | [
"Return",
"True",
"if",
"value",
"is",
"an",
"instance",
"of",
"a",
"duration",
"type",
"."
] | def is_duration(t):
"""
Return True if value is an instance of a duration type.
Parameters
----------
t : DataType
"""
return t.id == lib.Type_DURATION | [
"def",
"is_duration",
"(",
"t",
")",
":",
"return",
"t",
".",
"id",
"==",
"lib",
".",
"Type_DURATION"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/types.py#L321-L329 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_gym_env_example.py | python | ResetPoseExample | (log_path=None) | An example that the minitaur stands still using the reset pose. | An example that the minitaur stands still using the reset pose. | [
"An",
"example",
"that",
"the",
"minitaur",
"stands",
"still",
"using",
"the",
"reset",
"pose",
"."
] | def ResetPoseExample(log_path=None):
"""An example that the minitaur stands still using the reset pose."""
steps = 10000
environment = minitaur_gym_env.MinitaurGymEnv(
urdf_version=minitaur_gym_env.DERPY_V0_URDF_VERSION,
render=True,
leg_model_enabled=False,
motor_velocity_limit=np.inf,
pd_control_enabled=True,
accurate_motor_model_enabled=True,
motor_overheat_protection=True,
hard_reset=False,
log_path=log_path)
action = [math.pi / 2] * 8
for _ in range(steps):
_, _, done, _ = environment.step(action)
time.sleep(1. / 100.)
if done:
break | [
"def",
"ResetPoseExample",
"(",
"log_path",
"=",
"None",
")",
":",
"steps",
"=",
"10000",
"environment",
"=",
"minitaur_gym_env",
".",
"MinitaurGymEnv",
"(",
"urdf_version",
"=",
"minitaur_gym_env",
".",
"DERPY_V0_URDF_VERSION",
",",
"render",
"=",
"True",
",",
"leg_model_enabled",
"=",
"False",
",",
"motor_velocity_limit",
"=",
"np",
".",
"inf",
",",
"pd_control_enabled",
"=",
"True",
",",
"accurate_motor_model_enabled",
"=",
"True",
",",
"motor_overheat_protection",
"=",
"True",
",",
"hard_reset",
"=",
"False",
",",
"log_path",
"=",
"log_path",
")",
"action",
"=",
"[",
"math",
".",
"pi",
"/",
"2",
"]",
"*",
"8",
"for",
"_",
"in",
"range",
"(",
"steps",
")",
":",
"_",
",",
"_",
",",
"done",
",",
"_",
"=",
"environment",
".",
"step",
"(",
"action",
")",
"time",
".",
"sleep",
"(",
"1.",
"/",
"100.",
")",
"if",
"done",
":",
"break"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_gym_env_example.py#L46-L64 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/Interactive.py | python | SConsInteractiveCmd.do_shell | (self, argv) | \
shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and
'!' are synonyms. | \
shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and
'!' are synonyms. | [
"\\",
"shell",
"[",
"COMMANDLINE",
"]",
"Execute",
"COMMANDLINE",
"in",
"a",
"subshell",
".",
"sh",
"and",
"!",
"are",
"synonyms",
"."
] | def do_shell(self, argv):
"""\
shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and
'!' are synonyms.
"""
import subprocess
argv = argv[1:]
if not argv:
argv = os.environ[self.shell_variable]
try:
# Per "[Python-Dev] subprocess insufficiently platform-independent?"
# http://mail.python.org/pipermail/python-dev/2008-August/081979.html "+
# Doing the right thing with an argument list currently
# requires different shell= values on Windows and Linux.
p = subprocess.Popen(argv, shell=(sys.platform=='win32'))
except EnvironmentError, e:
sys.stderr.write('scons: %s: %s\n' % (argv[0], e.strerror))
else:
p.wait() | [
"def",
"do_shell",
"(",
"self",
",",
"argv",
")",
":",
"import",
"subprocess",
"argv",
"=",
"argv",
"[",
"1",
":",
"]",
"if",
"not",
"argv",
":",
"argv",
"=",
"os",
".",
"environ",
"[",
"self",
".",
"shell_variable",
"]",
"try",
":",
"# Per \"[Python-Dev] subprocess insufficiently platform-independent?\"",
"# http://mail.python.org/pipermail/python-dev/2008-August/081979.html \"+",
"# Doing the right thing with an argument list currently",
"# requires different shell= values on Windows and Linux.",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"argv",
",",
"shell",
"=",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
")",
"except",
"EnvironmentError",
",",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'scons: %s: %s\\n'",
"%",
"(",
"argv",
"[",
"0",
"]",
",",
"e",
".",
"strerror",
")",
")",
"else",
":",
"p",
".",
"wait",
"(",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/Interactive.py#L339-L357 | ||
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/text_format.py | python | Tokenizer.ConsumeIdentifierOrNumber | (self) | return result | Consumes protocol message field identifier.
Returns:
Identifier string.
Raises:
ParseError: If an identifier couldn't be consumed. | Consumes protocol message field identifier. | [
"Consumes",
"protocol",
"message",
"field",
"identifier",
"."
] | def ConsumeIdentifierOrNumber(self):
"""Consumes protocol message field identifier.
Returns:
Identifier string.
Raises:
ParseError: If an identifier couldn't be consumed.
"""
result = self.token
if not self._IDENTIFIER_OR_NUMBER.match(result):
raise self.ParseError('Expected identifier or number, got %s.' % result)
self.NextToken()
return result | [
"def",
"ConsumeIdentifierOrNumber",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"token",
"if",
"not",
"self",
".",
"_IDENTIFIER_OR_NUMBER",
".",
"match",
"(",
"result",
")",
":",
"raise",
"self",
".",
"ParseError",
"(",
"'Expected identifier or number, got %s.'",
"%",
"result",
")",
"self",
".",
"NextToken",
"(",
")",
"return",
"result"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/text_format.py#L1368-L1381 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | addon-sdk/source/python-lib/mozrunner/__init__.py | python | Profile.clean_addons | (self) | Cleans up addons in the profile. | Cleans up addons in the profile. | [
"Cleans",
"up",
"addons",
"in",
"the",
"profile",
"."
] | def clean_addons(self):
"""Cleans up addons in the profile."""
for addon in self.addons_installed:
if os.path.isdir(addon):
rmtree(addon) | [
"def",
"clean_addons",
"(",
"self",
")",
":",
"for",
"addon",
"in",
"self",
".",
"addons_installed",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"addon",
")",
":",
"rmtree",
"(",
"addon",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/addon-sdk/source/python-lib/mozrunner/__init__.py#L298-L302 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/dataview.py | python | DataViewIndexListModel.Reset | (*args, **kwargs) | return _dataview.DataViewIndexListModel_Reset(*args, **kwargs) | Reset(self, unsigned int new_size)
Call this if the data has to be read again from the model. This is
useful after major changes when calling methods like `RowChanged` or
`RowDeleted` (possibly thousands of times) doesn't make sense. | Reset(self, unsigned int new_size) | [
"Reset",
"(",
"self",
"unsigned",
"int",
"new_size",
")"
] | def Reset(*args, **kwargs):
"""
Reset(self, unsigned int new_size)
Call this if the data has to be read again from the model. This is
useful after major changes when calling methods like `RowChanged` or
`RowDeleted` (possibly thousands of times) doesn't make sense.
"""
return _dataview.DataViewIndexListModel_Reset(*args, **kwargs) | [
"def",
"Reset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewIndexListModel_Reset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L900-L908 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/examples/imagenet_trainer.py | python | AddNullInput | (model, reader, batch_size, img_size, dtype) | The null input function uses a gaussian fill operator to emulate real image
input. A label blob is hardcoded to a single value. This is useful if you
want to test compute throughput or don't have a dataset available. | The null input function uses a gaussian fill operator to emulate real image
input. A label blob is hardcoded to a single value. This is useful if you
want to test compute throughput or don't have a dataset available. | [
"The",
"null",
"input",
"function",
"uses",
"a",
"gaussian",
"fill",
"operator",
"to",
"emulate",
"real",
"image",
"input",
".",
"A",
"label",
"blob",
"is",
"hardcoded",
"to",
"a",
"single",
"value",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"test",
"compute",
"throughput",
"or",
"don",
"t",
"have",
"a",
"dataset",
"available",
"."
] | def AddNullInput(model, reader, batch_size, img_size, dtype):
'''
The null input function uses a gaussian fill operator to emulate real image
input. A label blob is hardcoded to a single value. This is useful if you
want to test compute throughput or don't have a dataset available.
'''
suffix = "_fp16" if dtype == "float16" else ""
model.param_init_net.GaussianFill(
[],
["data" + suffix],
shape=[batch_size, 3, img_size, img_size],
)
if dtype == "float16":
model.param_init_net.FloatToHalf("data" + suffix, "data")
model.param_init_net.ConstantFill(
[],
["label"],
shape=[batch_size],
value=1,
dtype=core.DataType.INT32,
) | [
"def",
"AddNullInput",
"(",
"model",
",",
"reader",
",",
"batch_size",
",",
"img_size",
",",
"dtype",
")",
":",
"suffix",
"=",
"\"_fp16\"",
"if",
"dtype",
"==",
"\"float16\"",
"else",
"\"\"",
"model",
".",
"param_init_net",
".",
"GaussianFill",
"(",
"[",
"]",
",",
"[",
"\"data\"",
"+",
"suffix",
"]",
",",
"shape",
"=",
"[",
"batch_size",
",",
"3",
",",
"img_size",
",",
"img_size",
"]",
",",
")",
"if",
"dtype",
"==",
"\"float16\"",
":",
"model",
".",
"param_init_net",
".",
"FloatToHalf",
"(",
"\"data\"",
"+",
"suffix",
",",
"\"data\"",
")",
"model",
".",
"param_init_net",
".",
"ConstantFill",
"(",
"[",
"]",
",",
"[",
"\"label\"",
"]",
",",
"shape",
"=",
"[",
"batch_size",
"]",
",",
"value",
"=",
"1",
",",
"dtype",
"=",
"core",
".",
"DataType",
".",
"INT32",
",",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/examples/imagenet_trainer.py#L82-L103 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/debug/cli/command_parser.py | python | parse_indices | (indices_string) | return [int(element) for element in indices_string.split(",")] | Parse a string representing indices.
For example, if the input is "[1, 2, 3]", the return value will be a list of
indices: [1, 2, 3]
Args:
indices_string: (str) a string representing indices. Can optionally be
surrounded by a pair of brackets.
Returns:
(list of int): Parsed indices. | Parse a string representing indices. | [
"Parse",
"a",
"string",
"representing",
"indices",
"."
] | def parse_indices(indices_string):
"""Parse a string representing indices.
For example, if the input is "[1, 2, 3]", the return value will be a list of
indices: [1, 2, 3]
Args:
indices_string: (str) a string representing indices. Can optionally be
surrounded by a pair of brackets.
Returns:
(list of int): Parsed indices.
"""
# Strip whitespace.
indices_string = re.sub(r"\s+", "", indices_string)
# Strip any brackets at the two ends.
if indices_string.startswith("[") and indices_string.endswith("]"):
indices_string = indices_string[1:-1]
return [int(element) for element in indices_string.split(",")] | [
"def",
"parse_indices",
"(",
"indices_string",
")",
":",
"# Strip whitespace.",
"indices_string",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\"\"",
",",
"indices_string",
")",
"# Strip any brackets at the two ends.",
"if",
"indices_string",
".",
"startswith",
"(",
"\"[\"",
")",
"and",
"indices_string",
".",
"endswith",
"(",
"\"]\"",
")",
":",
"indices_string",
"=",
"indices_string",
"[",
"1",
":",
"-",
"1",
"]",
"return",
"[",
"int",
"(",
"element",
")",
"for",
"element",
"in",
"indices_string",
".",
"split",
"(",
"\",\"",
")",
"]"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/command_parser.py#L219-L240 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.WriteMacBundleResources | (self, resources, bundle_depends) | Writes ninja edges for 'mac_bundle_resources'. | Writes ninja edges for 'mac_bundle_resources'. | [
"Writes",
"ninja",
"edges",
"for",
"mac_bundle_resources",
"."
] | def WriteMacBundleResources(self, resources, bundle_depends):
"""Writes ninja edges for 'mac_bundle_resources'."""
for output, res in gyp.xcode_emulation.GetMacBundleResources(
self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']),
self.xcode_settings, map(self.GypPathToNinja, resources)):
self.ninja.build(output, 'mac_tool', res,
variables=[('mactool_cmd', 'copy-bundle-resource')])
bundle_depends.append(output) | [
"def",
"WriteMacBundleResources",
"(",
"self",
",",
"resources",
",",
"bundle_depends",
")",
":",
"for",
"output",
",",
"res",
"in",
"gyp",
".",
"xcode_emulation",
".",
"GetMacBundleResources",
"(",
"self",
".",
"ExpandSpecial",
"(",
"generator_default_variables",
"[",
"'PRODUCT_DIR'",
"]",
")",
",",
"self",
".",
"xcode_settings",
",",
"map",
"(",
"self",
".",
"GypPathToNinja",
",",
"resources",
")",
")",
":",
"self",
".",
"ninja",
".",
"build",
"(",
"output",
",",
"'mac_tool'",
",",
"res",
",",
"variables",
"=",
"[",
"(",
"'mactool_cmd'",
",",
"'copy-bundle-resource'",
")",
"]",
")",
"bundle_depends",
".",
"append",
"(",
"output",
")"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/generator/ninja.py#L677-L684 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/_vendor/packaging/tags.py | python | sys_tags | (*, warn: bool = False) | Returns the sequence of tag triples for the running interpreter.
The order of the sequence corresponds to priority order for the
interpreter, from most to least important. | Returns the sequence of tag triples for the running interpreter. | [
"Returns",
"the",
"sequence",
"of",
"tag",
"triples",
"for",
"the",
"running",
"interpreter",
"."
] | def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
"""
Returns the sequence of tag triples for the running interpreter.
The order of the sequence corresponds to priority order for the
interpreter, from most to least important.
"""
interp_name = interpreter_name()
if interp_name == "cp":
yield from cpython_tags(warn=warn)
else:
yield from generic_tags()
yield from compatible_tags() | [
"def",
"sys_tags",
"(",
"*",
",",
"warn",
":",
"bool",
"=",
"False",
")",
"->",
"Iterator",
"[",
"Tag",
"]",
":",
"interp_name",
"=",
"interpreter_name",
"(",
")",
"if",
"interp_name",
"==",
"\"cp\"",
":",
"yield",
"from",
"cpython_tags",
"(",
"warn",
"=",
"warn",
")",
"else",
":",
"yield",
"from",
"generic_tags",
"(",
")",
"yield",
"from",
"compatible_tags",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/packaging/tags.py#L470-L484 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py | python | HashedCategoricalColumn.name | (self) | return self.key | See `FeatureColumn` base class. | See `FeatureColumn` base class. | [
"See",
"FeatureColumn",
"base",
"class",
"."
] | def name(self):
"""See `FeatureColumn` base class."""
return self.key | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"key"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L3467-L3469 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py | python | TypeRef.name | (self) | return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) | Get type name | Get type name | [
"Get",
"type",
"name"
] | def name(self):
"""
Get type name
"""
return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"ffi",
".",
"ret_string",
"(",
"ffi",
".",
"lib",
".",
"LLVMPY_GetTypeName",
"(",
"self",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py#L50-L54 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py | python | calldef_t.overloads | (self) | return self.parent.calldefs(
name=self.name,
function=lambda decl: decl is not self,
allow_empty=True,
recursive=False) | A list of overloaded "callables" (i.e. other callables with the
same name within the same scope.
@type: list of :class:`calldef_t` | A list of overloaded "callables" (i.e. other callables with the
same name within the same scope. | [
"A",
"list",
"of",
"overloaded",
"callables",
"(",
"i",
".",
"e",
".",
"other",
"callables",
"with",
"the",
"same",
"name",
"within",
"the",
"same",
"scope",
"."
] | def overloads(self):
"""A list of overloaded "callables" (i.e. other callables with the
same name within the same scope.
@type: list of :class:`calldef_t`
"""
if not self.parent:
return []
# finding all functions with the same name
return self.parent.calldefs(
name=self.name,
function=lambda decl: decl is not self,
allow_empty=True,
recursive=False) | [
"def",
"overloads",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"[",
"]",
"# finding all functions with the same name",
"return",
"self",
".",
"parent",
".",
"calldefs",
"(",
"name",
"=",
"self",
".",
"name",
",",
"function",
"=",
"lambda",
"decl",
":",
"decl",
"is",
"not",
"self",
",",
"allow_empty",
"=",
"True",
",",
"recursive",
"=",
"False",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py#L278-L291 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.py | python | _is_cert | (item) | return CoreFoundation.CFGetTypeID(item) == expected | Returns True if a given CFTypeRef is a certificate. | Returns True if a given CFTypeRef is a certificate. | [
"Returns",
"True",
"if",
"a",
"given",
"CFTypeRef",
"is",
"a",
"certificate",
"."
] | def _is_cert(item):
"""
Returns True if a given CFTypeRef is a certificate.
"""
expected = Security.SecCertificateGetTypeID()
return CoreFoundation.CFGetTypeID(item) == expected | [
"def",
"_is_cert",
"(",
"item",
")",
":",
"expected",
"=",
"Security",
".",
"SecCertificateGetTypeID",
"(",
")",
"return",
"CoreFoundation",
".",
"CFGetTypeID",
"(",
"item",
")",
"==",
"expected"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.py#L195-L200 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/trajectory.py | python | SE3Trajectory.to_se3 | (self,state) | return (state[:9],state[9:]) | Converts a state parameter vector to a klampt.se3 element | Converts a state parameter vector to a klampt.se3 element | [
"Converts",
"a",
"state",
"parameter",
"vector",
"to",
"a",
"klampt",
".",
"se3",
"element"
] | def to_se3(self,state):
"""Converts a state parameter vector to a klampt.se3 element"""
return (state[:9],state[9:]) | [
"def",
"to_se3",
"(",
"self",
",",
"state",
")",
":",
"return",
"(",
"state",
"[",
":",
"9",
"]",
",",
"state",
"[",
"9",
":",
"]",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L682-L684 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py | python | DependencyGraphNode._LinkDependenciesInternal | (self, targets, include_shared_libraries,
dependencies=None, initial=True) | return dependencies | Returns an OrderedSet of dependency targets that are linked
into this target.
This function has a split personality, depending on the setting of
|initial|. Outside callers should always leave |initial| at its default
setting.
When adding a target to the list of dependencies, this function will
recurse into itself with |initial| set to False, to collect dependencies
that are linked into the linkable target for which the list is being built.
If |include_shared_libraries| is False, the resulting dependencies will not
include shared_library targets that are linked into this target. | Returns an OrderedSet of dependency targets that are linked
into this target. | [
"Returns",
"an",
"OrderedSet",
"of",
"dependency",
"targets",
"that",
"are",
"linked",
"into",
"this",
"target",
"."
] | def _LinkDependenciesInternal(self, targets, include_shared_libraries,
dependencies=None, initial=True):
"""Returns an OrderedSet of dependency targets that are linked
into this target.
This function has a split personality, depending on the setting of
|initial|. Outside callers should always leave |initial| at its default
setting.
When adding a target to the list of dependencies, this function will
recurse into itself with |initial| set to False, to collect dependencies
that are linked into the linkable target for which the list is being built.
If |include_shared_libraries| is False, the resulting dependencies will not
include shared_library targets that are linked into this target.
"""
if dependencies is None:
# Using a list to get ordered output and a set to do fast "is it
# already added" checks.
dependencies = OrderedSet()
# Check for None, corresponding to the root node.
if self.ref is None:
return dependencies
# It's kind of sucky that |targets| has to be passed into this function,
# but that's presently the easiest way to access the target dicts so that
# this function can find target types.
if 'target_name' not in targets[self.ref]:
raise GypError("Missing 'target_name' field in target.")
if 'type' not in targets[self.ref]:
raise GypError("Missing 'type' field in target %s" %
targets[self.ref]['target_name'])
target_type = targets[self.ref]['type']
is_linkable = target_type in linkable_types
if initial and not is_linkable:
# If this is the first target being examined and it's not linkable,
# return an empty list of link dependencies, because the link
# dependencies are intended to apply to the target itself (initial is
# True) and this target won't be linked.
return dependencies
# Don't traverse 'none' targets if explicitly excluded.
if (target_type == 'none' and
not targets[self.ref].get('dependencies_traverse', True)):
dependencies.add(self.ref)
return dependencies
# Executables, mac kernel extensions and loadable modules are already fully
# and finally linked. Nothing else can be a link dependency of them, there
# can only be dependencies in the sense that a dependent target might run
# an executable or load the loadable_module.
if not initial and target_type in ('executable', 'loadable_module',
'mac_kernel_extension'):
return dependencies
# Shared libraries are already fully linked. They should only be included
# in |dependencies| when adjusting static library dependencies (in order to
# link against the shared_library's import lib), but should not be included
# in |dependencies| when propagating link_settings.
# The |include_shared_libraries| flag controls which of these two cases we
# are handling.
if (not initial and target_type == 'shared_library' and
not include_shared_libraries):
return dependencies
# The target is linkable, add it to the list of link dependencies.
if self.ref not in dependencies:
dependencies.add(self.ref)
if initial or not is_linkable:
# If this is a subsequent target and it's linkable, don't look any
# further for linkable dependencies, as they'll already be linked into
# this target linkable. Always look at dependencies of the initial
# target, and always look at dependencies of non-linkables.
for dependency in self.dependencies:
dependency._LinkDependenciesInternal(targets,
include_shared_libraries,
dependencies, False)
return dependencies | [
"def",
"_LinkDependenciesInternal",
"(",
"self",
",",
"targets",
",",
"include_shared_libraries",
",",
"dependencies",
"=",
"None",
",",
"initial",
"=",
"True",
")",
":",
"if",
"dependencies",
"is",
"None",
":",
"# Using a list to get ordered output and a set to do fast \"is it",
"# already added\" checks.",
"dependencies",
"=",
"OrderedSet",
"(",
")",
"# Check for None, corresponding to the root node.",
"if",
"self",
".",
"ref",
"is",
"None",
":",
"return",
"dependencies",
"# It's kind of sucky that |targets| has to be passed into this function,",
"# but that's presently the easiest way to access the target dicts so that",
"# this function can find target types.",
"if",
"'target_name'",
"not",
"in",
"targets",
"[",
"self",
".",
"ref",
"]",
":",
"raise",
"GypError",
"(",
"\"Missing 'target_name' field in target.\"",
")",
"if",
"'type'",
"not",
"in",
"targets",
"[",
"self",
".",
"ref",
"]",
":",
"raise",
"GypError",
"(",
"\"Missing 'type' field in target %s\"",
"%",
"targets",
"[",
"self",
".",
"ref",
"]",
"[",
"'target_name'",
"]",
")",
"target_type",
"=",
"targets",
"[",
"self",
".",
"ref",
"]",
"[",
"'type'",
"]",
"is_linkable",
"=",
"target_type",
"in",
"linkable_types",
"if",
"initial",
"and",
"not",
"is_linkable",
":",
"# If this is the first target being examined and it's not linkable,",
"# return an empty list of link dependencies, because the link",
"# dependencies are intended to apply to the target itself (initial is",
"# True) and this target won't be linked.",
"return",
"dependencies",
"# Don't traverse 'none' targets if explicitly excluded.",
"if",
"(",
"target_type",
"==",
"'none'",
"and",
"not",
"targets",
"[",
"self",
".",
"ref",
"]",
".",
"get",
"(",
"'dependencies_traverse'",
",",
"True",
")",
")",
":",
"dependencies",
".",
"add",
"(",
"self",
".",
"ref",
")",
"return",
"dependencies",
"# Executables, mac kernel extensions and loadable modules are already fully",
"# and finally linked. Nothing else can be a link dependency of them, there",
"# can only be dependencies in the sense that a dependent target might run",
"# an executable or load the loadable_module.",
"if",
"not",
"initial",
"and",
"target_type",
"in",
"(",
"'executable'",
",",
"'loadable_module'",
",",
"'mac_kernel_extension'",
")",
":",
"return",
"dependencies",
"# Shared libraries are already fully linked. They should only be included",
"# in |dependencies| when adjusting static library dependencies (in order to",
"# link against the shared_library's import lib), but should not be included",
"# in |dependencies| when propagating link_settings.",
"# The |include_shared_libraries| flag controls which of these two cases we",
"# are handling.",
"if",
"(",
"not",
"initial",
"and",
"target_type",
"==",
"'shared_library'",
"and",
"not",
"include_shared_libraries",
")",
":",
"return",
"dependencies",
"# The target is linkable, add it to the list of link dependencies.",
"if",
"self",
".",
"ref",
"not",
"in",
"dependencies",
":",
"dependencies",
".",
"add",
"(",
"self",
".",
"ref",
")",
"if",
"initial",
"or",
"not",
"is_linkable",
":",
"# If this is a subsequent target and it's linkable, don't look any",
"# further for linkable dependencies, as they'll already be linked into",
"# this target linkable. Always look at dependencies of the initial",
"# target, and always look at dependencies of non-linkables.",
"for",
"dependency",
"in",
"self",
".",
"dependencies",
":",
"dependency",
".",
"_LinkDependenciesInternal",
"(",
"targets",
",",
"include_shared_libraries",
",",
"dependencies",
",",
"False",
")",
"return",
"dependencies"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L1687-L1771 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/shortcuteditor.py | python | ShortcutEditor.ToMenuBar | (self, topWindow) | Dumps the entire shortcut hierarchy (for shortcuts associated with a :class:`MenuItem`), into
a :class:`MenuBar`, changing only the :class:`Menu` / :class:`MenuItem` labels (it does **not** rebuild
the :class:`MenuBar`).
:param `topWindow`: an instance of :class:`TopLevelWindow`, containing the :class:`MenuBar`
we wish to repopulate. | Dumps the entire shortcut hierarchy (for shortcuts associated with a :class:`MenuItem`), into
a :class:`MenuBar`, changing only the :class:`Menu` / :class:`MenuItem` labels (it does **not** rebuild
the :class:`MenuBar`). | [
"Dumps",
"the",
"entire",
"shortcut",
"hierarchy",
"(",
"for",
"shortcuts",
"associated",
"with",
"a",
":",
"class",
":",
"MenuItem",
")",
"into",
"a",
":",
"class",
":",
"MenuBar",
"changing",
"only",
"the",
":",
"class",
":",
"Menu",
"/",
":",
"class",
":",
"MenuItem",
"labels",
"(",
"it",
"does",
"**",
"not",
"**",
"rebuild",
"the",
":",
"class",
":",
"MenuBar",
")",
"."
] | def ToMenuBar(self, topWindow):
"""
Dumps the entire shortcut hierarchy (for shortcuts associated with a :class:`MenuItem`), into
a :class:`MenuBar`, changing only the :class:`Menu` / :class:`MenuItem` labels (it does **not** rebuild
the :class:`MenuBar`).
:param `topWindow`: an instance of :class:`TopLevelWindow`, containing the :class:`MenuBar`
we wish to repopulate.
"""
def MenuItemSet(shortcut, menuBar):
child, cookie = shortcut.GetFirstChild(shortcut)
while child:
child.ToMenuItem(menuBar)
MenuItemSet(child, menuBar)
child, cookie = shortcut.GetNextChild(shortcut, cookie)
manager = self.GetShortcutManager()
menuBar = topWindow.GetMenuBar()
MenuItemSet(manager, menuBar) | [
"def",
"ToMenuBar",
"(",
"self",
",",
"topWindow",
")",
":",
"def",
"MenuItemSet",
"(",
"shortcut",
",",
"menuBar",
")",
":",
"child",
",",
"cookie",
"=",
"shortcut",
".",
"GetFirstChild",
"(",
"shortcut",
")",
"while",
"child",
":",
"child",
".",
"ToMenuItem",
"(",
"menuBar",
")",
"MenuItemSet",
"(",
"child",
",",
"menuBar",
")",
"child",
",",
"cookie",
"=",
"shortcut",
".",
"GetNextChild",
"(",
"shortcut",
",",
"cookie",
")",
"manager",
"=",
"self",
".",
"GetShortcutManager",
"(",
")",
"menuBar",
"=",
"topWindow",
".",
"GetMenuBar",
"(",
")",
"MenuItemSet",
"(",
"manager",
",",
"menuBar",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shortcuteditor.py#L2370-L2392 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | SimRobotController.setPIDCommand | (self, *args) | return _robotsim.SimRobotController_setPIDCommand(self, *args) | setPIDCommand(SimRobotController self, doubleVector qdes, doubleVector dqdes)
setPIDCommand(SimRobotController self, doubleVector qdes, doubleVector dqdes, doubleVector tfeedforward)
Sets a PID command controller. If tfeedforward is provided, it is the
feedforward torque vector. | setPIDCommand(SimRobotController self, doubleVector qdes, doubleVector dqdes)
setPIDCommand(SimRobotController self, doubleVector qdes, doubleVector dqdes, doubleVector tfeedforward) | [
"setPIDCommand",
"(",
"SimRobotController",
"self",
"doubleVector",
"qdes",
"doubleVector",
"dqdes",
")",
"setPIDCommand",
"(",
"SimRobotController",
"self",
"doubleVector",
"qdes",
"doubleVector",
"dqdes",
"doubleVector",
"tfeedforward",
")"
] | def setPIDCommand(self, *args):
"""
setPIDCommand(SimRobotController self, doubleVector qdes, doubleVector dqdes)
setPIDCommand(SimRobotController self, doubleVector qdes, doubleVector dqdes, doubleVector tfeedforward)
Sets a PID command controller. If tfeedforward is provided, it is the
feedforward torque vector.
"""
return _robotsim.SimRobotController_setPIDCommand(self, *args) | [
"def",
"setPIDCommand",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_robotsim",
".",
"SimRobotController_setPIDCommand",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L7729-L7740 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py | python | BackgroundCorrectionsView.set_slot_for_show_fit_output_clicked | (self, slot) | Sets the slot for when the 'Show Output' is clicked. | Sets the slot for when the 'Show Output' is clicked. | [
"Sets",
"the",
"slot",
"for",
"when",
"the",
"Show",
"Output",
"is",
"clicked",
"."
] | def set_slot_for_show_fit_output_clicked(self, slot) -> None:
"""Sets the slot for when the 'Show Output' is clicked."""
self.handle_show_fit_output_clicked = slot | [
"def",
"set_slot_for_show_fit_output_clicked",
"(",
"self",
",",
"slot",
")",
"->",
"None",
":",
"self",
".",
"handle_show_fit_output_clicked",
"=",
"slot"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py#L109-L111 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/config.py | python | DictConfigurator.configure_handler | (self, config) | return result | Configure a handler from a dictionary. | Configure a handler from a dictionary. | [
"Configure",
"a",
"handler",
"from",
"a",
"dictionary",
"."
] | def configure_handler(self, config):
"""Configure a handler from a dictionary."""
formatter = config.pop('formatter', None)
if formatter:
try:
formatter = self.config['formatters'][formatter]
except StandardError, e:
raise ValueError('Unable to set formatter '
'%r: %s' % (formatter, e))
level = config.pop('level', None)
filters = config.pop('filters', None)
if '()' in config:
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
factory = c
else:
cname = config.pop('class')
klass = self.resolve(cname)
#Special case for handler which refers to another handler
if issubclass(klass, logging.handlers.MemoryHandler) and\
'target' in config:
try:
th = self.config['handlers'][config['target']]
if not isinstance(th, logging.Handler):
config['class'] = cname # restore for deferred configuration
raise StandardError('target not configured yet')
config['target'] = th
except StandardError, e:
raise ValueError('Unable to set target handler '
'%r: %s' % (config['target'], e))
elif issubclass(klass, logging.handlers.SMTPHandler) and\
'mailhost' in config:
config['mailhost'] = self.as_tuple(config['mailhost'])
elif issubclass(klass, logging.handlers.SysLogHandler) and\
'address' in config:
config['address'] = self.as_tuple(config['address'])
factory = klass
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
try:
result = factory(**kwargs)
except TypeError, te:
if "'stream'" not in str(te):
raise
#The argument name changed from strm to stream
#Retry with old name.
#This is so that code can be used with older Python versions
#(e.g. by Django)
kwargs['strm'] = kwargs.pop('stream')
result = factory(**kwargs)
if formatter:
result.setFormatter(formatter)
if level is not None:
result.setLevel(logging._checkLevel(level))
if filters:
self.add_filters(result, filters)
return result | [
"def",
"configure_handler",
"(",
"self",
",",
"config",
")",
":",
"formatter",
"=",
"config",
".",
"pop",
"(",
"'formatter'",
",",
"None",
")",
"if",
"formatter",
":",
"try",
":",
"formatter",
"=",
"self",
".",
"config",
"[",
"'formatters'",
"]",
"[",
"formatter",
"]",
"except",
"StandardError",
",",
"e",
":",
"raise",
"ValueError",
"(",
"'Unable to set formatter '",
"'%r: %s'",
"%",
"(",
"formatter",
",",
"e",
")",
")",
"level",
"=",
"config",
".",
"pop",
"(",
"'level'",
",",
"None",
")",
"filters",
"=",
"config",
".",
"pop",
"(",
"'filters'",
",",
"None",
")",
"if",
"'()'",
"in",
"config",
":",
"c",
"=",
"config",
".",
"pop",
"(",
"'()'",
")",
"if",
"not",
"hasattr",
"(",
"c",
",",
"'__call__'",
")",
"and",
"hasattr",
"(",
"types",
",",
"'ClassType'",
")",
"and",
"type",
"(",
"c",
")",
"!=",
"types",
".",
"ClassType",
":",
"c",
"=",
"self",
".",
"resolve",
"(",
"c",
")",
"factory",
"=",
"c",
"else",
":",
"cname",
"=",
"config",
".",
"pop",
"(",
"'class'",
")",
"klass",
"=",
"self",
".",
"resolve",
"(",
"cname",
")",
"#Special case for handler which refers to another handler",
"if",
"issubclass",
"(",
"klass",
",",
"logging",
".",
"handlers",
".",
"MemoryHandler",
")",
"and",
"'target'",
"in",
"config",
":",
"try",
":",
"th",
"=",
"self",
".",
"config",
"[",
"'handlers'",
"]",
"[",
"config",
"[",
"'target'",
"]",
"]",
"if",
"not",
"isinstance",
"(",
"th",
",",
"logging",
".",
"Handler",
")",
":",
"config",
"[",
"'class'",
"]",
"=",
"cname",
"# restore for deferred configuration",
"raise",
"StandardError",
"(",
"'target not configured yet'",
")",
"config",
"[",
"'target'",
"]",
"=",
"th",
"except",
"StandardError",
",",
"e",
":",
"raise",
"ValueError",
"(",
"'Unable to set target handler '",
"'%r: %s'",
"%",
"(",
"config",
"[",
"'target'",
"]",
",",
"e",
")",
")",
"elif",
"issubclass",
"(",
"klass",
",",
"logging",
".",
"handlers",
".",
"SMTPHandler",
")",
"and",
"'mailhost'",
"in",
"config",
":",
"config",
"[",
"'mailhost'",
"]",
"=",
"self",
".",
"as_tuple",
"(",
"config",
"[",
"'mailhost'",
"]",
")",
"elif",
"issubclass",
"(",
"klass",
",",
"logging",
".",
"handlers",
".",
"SysLogHandler",
")",
"and",
"'address'",
"in",
"config",
":",
"config",
"[",
"'address'",
"]",
"=",
"self",
".",
"as_tuple",
"(",
"config",
"[",
"'address'",
"]",
")",
"factory",
"=",
"klass",
"kwargs",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"config",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"config",
"if",
"valid_ident",
"(",
"k",
")",
"]",
")",
"try",
":",
"result",
"=",
"factory",
"(",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
",",
"te",
":",
"if",
"\"'stream'\"",
"not",
"in",
"str",
"(",
"te",
")",
":",
"raise",
"#The argument name changed from strm to stream",
"#Retry with old name.",
"#This is so that code can be used with older Python versions",
"#(e.g. by Django)",
"kwargs",
"[",
"'strm'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'stream'",
")",
"result",
"=",
"factory",
"(",
"*",
"*",
"kwargs",
")",
"if",
"formatter",
":",
"result",
".",
"setFormatter",
"(",
"formatter",
")",
"if",
"level",
"is",
"not",
"None",
":",
"result",
".",
"setLevel",
"(",
"logging",
".",
"_checkLevel",
"(",
"level",
")",
")",
"if",
"filters",
":",
"self",
".",
"add_filters",
"(",
"result",
",",
"filters",
")",
"return",
"result"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/config.py#L702-L758 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | TimeSpan.Format | (*args, **kwargs) | return _misc_.TimeSpan_Format(*args, **kwargs) | Format(self, String format=DefaultTimeSpanFormat) -> String | Format(self, String format=DefaultTimeSpanFormat) -> String | [
"Format",
"(",
"self",
"String",
"format",
"=",
"DefaultTimeSpanFormat",
")",
"-",
">",
"String"
] | def Format(*args, **kwargs):
"""Format(self, String format=DefaultTimeSpanFormat) -> String"""
return _misc_.TimeSpan_Format(*args, **kwargs) | [
"def",
"Format",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"TimeSpan_Format",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L4538-L4540 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/base_layer_v1.py | python | Layer.call | (self, inputs, **kwargs) | return inputs | This is where the layer's logic lives.
Args:
inputs: Input tensor, or list/tuple of input tensors.
**kwargs: Additional keyword arguments.
Returns:
A tensor or list/tuple of tensors. | This is where the layer's logic lives. | [
"This",
"is",
"where",
"the",
"layer",
"s",
"logic",
"lives",
"."
] | def call(self, inputs, **kwargs): # pylint: disable=unused-argument
"""This is where the layer's logic lives.
Args:
inputs: Input tensor, or list/tuple of input tensors.
**kwargs: Additional keyword arguments.
Returns:
A tensor or list/tuple of tensors.
"""
return inputs | [
"def",
"call",
"(",
"self",
",",
"inputs",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"return",
"inputs"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/base_layer_v1.py#L281-L291 | |
baidu/AnyQ | d94d450d2aaa5f7ed73424b10aa4539835b97527 | tools/simnet/preprocess/operation_unit.py | python | OpWriteData._get_pairwise_lines | (self, dataset, setname) | pairwise data generator | pairwise data generator | [
"pairwise",
"data",
"generator"
] | def _get_pairwise_lines(self, dataset, setname):
"""
pairwise data generator
"""
for (qid, oo_list) in dataset:
if setname == 'train':
pos_titles = []
neg_titles = []
for oo in oo_list:
infos = oo.get_infos()
if int(infos['label']) > 0:
pos_titles.append(' '.join(infos['title_token']))
else:
neg_titles.append(' '.join(infos['title_token']))
if len(pos_titles) * len(neg_titles) <= 0:
continue
query = ''
if len(oo_list) > 0:
infos = oo_list[0].get_infos()
query = ' '.join(infos['query_token'])
pos_neg_pair = itertools.product(pos_titles, neg_titles)
for pair in pos_neg_pair:
line = '%s\t%s\t%s\n' % (query, pair[0], pair[1])
yield line
elif setname == 'test':
for oo in oo_list:
infos = oo.get_infos()
line = "%s\t%s\t%s\t%s\n" % (infos['qid'], infos['label'], \
' '.join(infos['query_token']), ' '.join(infos['title_token']))
yield line | [
"def",
"_get_pairwise_lines",
"(",
"self",
",",
"dataset",
",",
"setname",
")",
":",
"for",
"(",
"qid",
",",
"oo_list",
")",
"in",
"dataset",
":",
"if",
"setname",
"==",
"'train'",
":",
"pos_titles",
"=",
"[",
"]",
"neg_titles",
"=",
"[",
"]",
"for",
"oo",
"in",
"oo_list",
":",
"infos",
"=",
"oo",
".",
"get_infos",
"(",
")",
"if",
"int",
"(",
"infos",
"[",
"'label'",
"]",
")",
">",
"0",
":",
"pos_titles",
".",
"append",
"(",
"' '",
".",
"join",
"(",
"infos",
"[",
"'title_token'",
"]",
")",
")",
"else",
":",
"neg_titles",
".",
"append",
"(",
"' '",
".",
"join",
"(",
"infos",
"[",
"'title_token'",
"]",
")",
")",
"if",
"len",
"(",
"pos_titles",
")",
"*",
"len",
"(",
"neg_titles",
")",
"<=",
"0",
":",
"continue",
"query",
"=",
"''",
"if",
"len",
"(",
"oo_list",
")",
">",
"0",
":",
"infos",
"=",
"oo_list",
"[",
"0",
"]",
".",
"get_infos",
"(",
")",
"query",
"=",
"' '",
".",
"join",
"(",
"infos",
"[",
"'query_token'",
"]",
")",
"pos_neg_pair",
"=",
"itertools",
".",
"product",
"(",
"pos_titles",
",",
"neg_titles",
")",
"for",
"pair",
"in",
"pos_neg_pair",
":",
"line",
"=",
"'%s\\t%s\\t%s\\n'",
"%",
"(",
"query",
",",
"pair",
"[",
"0",
"]",
",",
"pair",
"[",
"1",
"]",
")",
"yield",
"line",
"elif",
"setname",
"==",
"'test'",
":",
"for",
"oo",
"in",
"oo_list",
":",
"infos",
"=",
"oo",
".",
"get_infos",
"(",
")",
"line",
"=",
"\"%s\\t%s\\t%s\\t%s\\n\"",
"%",
"(",
"infos",
"[",
"'qid'",
"]",
",",
"infos",
"[",
"'label'",
"]",
",",
"' '",
".",
"join",
"(",
"infos",
"[",
"'query_token'",
"]",
")",
",",
"' '",
".",
"join",
"(",
"infos",
"[",
"'title_token'",
"]",
")",
")",
"yield",
"line"
] | https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/preprocess/operation_unit.py#L255-L284 | ||
vusec/vuzzer64 | 2b1b0ed757a3dca114db0192fa4ab1add92348bc | fuzzer-code/runfuzzer.py | python | form_bitvector | (bbdict) | This function forms bit vector for each trace and append them to config.TEMPTRACE list. | This function forms bit vector for each trace and append them to config.TEMPTRACE list. | [
"This",
"function",
"forms",
"bit",
"vector",
"for",
"each",
"trace",
"and",
"append",
"them",
"to",
"config",
".",
"TEMPTRACE",
"list",
"."
] | def form_bitvector(bbdict):
''' This function forms bit vector for each trace and append them to config.TEMPTRACE list. '''
newbb=0
temp=set()
for bbadr in bbdict:
temp.add(bbadr)
if bbadr not in config.BBSEENVECTOR:
#added for bit vector formation
newbb +=1
config.BBSEENVECTOR.append(bbadr)
tbv=BV.BitVector(size=(len(config.BBSEENVECTOR)))
if newbb == 0:
for el in temp:
tbv[config.BBSEENVECTOR.index(el)]=1
config.TEMPTRACE.append(tbv.deep_copy())
else:
for bvs in config.TEMPTRACE:
bvs.pad_from_right(newbb)
for el in temp:
tbv[config.BBSEENVECTOR.index(el)]=1
config.TEMPTRACE.append(tbv.deep_copy())
del tbv | [
"def",
"form_bitvector",
"(",
"bbdict",
")",
":",
"newbb",
"=",
"0",
"temp",
"=",
"set",
"(",
")",
"for",
"bbadr",
"in",
"bbdict",
":",
"temp",
".",
"add",
"(",
"bbadr",
")",
"if",
"bbadr",
"not",
"in",
"config",
".",
"BBSEENVECTOR",
":",
"#added for bit vector formation",
"newbb",
"+=",
"1",
"config",
".",
"BBSEENVECTOR",
".",
"append",
"(",
"bbadr",
")",
"tbv",
"=",
"BV",
".",
"BitVector",
"(",
"size",
"=",
"(",
"len",
"(",
"config",
".",
"BBSEENVECTOR",
")",
")",
")",
"if",
"newbb",
"==",
"0",
":",
"for",
"el",
"in",
"temp",
":",
"tbv",
"[",
"config",
".",
"BBSEENVECTOR",
".",
"index",
"(",
"el",
")",
"]",
"=",
"1",
"config",
".",
"TEMPTRACE",
".",
"append",
"(",
"tbv",
".",
"deep_copy",
"(",
")",
")",
"else",
":",
"for",
"bvs",
"in",
"config",
".",
"TEMPTRACE",
":",
"bvs",
".",
"pad_from_right",
"(",
"newbb",
")",
"for",
"el",
"in",
"temp",
":",
"tbv",
"[",
"config",
".",
"BBSEENVECTOR",
".",
"index",
"(",
"el",
")",
"]",
"=",
"1",
"config",
".",
"TEMPTRACE",
".",
"append",
"(",
"tbv",
".",
"deep_copy",
"(",
")",
")",
"del",
"tbv"
] | https://github.com/vusec/vuzzer64/blob/2b1b0ed757a3dca114db0192fa4ab1add92348bc/fuzzer-code/runfuzzer.py#L94-L116 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/clustering/dbscan.py | python | DBSCANModel.__repr__ | (self) | return out + "\n" + out2 | Print a string description of the model when the model name is entered
in the terminal. | Print a string description of the model when the model name is entered
in the terminal. | [
"Print",
"a",
"string",
"description",
"of",
"the",
"model",
"when",
"the",
"model",
"name",
"is",
"entered",
"in",
"the",
"terminal",
"."
] | def __repr__(self):
"""
Print a string description of the model when the model name is entered
in the terminal.
"""
width = 40
sections, section_titles = self._get_summary_struct()
accessible_fields = {
"cluster_id": "Cluster label for each row in the input dataset."
}
out = _toolkit_repr_print(self, sections, section_titles, width=width)
out2 = _summarize_accessible_fields(accessible_fields, width=width)
return out + "\n" + out2 | [
"def",
"__repr__",
"(",
"self",
")",
":",
"width",
"=",
"40",
"sections",
",",
"section_titles",
"=",
"self",
".",
"_get_summary_struct",
"(",
")",
"accessible_fields",
"=",
"{",
"\"cluster_id\"",
":",
"\"Cluster label for each row in the input dataset.\"",
"}",
"out",
"=",
"_toolkit_repr_print",
"(",
"self",
",",
"sections",
",",
"section_titles",
",",
"width",
"=",
"width",
")",
"out2",
"=",
"_summarize_accessible_fields",
"(",
"accessible_fields",
",",
"width",
"=",
"width",
")",
"return",
"out",
"+",
"\"\\n\"",
"+",
"out2"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/clustering/dbscan.py#L390-L404 | |
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/tyr/tyr/tasks.py | python | import_in_mimir | (_file, instance, asynchronous=True) | Import pt data stops to autocomplete | Import pt data stops to autocomplete | [
"Import",
"pt",
"data",
"stops",
"to",
"autocomplete"
] | def import_in_mimir(_file, instance, asynchronous=True):
"""
Import pt data stops to autocomplete
"""
datatype, _ = utils.type_of_data(_file)
family_type = utils.family_of_data(datatype)
current_app.logger.debug("Import {} data to mimir".format(family_type))
actions = []
for version in (2, 7):
if not is_activate_autocomplete_version(version):
logging.getLogger(__name__).info("Disable import mimir version {}".format(version))
continue
if family_type == 'pt':
if instance.import_ntfs_in_mimir:
actions.append(ntfs2mimir.si(instance.name, _file, version))
# Deprecated: https://github.com/CanalTP/mimirsbrunn/blob/4430eed1d81247fffa7cf32ba675a9c5ad8b1cbe/documentation/components.md#stops2mimir
if instance.import_stops_in_mimir and not instance.import_ntfs_in_mimir:
actions.append(stops2mimir.si(instance.name, _file, version))
elif family_type == 'poi':
actions.append(poi2mimir.si(instance.name, _file, version))
else:
current_app.logger.warning("Unsupported family_type {}".format(family_type))
if asynchronous:
return chain(*actions).delay()
else:
# all job are run in sequence and import_in_mimir will only return when all the jobs are finish
return chain(*actions).apply() | [
"def",
"import_in_mimir",
"(",
"_file",
",",
"instance",
",",
"asynchronous",
"=",
"True",
")",
":",
"datatype",
",",
"_",
"=",
"utils",
".",
"type_of_data",
"(",
"_file",
")",
"family_type",
"=",
"utils",
".",
"family_of_data",
"(",
"datatype",
")",
"current_app",
".",
"logger",
".",
"debug",
"(",
"\"Import {} data to mimir\"",
".",
"format",
"(",
"family_type",
")",
")",
"actions",
"=",
"[",
"]",
"for",
"version",
"in",
"(",
"2",
",",
"7",
")",
":",
"if",
"not",
"is_activate_autocomplete_version",
"(",
"version",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"info",
"(",
"\"Disable import mimir version {}\"",
".",
"format",
"(",
"version",
")",
")",
"continue",
"if",
"family_type",
"==",
"'pt'",
":",
"if",
"instance",
".",
"import_ntfs_in_mimir",
":",
"actions",
".",
"append",
"(",
"ntfs2mimir",
".",
"si",
"(",
"instance",
".",
"name",
",",
"_file",
",",
"version",
")",
")",
"# Deprecated: https://github.com/CanalTP/mimirsbrunn/blob/4430eed1d81247fffa7cf32ba675a9c5ad8b1cbe/documentation/components.md#stops2mimir",
"if",
"instance",
".",
"import_stops_in_mimir",
"and",
"not",
"instance",
".",
"import_ntfs_in_mimir",
":",
"actions",
".",
"append",
"(",
"stops2mimir",
".",
"si",
"(",
"instance",
".",
"name",
",",
"_file",
",",
"version",
")",
")",
"elif",
"family_type",
"==",
"'poi'",
":",
"actions",
".",
"append",
"(",
"poi2mimir",
".",
"si",
"(",
"instance",
".",
"name",
",",
"_file",
",",
"version",
")",
")",
"else",
":",
"current_app",
".",
"logger",
".",
"warning",
"(",
"\"Unsupported family_type {}\"",
".",
"format",
"(",
"family_type",
")",
")",
"if",
"asynchronous",
":",
"return",
"chain",
"(",
"*",
"actions",
")",
".",
"delay",
"(",
")",
"else",
":",
"# all job are run in sequence and import_in_mimir will only return when all the jobs are finish",
"return",
"chain",
"(",
"*",
"actions",
")",
".",
"apply",
"(",
")"
] | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/tyr/tyr/tasks.py#L397-L426 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | media/tools/constrained_network_server/cns.py | python | ParseArgs | () | return options | Define and parse the command-line arguments. | Define and parse the command-line arguments. | [
"Define",
"and",
"parse",
"the",
"command",
"-",
"line",
"arguments",
"."
] | def ParseArgs():
"""Define and parse the command-line arguments."""
parser = optparse.OptionParser()
parser.add_option('--expiry-time', type='int',
default=_DEFAULT_PORT_EXPIRY_TIME_SECS,
help=('Number of seconds before constrained ports expire '
'and are cleaned up. 0=Disabled. Default: %default'))
parser.add_option('--port', type='int', default=_DEFAULT_SERVING_PORT,
help='Port to serve the API on. Default: %default')
parser.add_option('--port-range', default=_DEFAULT_CNS_PORT_RANGE,
help=('Range of ports for constrained serving. Specify as '
'a comma separated value pair. Default: %default'))
parser.add_option('--interface', default='eth0',
help=('Interface to setup constraints on. Use lo for a '
'local client. Default: %default'))
parser.add_option('--socket-timeout', type='int',
default=cherrypy.server.socket_timeout,
help=('Number of seconds before a socket connection times '
'out. Default: %default'))
parser.add_option('--threads', type='int',
default=cherrypy._cpserver.Server.thread_pool,
help=('Number of threads in the thread pool. Default: '
'%default'))
parser.add_option('--www-root', default='',
help=('Directory root to serve files from. If --local-'
'server-port is used, the path is appended to the '
'redirected URL of local server. Defaults to the '
'current directory (if --local-server-port is not '
'used): %s' % os.getcwd()))
parser.add_option('--local-server-port', type='int',
help=('Optional local server port to host files.'))
parser.add_option('-v', '--verbose', action='store_true', default=False,
help='Turn on verbose output.')
options = parser.parse_args()[0]
# Convert port range into the desired tuple format.
try:
if isinstance(options.port_range, str):
options.port_range = [int(port) for port in options.port_range.split(',')]
except ValueError:
parser.error('Invalid port range specified.')
if options.expiry_time < 0:
parser.error('Invalid expiry time specified.')
# Convert the path to an absolute to remove any . or ..
if not options.local_server_port:
if not options.www_root:
options.www_root = os.getcwd()
options.www_root = os.path.abspath(options.www_root)
_SetLogger(options.verbose)
return options | [
"def",
"ParseArgs",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"'--expiry-time'",
",",
"type",
"=",
"'int'",
",",
"default",
"=",
"_DEFAULT_PORT_EXPIRY_TIME_SECS",
",",
"help",
"=",
"(",
"'Number of seconds before constrained ports expire '",
"'and are cleaned up. 0=Disabled. Default: %default'",
")",
")",
"parser",
".",
"add_option",
"(",
"'--port'",
",",
"type",
"=",
"'int'",
",",
"default",
"=",
"_DEFAULT_SERVING_PORT",
",",
"help",
"=",
"'Port to serve the API on. Default: %default'",
")",
"parser",
".",
"add_option",
"(",
"'--port-range'",
",",
"default",
"=",
"_DEFAULT_CNS_PORT_RANGE",
",",
"help",
"=",
"(",
"'Range of ports for constrained serving. Specify as '",
"'a comma separated value pair. Default: %default'",
")",
")",
"parser",
".",
"add_option",
"(",
"'--interface'",
",",
"default",
"=",
"'eth0'",
",",
"help",
"=",
"(",
"'Interface to setup constraints on. Use lo for a '",
"'local client. Default: %default'",
")",
")",
"parser",
".",
"add_option",
"(",
"'--socket-timeout'",
",",
"type",
"=",
"'int'",
",",
"default",
"=",
"cherrypy",
".",
"server",
".",
"socket_timeout",
",",
"help",
"=",
"(",
"'Number of seconds before a socket connection times '",
"'out. Default: %default'",
")",
")",
"parser",
".",
"add_option",
"(",
"'--threads'",
",",
"type",
"=",
"'int'",
",",
"default",
"=",
"cherrypy",
".",
"_cpserver",
".",
"Server",
".",
"thread_pool",
",",
"help",
"=",
"(",
"'Number of threads in the thread pool. Default: '",
"'%default'",
")",
")",
"parser",
".",
"add_option",
"(",
"'--www-root'",
",",
"default",
"=",
"''",
",",
"help",
"=",
"(",
"'Directory root to serve files from. If --local-'",
"'server-port is used, the path is appended to the '",
"'redirected URL of local server. Defaults to the '",
"'current directory (if --local-server-port is not '",
"'used): %s'",
"%",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"parser",
".",
"add_option",
"(",
"'--local-server-port'",
",",
"type",
"=",
"'int'",
",",
"help",
"=",
"(",
"'Optional local server port to host files.'",
")",
")",
"parser",
".",
"add_option",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Turn on verbose output.'",
")",
"options",
"=",
"parser",
".",
"parse_args",
"(",
")",
"[",
"0",
"]",
"# Convert port range into the desired tuple format.",
"try",
":",
"if",
"isinstance",
"(",
"options",
".",
"port_range",
",",
"str",
")",
":",
"options",
".",
"port_range",
"=",
"[",
"int",
"(",
"port",
")",
"for",
"port",
"in",
"options",
".",
"port_range",
".",
"split",
"(",
"','",
")",
"]",
"except",
"ValueError",
":",
"parser",
".",
"error",
"(",
"'Invalid port range specified.'",
")",
"if",
"options",
".",
"expiry_time",
"<",
"0",
":",
"parser",
".",
"error",
"(",
"'Invalid expiry time specified.'",
")",
"# Convert the path to an absolute to remove any . or ..",
"if",
"not",
"options",
".",
"local_server_port",
":",
"if",
"not",
"options",
".",
"www_root",
":",
"options",
".",
"www_root",
"=",
"os",
".",
"getcwd",
"(",
")",
"options",
".",
"www_root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"options",
".",
"www_root",
")",
"_SetLogger",
"(",
"options",
".",
"verbose",
")",
"return",
"options"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/media/tools/constrained_network_server/cns.py#L354-L409 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/graphics.py | python | GraphicsContext.SetTransform | (self, matrix) | Set the context's current transformation matrix to matrix. | Set the context's current transformation matrix to matrix. | [
"Set",
"the",
"context",
"s",
"current",
"transformation",
"matrix",
"to",
"matrix",
"."
] | def SetTransform(self, matrix):
"""
Set the context's current transformation matrix to matrix.
"""
self._context.set_matrix(matrix.GetNativeMatrix()) | [
"def",
"SetTransform",
"(",
"self",
",",
"matrix",
")",
":",
"self",
".",
"_context",
".",
"set_matrix",
"(",
"matrix",
".",
"GetNativeMatrix",
"(",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/graphics.py#L1226-L1230 | ||
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/commands/undistort.py | python | undistort_image | (shot, undistorted_shots, original, interpolation,
max_size) | Undistort an image into a set of undistorted ones.
Args:
shot: the distorted shot
undistorted_shots: the set of undistorted shots covering the
distorted shot field of view. That is 1 for most camera
types and 6 for equirectangular cameras.
original: the original distorted image array.
interpolation: the opencv interpolation flag to use.
max_size: maximum size of the undistorted image. | Undistort an image into a set of undistorted ones. | [
"Undistort",
"an",
"image",
"into",
"a",
"set",
"of",
"undistorted",
"ones",
"."
] | def undistort_image(shot, undistorted_shots, original, interpolation,
max_size):
"""Undistort an image into a set of undistorted ones.
Args:
shot: the distorted shot
undistorted_shots: the set of undistorted shots covering the
distorted shot field of view. That is 1 for most camera
types and 6 for equirectangular cameras.
original: the original distorted image array.
interpolation: the opencv interpolation flag to use.
max_size: maximum size of the undistorted image.
"""
if original is None:
return
projection_type = shot.camera.projection_type
if projection_type in ['perspective', 'brown', 'fisheye']:
undistort_function = {
'perspective': undistort_perspective_image,
'brown': undistort_brown_image,
'fisheye': undistort_fisheye_image,
}
new_camera = undistorted_shots[0].camera
uf = undistort_function[projection_type]
undistorted = uf(original, shot.camera, new_camera, interpolation)
return {shot.id: scale_image(undistorted, max_size)}
elif projection_type in ['equirectangular', 'spherical']:
subshot_width = undistorted_shots[0].camera.width
width = 4 * subshot_width
height = width // 2
image = cv2.resize(original, (width, height), interpolation=interpolation)
mint = cv2.INTER_LINEAR if interpolation == cv2.INTER_AREA else interpolation
res = {}
for subshot in undistorted_shots:
undistorted = render_perspective_view_of_a_panorama(
image, shot, subshot, mint)
res[subshot.id] = scale_image(undistorted, max_size)
return res
else:
raise NotImplementedError(
'Undistort not implemented for projection type: {}'.format(
shot.camera.projection_type)) | [
"def",
"undistort_image",
"(",
"shot",
",",
"undistorted_shots",
",",
"original",
",",
"interpolation",
",",
"max_size",
")",
":",
"if",
"original",
"is",
"None",
":",
"return",
"projection_type",
"=",
"shot",
".",
"camera",
".",
"projection_type",
"if",
"projection_type",
"in",
"[",
"'perspective'",
",",
"'brown'",
",",
"'fisheye'",
"]",
":",
"undistort_function",
"=",
"{",
"'perspective'",
":",
"undistort_perspective_image",
",",
"'brown'",
":",
"undistort_brown_image",
",",
"'fisheye'",
":",
"undistort_fisheye_image",
",",
"}",
"new_camera",
"=",
"undistorted_shots",
"[",
"0",
"]",
".",
"camera",
"uf",
"=",
"undistort_function",
"[",
"projection_type",
"]",
"undistorted",
"=",
"uf",
"(",
"original",
",",
"shot",
".",
"camera",
",",
"new_camera",
",",
"interpolation",
")",
"return",
"{",
"shot",
".",
"id",
":",
"scale_image",
"(",
"undistorted",
",",
"max_size",
")",
"}",
"elif",
"projection_type",
"in",
"[",
"'equirectangular'",
",",
"'spherical'",
"]",
":",
"subshot_width",
"=",
"undistorted_shots",
"[",
"0",
"]",
".",
"camera",
".",
"width",
"width",
"=",
"4",
"*",
"subshot_width",
"height",
"=",
"width",
"//",
"2",
"image",
"=",
"cv2",
".",
"resize",
"(",
"original",
",",
"(",
"width",
",",
"height",
")",
",",
"interpolation",
"=",
"interpolation",
")",
"mint",
"=",
"cv2",
".",
"INTER_LINEAR",
"if",
"interpolation",
"==",
"cv2",
".",
"INTER_AREA",
"else",
"interpolation",
"res",
"=",
"{",
"}",
"for",
"subshot",
"in",
"undistorted_shots",
":",
"undistorted",
"=",
"render_perspective_view_of_a_panorama",
"(",
"image",
",",
"shot",
",",
"subshot",
",",
"mint",
")",
"res",
"[",
"subshot",
".",
"id",
"]",
"=",
"scale_image",
"(",
"undistorted",
",",
"max_size",
")",
"return",
"res",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Undistort not implemented for projection type: {}'",
".",
"format",
"(",
"shot",
".",
"camera",
".",
"projection_type",
")",
")"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/commands/undistort.py#L111-L153 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/more-itertools/py2/more_itertools/more.py | python | with_iter | (context_manager) | Wrap an iterable in a ``with`` statement, so it closes once exhausted.
For example, this will close the file when the iterator is exhausted::
upper_lines = (line.upper() for line in with_iter(open('foo')))
Any context manager which returns an iterable is a candidate for
``with_iter``. | Wrap an iterable in a ``with`` statement, so it closes once exhausted. | [
"Wrap",
"an",
"iterable",
"in",
"a",
"with",
"statement",
"so",
"it",
"closes",
"once",
"exhausted",
"."
] | def with_iter(context_manager):
"""Wrap an iterable in a ``with`` statement, so it closes once exhausted.
For example, this will close the file when the iterator is exhausted::
upper_lines = (line.upper() for line in with_iter(open('foo')))
Any context manager which returns an iterable is a candidate for
``with_iter``.
"""
with context_manager as iterable:
for item in iterable:
yield item | [
"def",
"with_iter",
"(",
"context_manager",
")",
":",
"with",
"context_manager",
"as",
"iterable",
":",
"for",
"item",
"in",
"iterable",
":",
"yield",
"item"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py2/more_itertools/more.py#L466-L479 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/filters.py | python | do_indent | (s, width=4, indentfirst=False) | return rv | Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
{{ mytext|indent(2, true) }}
indent by two spaces and indent the first line too. | Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter: | [
"Return",
"a",
"copy",
"of",
"the",
"passed",
"string",
"each",
"line",
"indented",
"by",
"4",
"spaces",
".",
"The",
"first",
"line",
"is",
"not",
"indented",
".",
"If",
"you",
"want",
"to",
"change",
"the",
"number",
"of",
"spaces",
"or",
"indent",
"the",
"first",
"line",
"too",
"you",
"can",
"pass",
"additional",
"parameters",
"to",
"the",
"filter",
":"
] | def do_indent(s, width=4, indentfirst=False):
"""Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
{{ mytext|indent(2, true) }}
indent by two spaces and indent the first line too.
"""
indention = u' ' * width
rv = (u'\n' + indention).join(s.splitlines())
if indentfirst:
rv = indention + rv
return rv | [
"def",
"do_indent",
"(",
"s",
",",
"width",
"=",
"4",
",",
"indentfirst",
"=",
"False",
")",
":",
"indention",
"=",
"u' '",
"*",
"width",
"rv",
"=",
"(",
"u'\\n'",
"+",
"indention",
")",
".",
"join",
"(",
"s",
".",
"splitlines",
"(",
")",
")",
"if",
"indentfirst",
":",
"rv",
"=",
"indention",
"+",
"rv",
"return",
"rv"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/filters.py#L430-L445 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.