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
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/v8/third_party/jinja2/filters.py | python | do_join | (eval_ctx, value, d=u'', attribute=None) | return soft_unicode(d).join(imap(soft_unicode, value)) | Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
.. sourcecode:: jinja
{{ users|join(', ', attribute='username') }}
.. versionadded:: 2.6
The `attribute` parameter was added. | Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter: | [
"Return",
"a",
"string",
"which",
"is",
"the",
"concatenation",
"of",
"the",
"strings",
"in",
"the",
"sequence",
".",
"The",
"separator",
"between",
"elements",
"is",
"an",
"empty",
"string",
"per",
"default",
"you",
"can",
"define",
"it",
"with",
"the",
"optional",
"parameter",
":"
] | def do_join(eval_ctx, value, d=u'', attribute=None):
"""Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
.. sourcecode:: jinja
{{ users|join(', ', attribute='username') }}
.. versionadded:: 2.6
The `attribute` parameter was added.
"""
if attribute is not None:
value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
# no automatic escaping? joining is a lot eaiser then
if not eval_ctx.autoescape:
return text_type(d).join(imap(text_type, value))
# if the delimiter doesn't have an html representation we check
# if any of the items has. If yes we do a coercion to Markup
if not hasattr(d, '__html__'):
value = list(value)
do_escape = False
for idx, item in enumerate(value):
if hasattr(item, '__html__'):
do_escape = True
else:
value[idx] = text_type(item)
if do_escape:
d = escape(d)
else:
d = text_type(d)
return d.join(value)
# no html involved, to normal joining
return soft_unicode(d).join(imap(soft_unicode, value)) | [
"def",
"do_join",
"(",
"eval_ctx",
",",
"value",
",",
"d",
"=",
"u''",
",",
"attribute",
"=",
"None",
")",
":",
"if",
"attribute",
"is",
"not",
"None",
":",
"value",
"=",
"imap",
"(",
"make_attrgetter",
"(",
"eval_ctx",
".",
"environment",
",",
"attribute",
")",
",",
"value",
")",
"# no automatic escaping? joining is a lot eaiser then",
"if",
"not",
"eval_ctx",
".",
"autoescape",
":",
"return",
"text_type",
"(",
"d",
")",
".",
"join",
"(",
"imap",
"(",
"text_type",
",",
"value",
")",
")",
"# if the delimiter doesn't have an html representation we check",
"# if any of the items has. If yes we do a coercion to Markup",
"if",
"not",
"hasattr",
"(",
"d",
",",
"'__html__'",
")",
":",
"value",
"=",
"list",
"(",
"value",
")",
"do_escape",
"=",
"False",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"item",
",",
"'__html__'",
")",
":",
"do_escape",
"=",
"True",
"else",
":",
"value",
"[",
"idx",
"]",
"=",
"text_type",
"(",
"item",
")",
"if",
"do_escape",
":",
"d",
"=",
"escape",
"(",
"d",
")",
"else",
":",
"d",
"=",
"text_type",
"(",
"d",
")",
"return",
"d",
".",
"join",
"(",
"value",
")",
"# no html involved, to normal joining",
"return",
"soft_unicode",
"(",
"d",
")",
".",
"join",
"(",
"imap",
"(",
"soft_unicode",
",",
"value",
")",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/filters.py#L378-L424 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py | python | Node.prefix | (self) | return self.children[0].prefix | The whitespace and comments preceding this node in the input. | The whitespace and comments preceding this node in the input. | [
"The",
"whitespace",
"and",
"comments",
"preceding",
"this",
"node",
"in",
"the",
"input",
"."
] | def prefix(self):
"""
The whitespace and comments preceding this node in the input.
"""
if not self.children:
return ""
return self.children[0].prefix | [
"def",
"prefix",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"children",
":",
"return",
"\"\"",
"return",
"self",
".",
"children",
"[",
"0",
"]",
".",
"prefix"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py#L275-L281 |
|
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn.py | python | DNNClassifier._get_train_ops | (self, features, targets) | return super(DNNClassifier, self)._get_train_ops(features, targets) | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def _get_train_ops(self, features, targets):
"""See base class."""
self._validate_dnn_feature_columns(features)
return super(DNNClassifier, self)._get_train_ops(features, targets) | [
"def",
"_get_train_ops",
"(",
"self",
",",
"features",
",",
"targets",
")",
":",
"self",
".",
"_validate_dnn_feature_columns",
"(",
"features",
")",
"return",
"super",
"(",
"DNNClassifier",
",",
"self",
")",
".",
"_get_train_ops",
"(",
"features",
",",
"targets",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn.py#L181-L184 |
|
raspberrypi/tools | 13474ee775d0c5ec8a7da4fb0a9fa84187abfc87 | arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/share/gdb/python/gdb/types.py | python | apply_type_recognizers | (recognizers, type_obj) | return None | Apply the given list of type recognizers to the type TYPE_OBJ.
If any recognizer in the list recognizes TYPE_OBJ, returns the name
given by the recognizer. Otherwise, this returns None. | Apply the given list of type recognizers to the type TYPE_OBJ.
If any recognizer in the list recognizes TYPE_OBJ, returns the name
given by the recognizer. Otherwise, this returns None. | [
"Apply",
"the",
"given",
"list",
"of",
"type",
"recognizers",
"to",
"the",
"type",
"TYPE_OBJ",
".",
"If",
"any",
"recognizer",
"in",
"the",
"list",
"recognizes",
"TYPE_OBJ",
"returns",
"the",
"name",
"given",
"by",
"the",
"recognizer",
".",
"Otherwise",
"this",
"returns",
"None",
"."
] | def apply_type_recognizers(recognizers, type_obj):
"""Apply the given list of type recognizers to the type TYPE_OBJ.
If any recognizer in the list recognizes TYPE_OBJ, returns the name
given by the recognizer. Otherwise, this returns None."""
for r in recognizers:
result = r.recognize(type_obj)
if result is not None:
return result
return None | [
"def",
"apply_type_recognizers",
"(",
"recognizers",
",",
"type_obj",
")",
":",
"for",
"r",
"in",
"recognizers",
":",
"result",
"=",
"r",
".",
"recognize",
"(",
"type_obj",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"return",
"None"
] | https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/share/gdb/python/gdb/types.py#L158-L166 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/spatial/kdtree.py | python | Rectangle.max_distance_point | (self, x, p=2.) | return minkowski_distance(0, np.maximum(self.maxes-x,x-self.mins),p) | Return the maximum distance between input and points in the hyperrectangle.
Parameters
----------
x : array_like
Input array.
p : float, optional
Input. | Return the maximum distance between input and points in the hyperrectangle. | [
"Return",
"the",
"maximum",
"distance",
"between",
"input",
"and",
"points",
"in",
"the",
"hyperrectangle",
"."
] | def max_distance_point(self, x, p=2.):
"""
Return the maximum distance between input and points in the hyperrectangle.
Parameters
----------
x : array_like
Input array.
p : float, optional
Input.
"""
return minkowski_distance(0, np.maximum(self.maxes-x,x-self.mins),p) | [
"def",
"max_distance_point",
"(",
"self",
",",
"x",
",",
"p",
"=",
"2.",
")",
":",
"return",
"minkowski_distance",
"(",
"0",
",",
"np",
".",
"maximum",
"(",
"self",
".",
"maxes",
"-",
"x",
",",
"x",
"-",
"self",
".",
"mins",
")",
",",
"p",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/spatial/kdtree.py#L133-L145 |
|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/utils.py | python | get_python_long_version | (path) | return ver | Return long version (X.Y.Z) for the Python distribution located in
*path* | Return long version (X.Y.Z) for the Python distribution located in
*path* | [
"Return",
"long",
"version",
"(",
"X",
".",
"Y",
".",
"Z",
")",
"for",
"the",
"Python",
"distribution",
"located",
"in",
"*",
"path",
"*"
] | def get_python_long_version(path):
"""Return long version (X.Y.Z) for the Python distribution located in
*path*"""
ver = python_query("import sys; print('%d.%d.%d' % "\
"(sys.version_info.major, sys.version_info.minor,"\
"sys.version_info.micro))", path)
if re.match(r'([0-9]*)\.([0-9]*)\.([0-9]*)', ver) is None:
ver = None
return ver | [
"def",
"get_python_long_version",
"(",
"path",
")",
":",
"ver",
"=",
"python_query",
"(",
"\"import sys; print('%d.%d.%d' % \"",
"\"(sys.version_info.major, sys.version_info.minor,\"",
"\"sys.version_info.micro))\"",
",",
"path",
")",
"if",
"re",
".",
"match",
"(",
"r'([0-9]*)\\.([0-9]*)\\.([0-9]*)'",
",",
"ver",
")",
"is",
"None",
":",
"ver",
"=",
"None",
"return",
"ver"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/utils.py#L235-L243 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/parenmatch.py | python | ParenMatch.set_timeout_last | (self) | The last highlight created will be removed after FLASH_DELAY millisecs | The last highlight created will be removed after FLASH_DELAY millisecs | [
"The",
"last",
"highlight",
"created",
"will",
"be",
"removed",
"after",
"FLASH_DELAY",
"millisecs"
] | def set_timeout_last(self):
"""The last highlight created will be removed after FLASH_DELAY millisecs"""
# associate a counter with an event; only disable the "paren"
# tag if the event is for the most recent timer.
self.counter += 1
self.editwin.text_frame.after(
self.FLASH_DELAY,
lambda self=self, c=self.counter: self.handle_restore_timer(c)) | [
"def",
"set_timeout_last",
"(",
"self",
")",
":",
"# associate a counter with an event; only disable the \"paren\"",
"# tag if the event is for the most recent timer.",
"self",
".",
"counter",
"+=",
"1",
"self",
".",
"editwin",
".",
"text_frame",
".",
"after",
"(",
"self",
".",
"FLASH_DELAY",
",",
"lambda",
"self",
"=",
"self",
",",
"c",
"=",
"self",
".",
"counter",
":",
"self",
".",
"handle_restore_timer",
"(",
"c",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/parenmatch.py#L168-L175 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | Regex.sub | (self, repl) | return self.addParseAction(pa) | r"""
Return Regex with an attached parse action to transform the parsed
result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.
Example::
make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>")
print(make_html.transformString("h1:main title:"))
# prints "<h1>main title</h1>" | r"""
Return Regex with an attached parse action to transform the parsed
result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. | [
"r",
"Return",
"Regex",
"with",
"an",
"attached",
"parse",
"action",
"to",
"transform",
"the",
"parsed",
"result",
"as",
"if",
"called",
"using",
"re",
".",
"sub",
"(",
"expr",
"repl",
"string",
")",
"<https",
":",
"//",
"docs",
".",
"python",
".",
"org",
"/",
"3",
"/",
"library",
"/",
"re",
".",
"html#re",
".",
"sub",
">",
"_",
"."
] | def sub(self, repl):
r"""
Return Regex with an attached parse action to transform the parsed
result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.
Example::
make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>")
print(make_html.transformString("h1:main title:"))
# prints "<h1>main title</h1>"
"""
if self.asGroupList:
warnings.warn("cannot use sub() with Regex(asGroupList=True)",
SyntaxWarning, stacklevel=2)
raise SyntaxError()
if self.asMatch and callable(repl):
warnings.warn("cannot use sub() with a callable with Regex(asMatch=True)",
SyntaxWarning, stacklevel=2)
raise SyntaxError()
if self.asMatch:
def pa(tokens):
return tokens[0].expand(repl)
else:
def pa(tokens):
return self.re.sub(repl, tokens[0])
return self.addParseAction(pa) | [
"def",
"sub",
"(",
"self",
",",
"repl",
")",
":",
"if",
"self",
".",
"asGroupList",
":",
"warnings",
".",
"warn",
"(",
"\"cannot use sub() with Regex(asGroupList=True)\"",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"raise",
"SyntaxError",
"(",
")",
"if",
"self",
".",
"asMatch",
"and",
"callable",
"(",
"repl",
")",
":",
"warnings",
".",
"warn",
"(",
"\"cannot use sub() with a callable with Regex(asMatch=True)\"",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"raise",
"SyntaxError",
"(",
")",
"if",
"self",
".",
"asMatch",
":",
"def",
"pa",
"(",
"tokens",
")",
":",
"return",
"tokens",
"[",
"0",
"]",
".",
"expand",
"(",
"repl",
")",
"else",
":",
"def",
"pa",
"(",
"tokens",
")",
":",
"return",
"self",
".",
"re",
".",
"sub",
"(",
"repl",
",",
"tokens",
"[",
"0",
"]",
")",
"return",
"self",
".",
"addParseAction",
"(",
"pa",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L3381-L3408 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py | python | CheckList.setstatus | (self, entrypath, mode='on') | Sets the status of entryPath to be status. A bitmap will be
displayed next to the entry its status is on, off or default. | Sets the status of entryPath to be status. A bitmap will be
displayed next to the entry its status is on, off or default. | [
"Sets",
"the",
"status",
"of",
"entryPath",
"to",
"be",
"status",
".",
"A",
"bitmap",
"will",
"be",
"displayed",
"next",
"to",
"the",
"entry",
"its",
"status",
"is",
"on",
"off",
"or",
"default",
"."
] | def setstatus(self, entrypath, mode='on'):
'''Sets the status of entryPath to be status. A bitmap will be
displayed next to the entry its status is on, off or default.'''
self.tk.call(self._w, 'setstatus', entrypath, mode) | [
"def",
"setstatus",
"(",
"self",
",",
"entrypath",
",",
"mode",
"=",
"'on'",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'setstatus'",
",",
"entrypath",
",",
"mode",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py#L1612-L1615 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/filters.py | python | do_reverse | (value: t.Union[str, t.Iterable[V]]) | Reverse the object or return an iterator that iterates over it the other
way round. | Reverse the object or return an iterator that iterates over it the other
way round. | [
"Reverse",
"the",
"object",
"or",
"return",
"an",
"iterator",
"that",
"iterates",
"over",
"it",
"the",
"other",
"way",
"round",
"."
] | def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
"""Reverse the object or return an iterator that iterates over it the other
way round.
"""
if isinstance(value, str):
return value[::-1]
try:
return reversed(value) # type: ignore
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError as e:
raise FilterArgumentError("argument must be iterable") from e | [
"def",
"do_reverse",
"(",
"value",
":",
"t",
".",
"Union",
"[",
"str",
",",
"t",
".",
"Iterable",
"[",
"V",
"]",
"]",
")",
"->",
"t",
".",
"Union",
"[",
"str",
",",
"t",
".",
"Iterable",
"[",
"V",
"]",
"]",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"[",
":",
":",
"-",
"1",
"]",
"try",
":",
"return",
"reversed",
"(",
"value",
")",
"# type: ignore",
"except",
"TypeError",
":",
"try",
":",
"rv",
"=",
"list",
"(",
"value",
")",
"rv",
".",
"reverse",
"(",
")",
"return",
"rv",
"except",
"TypeError",
"as",
"e",
":",
"raise",
"FilterArgumentError",
"(",
"\"argument must be iterable\"",
")",
"from",
"e"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L1339-L1354 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/concurrent/futures/_base.py | python | Future.set_result | (self, result) | Sets the return value of work associated with the future.
Should only be used by Executor implementations and unit tests. | Sets the return value of work associated with the future. | [
"Sets",
"the",
"return",
"value",
"of",
"work",
"associated",
"with",
"the",
"future",
"."
] | def set_result(self, result):
"""Sets the return value of work associated with the future.
Should only be used by Executor implementations and unit tests.
"""
with self._condition:
if self._state in {CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED}:
raise InvalidStateError('{}: {!r}'.format(self._state, self))
self._result = result
self._state = FINISHED
for waiter in self._waiters:
waiter.add_result(self)
self._condition.notify_all()
self._invoke_callbacks() | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"with",
"self",
".",
"_condition",
":",
"if",
"self",
".",
"_state",
"in",
"{",
"CANCELLED",
",",
"CANCELLED_AND_NOTIFIED",
",",
"FINISHED",
"}",
":",
"raise",
"InvalidStateError",
"(",
"'{}: {!r}'",
".",
"format",
"(",
"self",
".",
"_state",
",",
"self",
")",
")",
"self",
".",
"_result",
"=",
"result",
"self",
".",
"_state",
"=",
"FINISHED",
"for",
"waiter",
"in",
"self",
".",
"_waiters",
":",
"waiter",
".",
"add_result",
"(",
"self",
")",
"self",
".",
"_condition",
".",
"notify_all",
"(",
")",
"self",
".",
"_invoke_callbacks",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/concurrent/futures/_base.py#L527-L540 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/calltip.py | python | Calltip.force_open_calltip_event | (self, event) | return "break" | The user selected the menu entry or hotkey, open the tip. | The user selected the menu entry or hotkey, open the tip. | [
"The",
"user",
"selected",
"the",
"menu",
"entry",
"or",
"hotkey",
"open",
"the",
"tip",
"."
] | def force_open_calltip_event(self, event):
"The user selected the menu entry or hotkey, open the tip."
self.open_calltip(True)
return "break" | [
"def",
"force_open_calltip_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"open_calltip",
"(",
"True",
")",
"return",
"\"break\""
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/calltip.py#L41-L44 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/grep.py | python | GrepDialog.default_command | (self, event=None) | Grep for search pattern in file path. The default command is bound
to <Return>.
If entry values are populated, set OutputWindow as stdout
and perform search. The search dialog is closed automatically
when the search begins. | Grep for search pattern in file path. The default command is bound
to <Return>. | [
"Grep",
"for",
"search",
"pattern",
"in",
"file",
"path",
".",
"The",
"default",
"command",
"is",
"bound",
"to",
"<Return",
">",
"."
] | def default_command(self, event=None):
"""Grep for search pattern in file path. The default command is bound
to <Return>.
If entry values are populated, set OutputWindow as stdout
and perform search. The search dialog is closed automatically
when the search begins.
"""
prog = self.engine.getprog()
if not prog:
return
path = self.globvar.get()
if not path:
self.top.bell()
return
from idlelib.outwin import OutputWindow # leave here!
save = sys.stdout
try:
sys.stdout = OutputWindow(self.flist)
self.grep_it(prog, path)
finally:
sys.stdout = save | [
"def",
"default_command",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"prog",
"=",
"self",
".",
"engine",
".",
"getprog",
"(",
")",
"if",
"not",
"prog",
":",
"return",
"path",
"=",
"self",
".",
"globvar",
".",
"get",
"(",
")",
"if",
"not",
"path",
":",
"self",
".",
"top",
".",
"bell",
"(",
")",
"return",
"from",
"idlelib",
".",
"outwin",
"import",
"OutputWindow",
"# leave here!",
"save",
"=",
"sys",
".",
"stdout",
"try",
":",
"sys",
".",
"stdout",
"=",
"OutputWindow",
"(",
"self",
".",
"flist",
")",
"self",
".",
"grep_it",
"(",
"prog",
",",
"path",
")",
"finally",
":",
"sys",
".",
"stdout",
"=",
"save"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/grep.py#L129-L150 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Clipboard.Clear | (*args, **kwargs) | return _misc_.Clipboard_Clear(*args, **kwargs) | Clear(self)
Clears data from the clipboard object and also the system's clipboard
if possible. | Clear(self) | [
"Clear",
"(",
"self",
")"
] | def Clear(*args, **kwargs):
"""
Clear(self)
Clears data from the clipboard object and also the system's clipboard
if possible.
"""
return _misc_.Clipboard_Clear(*args, **kwargs) | [
"def",
"Clear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Clipboard_Clear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5865-L5872 |
|
Illumina/manta | 75b5c38d4fcd2f6961197b28a41eb61856f2d976 | src/python/lib/mantaWorkflow.py | python | runLocusGraph | (self,taskPrefix="",dependencies=None) | return nextStepWait | Create the full SV locus graph | Create the full SV locus graph | [
"Create",
"the",
"full",
"SV",
"locus",
"graph"
] | def runLocusGraph(self,taskPrefix="",dependencies=None):
"""
Create the full SV locus graph
"""
statsPath=self.paths.getStatsPath()
graphPath=self.paths.getGraphPath()
graphStatsPath=self.paths.getGraphStatsPath()
tmpGraphDir=self.paths.getTmpGraphDir()
makeTmpGraphDirCmd = getMkdirCmd() + [tmpGraphDir]
dirTask = self.addTask(preJoin(taskPrefix,"makeGraphTmpDir"), makeTmpGraphDirCmd, dependencies=dependencies, isForceLocal=True)
tmpGraphFiles = []
graphTasks = set()
for gsegGroup in getGenomeSegmentGroups(getNextGenomeSegment(self.params)) :
assert(len(gsegGroup) != 0)
gid=gsegGroup[0].id
if len(gsegGroup) > 1 :
gid += "_to_"+gsegGroup[-1].id
tmpGraphFiles.append(self.paths.getTmpGraphFile(gid))
graphCmd = [ self.params.mantaGraphBin ]
graphCmd.extend(["--output-file", tmpGraphFiles[-1]])
graphCmd.extend(["--align-stats",statsPath])
for gseg in gsegGroup :
graphCmd.extend(["--region",gseg.bamRegion])
graphCmd.extend(["--min-candidate-sv-size", self.params.minCandidateVariantSize])
graphCmd.extend(["--min-edge-observations", self.params.minEdgeObservations])
graphCmd.extend(["--ref",self.params.referenceFasta])
for bamPath in self.params.normalBamList :
graphCmd.extend(["--align-file",bamPath])
for bamPath in self.params.tumorBamList :
graphCmd.extend(["--tumor-align-file",bamPath])
if self.params.isHighDepthFilter :
graphCmd.extend(["--chrom-depth", self.paths.getChromDepth()])
if self.params.isIgnoreAnomProperPair :
graphCmd.append("--ignore-anom-proper-pair")
if self.params.isRNA :
graphCmd.append("--rna")
graphTask=preJoin(taskPrefix,"makeLocusGraph_"+gid)
graphTasks.add(self.addTask(graphTask,graphCmd,dependencies=dirTask,memMb=self.params.estimateMemMb))
if len(tmpGraphFiles) == 0 :
raise Exception("No SV Locus graphs to create. Possible target region parse error.")
tmpGraphFileList = self.paths.getTmpGraphFileListPath()
tmpGraphFileListTask = preJoin(taskPrefix,"mergeLocusGraphInputList")
self.addWorkflowTask(tmpGraphFileListTask,listFileWorkflow(tmpGraphFileList,tmpGraphFiles),dependencies=graphTasks)
mergeCmd = [ self.params.mantaGraphMergeBin ]
mergeCmd.extend(["--output-file", graphPath])
mergeCmd.extend(["--graph-file-list",tmpGraphFileList])
mergeTask = self.addTask(preJoin(taskPrefix,"mergeLocusGraph"),mergeCmd,dependencies=tmpGraphFileListTask,memMb=self.params.mergeMemMb)
# Run a separate process to rigorously check that the final graph is valid, the sv candidate generators will check as well, but
# this makes the check much more clear:
checkCmd = [ self.params.mantaGraphCheckBin ]
checkCmd.extend(["--graph-file", graphPath])
checkTask = self.addTask(preJoin(taskPrefix,"checkLocusGraph"),checkCmd,dependencies=mergeTask,memMb=self.params.mergeMemMb)
if not self.params.isRetainTempFiles :
rmGraphTmpCmd = getRmdirCmd() + [tmpGraphDir]
rmTask=self.addTask(preJoin(taskPrefix,"removeTmpDir"),rmGraphTmpCmd,dependencies=mergeTask)
graphStatsCmd = [self.params.mantaGraphStatsBin,"--global"]
graphStatsCmd.extend(["--graph-file",graphPath])
graphStatsCmd.extend(["--output-file",graphStatsPath])
graphStatsTask = self.addTask(preJoin(taskPrefix,"locusGraphStats"),graphStatsCmd,dependencies=mergeTask,memMb=self.params.mergeMemMb)
nextStepWait = set()
nextStepWait.add(checkTask)
return nextStepWait | [
"def",
"runLocusGraph",
"(",
"self",
",",
"taskPrefix",
"=",
"\"\"",
",",
"dependencies",
"=",
"None",
")",
":",
"statsPath",
"=",
"self",
".",
"paths",
".",
"getStatsPath",
"(",
")",
"graphPath",
"=",
"self",
".",
"paths",
".",
"getGraphPath",
"(",
")",
"graphStatsPath",
"=",
"self",
".",
"paths",
".",
"getGraphStatsPath",
"(",
")",
"tmpGraphDir",
"=",
"self",
".",
"paths",
".",
"getTmpGraphDir",
"(",
")",
"makeTmpGraphDirCmd",
"=",
"getMkdirCmd",
"(",
")",
"+",
"[",
"tmpGraphDir",
"]",
"dirTask",
"=",
"self",
".",
"addTask",
"(",
"preJoin",
"(",
"taskPrefix",
",",
"\"makeGraphTmpDir\"",
")",
",",
"makeTmpGraphDirCmd",
",",
"dependencies",
"=",
"dependencies",
",",
"isForceLocal",
"=",
"True",
")",
"tmpGraphFiles",
"=",
"[",
"]",
"graphTasks",
"=",
"set",
"(",
")",
"for",
"gsegGroup",
"in",
"getGenomeSegmentGroups",
"(",
"getNextGenomeSegment",
"(",
"self",
".",
"params",
")",
")",
":",
"assert",
"(",
"len",
"(",
"gsegGroup",
")",
"!=",
"0",
")",
"gid",
"=",
"gsegGroup",
"[",
"0",
"]",
".",
"id",
"if",
"len",
"(",
"gsegGroup",
")",
">",
"1",
":",
"gid",
"+=",
"\"_to_\"",
"+",
"gsegGroup",
"[",
"-",
"1",
"]",
".",
"id",
"tmpGraphFiles",
".",
"append",
"(",
"self",
".",
"paths",
".",
"getTmpGraphFile",
"(",
"gid",
")",
")",
"graphCmd",
"=",
"[",
"self",
".",
"params",
".",
"mantaGraphBin",
"]",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--output-file\"",
",",
"tmpGraphFiles",
"[",
"-",
"1",
"]",
"]",
")",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--align-stats\"",
",",
"statsPath",
"]",
")",
"for",
"gseg",
"in",
"gsegGroup",
":",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--region\"",
",",
"gseg",
".",
"bamRegion",
"]",
")",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--min-candidate-sv-size\"",
",",
"self",
".",
"params",
".",
"minCandidateVariantSize",
"]",
")",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--min-edge-observations\"",
",",
"self",
".",
"params",
".",
"minEdgeObservations",
"]",
")",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--ref\"",
",",
"self",
".",
"params",
".",
"referenceFasta",
"]",
")",
"for",
"bamPath",
"in",
"self",
".",
"params",
".",
"normalBamList",
":",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--align-file\"",
",",
"bamPath",
"]",
")",
"for",
"bamPath",
"in",
"self",
".",
"params",
".",
"tumorBamList",
":",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--tumor-align-file\"",
",",
"bamPath",
"]",
")",
"if",
"self",
".",
"params",
".",
"isHighDepthFilter",
":",
"graphCmd",
".",
"extend",
"(",
"[",
"\"--chrom-depth\"",
",",
"self",
".",
"paths",
".",
"getChromDepth",
"(",
")",
"]",
")",
"if",
"self",
".",
"params",
".",
"isIgnoreAnomProperPair",
":",
"graphCmd",
".",
"append",
"(",
"\"--ignore-anom-proper-pair\"",
")",
"if",
"self",
".",
"params",
".",
"isRNA",
":",
"graphCmd",
".",
"append",
"(",
"\"--rna\"",
")",
"graphTask",
"=",
"preJoin",
"(",
"taskPrefix",
",",
"\"makeLocusGraph_\"",
"+",
"gid",
")",
"graphTasks",
".",
"add",
"(",
"self",
".",
"addTask",
"(",
"graphTask",
",",
"graphCmd",
",",
"dependencies",
"=",
"dirTask",
",",
"memMb",
"=",
"self",
".",
"params",
".",
"estimateMemMb",
")",
")",
"if",
"len",
"(",
"tmpGraphFiles",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"No SV Locus graphs to create. Possible target region parse error.\"",
")",
"tmpGraphFileList",
"=",
"self",
".",
"paths",
".",
"getTmpGraphFileListPath",
"(",
")",
"tmpGraphFileListTask",
"=",
"preJoin",
"(",
"taskPrefix",
",",
"\"mergeLocusGraphInputList\"",
")",
"self",
".",
"addWorkflowTask",
"(",
"tmpGraphFileListTask",
",",
"listFileWorkflow",
"(",
"tmpGraphFileList",
",",
"tmpGraphFiles",
")",
",",
"dependencies",
"=",
"graphTasks",
")",
"mergeCmd",
"=",
"[",
"self",
".",
"params",
".",
"mantaGraphMergeBin",
"]",
"mergeCmd",
".",
"extend",
"(",
"[",
"\"--output-file\"",
",",
"graphPath",
"]",
")",
"mergeCmd",
".",
"extend",
"(",
"[",
"\"--graph-file-list\"",
",",
"tmpGraphFileList",
"]",
")",
"mergeTask",
"=",
"self",
".",
"addTask",
"(",
"preJoin",
"(",
"taskPrefix",
",",
"\"mergeLocusGraph\"",
")",
",",
"mergeCmd",
",",
"dependencies",
"=",
"tmpGraphFileListTask",
",",
"memMb",
"=",
"self",
".",
"params",
".",
"mergeMemMb",
")",
"# Run a separate process to rigorously check that the final graph is valid, the sv candidate generators will check as well, but",
"# this makes the check much more clear:",
"checkCmd",
"=",
"[",
"self",
".",
"params",
".",
"mantaGraphCheckBin",
"]",
"checkCmd",
".",
"extend",
"(",
"[",
"\"--graph-file\"",
",",
"graphPath",
"]",
")",
"checkTask",
"=",
"self",
".",
"addTask",
"(",
"preJoin",
"(",
"taskPrefix",
",",
"\"checkLocusGraph\"",
")",
",",
"checkCmd",
",",
"dependencies",
"=",
"mergeTask",
",",
"memMb",
"=",
"self",
".",
"params",
".",
"mergeMemMb",
")",
"if",
"not",
"self",
".",
"params",
".",
"isRetainTempFiles",
":",
"rmGraphTmpCmd",
"=",
"getRmdirCmd",
"(",
")",
"+",
"[",
"tmpGraphDir",
"]",
"rmTask",
"=",
"self",
".",
"addTask",
"(",
"preJoin",
"(",
"taskPrefix",
",",
"\"removeTmpDir\"",
")",
",",
"rmGraphTmpCmd",
",",
"dependencies",
"=",
"mergeTask",
")",
"graphStatsCmd",
"=",
"[",
"self",
".",
"params",
".",
"mantaGraphStatsBin",
",",
"\"--global\"",
"]",
"graphStatsCmd",
".",
"extend",
"(",
"[",
"\"--graph-file\"",
",",
"graphPath",
"]",
")",
"graphStatsCmd",
".",
"extend",
"(",
"[",
"\"--output-file\"",
",",
"graphStatsPath",
"]",
")",
"graphStatsTask",
"=",
"self",
".",
"addTask",
"(",
"preJoin",
"(",
"taskPrefix",
",",
"\"locusGraphStats\"",
")",
",",
"graphStatsCmd",
",",
"dependencies",
"=",
"mergeTask",
",",
"memMb",
"=",
"self",
".",
"params",
".",
"mergeMemMb",
")",
"nextStepWait",
"=",
"set",
"(",
")",
"nextStepWait",
".",
"add",
"(",
"checkTask",
")",
"return",
"nextStepWait"
] | https://github.com/Illumina/manta/blob/75b5c38d4fcd2f6961197b28a41eb61856f2d976/src/python/lib/mantaWorkflow.py#L235-L313 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/bdist_rpm.py | python | bdist_rpm._format_changelog | (self, changelog) | return new_changelog | Format the changelog correctly and convert it to a list of strings | Format the changelog correctly and convert it to a list of strings | [
"Format",
"the",
"changelog",
"correctly",
"and",
"convert",
"it",
"to",
"a",
"list",
"of",
"strings"
] | def _format_changelog(self, changelog):
"""Format the changelog correctly and convert it to a list of strings
"""
if not changelog:
return changelog
new_changelog = []
for line in string.split(string.strip(changelog), '\n'):
line = string.strip(line)
if line[0] == '*':
new_changelog.extend(['', line])
elif line[0] == '-':
new_changelog.append(line)
else:
new_changelog.append(' ' + line)
# strip trailing newline inserted by first changelog entry
if not new_changelog[0]:
del new_changelog[0]
return new_changelog | [
"def",
"_format_changelog",
"(",
"self",
",",
"changelog",
")",
":",
"if",
"not",
"changelog",
":",
"return",
"changelog",
"new_changelog",
"=",
"[",
"]",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"string",
".",
"strip",
"(",
"changelog",
")",
",",
"'\\n'",
")",
":",
"line",
"=",
"string",
".",
"strip",
"(",
"line",
")",
"if",
"line",
"[",
"0",
"]",
"==",
"'*'",
":",
"new_changelog",
".",
"extend",
"(",
"[",
"''",
",",
"line",
"]",
")",
"elif",
"line",
"[",
"0",
"]",
"==",
"'-'",
":",
"new_changelog",
".",
"append",
"(",
"line",
")",
"else",
":",
"new_changelog",
".",
"append",
"(",
"' '",
"+",
"line",
")",
"# strip trailing newline inserted by first changelog entry",
"if",
"not",
"new_changelog",
"[",
"0",
"]",
":",
"del",
"new_changelog",
"[",
"0",
"]",
"return",
"new_changelog"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/bdist_rpm.py#L564-L583 |
|
facebook/fboss | 60063db1df37c2ec0e7dcd0955c54885ea9bf7f0 | build/fbcode_builder/fbcode_builder.py | python | FBCodeBuilder.render | (self, steps) | return res | Converts nested actions to your builder's expected output format.
Typically takes the output of build(). | [] | def render(self, steps):
"""
Converts nested actions to your builder's expected output format.
Typically takes the output of build().
"""
res = self._render_impl(steps) # Implementation-dependent
# Now that the output is rendered, we expect all options to have
# been used.
unused_options = set(self._options_do_not_access)
unused_options -= self.options_used
if unused_options:
raise RuntimeError(
"Unused options: {0} -- please check if you made a typo "
"in any of them. Those that are truly not useful should "
"be not be set so that this typo detection can be useful.".format(
unused_options
)
)
return res | [
"def",
"render",
"(",
"self",
",",
"steps",
")",
":",
"res",
"=",
"self",
".",
"_render_impl",
"(",
"steps",
")",
"# Implementation-dependent",
"# Now that the output is rendered, we expect all options to have",
"# been used.",
"unused_options",
"=",
"set",
"(",
"self",
".",
"_options_do_not_access",
")",
"unused_options",
"-=",
"self",
".",
"options_used",
"if",
"unused_options",
":",
"raise",
"RuntimeError",
"(",
"\"Unused options: {0} -- please check if you made a typo \"",
"\"in any of them. Those that are truly not useful should \"",
"\"be not be set so that this typo detection can be useful.\"",
".",
"format",
"(",
"unused_options",
")",
")",
"return",
"res"
] | https://github.com/facebook/fboss/blob/60063db1df37c2ec0e7dcd0955c54885ea9bf7f0/build/fbcode_builder/fbcode_builder.py#L120-L140 |
||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py | python | EscapeXcodeDefine | (s) | return re.sub(_xcode_define_re, r'\\\1', s) | We must escape the defines that we give to XCode so that it knows not to
split on spaces and to respect backslash and quote literals. However, we
must not quote the define, or Xcode will incorrectly intepret variables
especially $(inherited). | We must escape the defines that we give to XCode so that it knows not to
split on spaces and to respect backslash and quote literals. However, we
must not quote the define, or Xcode will incorrectly intepret variables
especially $(inherited). | [
"We",
"must",
"escape",
"the",
"defines",
"that",
"we",
"give",
"to",
"XCode",
"so",
"that",
"it",
"knows",
"not",
"to",
"split",
"on",
"spaces",
"and",
"to",
"respect",
"backslash",
"and",
"quote",
"literals",
".",
"However",
"we",
"must",
"not",
"quote",
"the",
"define",
"or",
"Xcode",
"will",
"incorrectly",
"intepret",
"variables",
"especially",
"$",
"(",
"inherited",
")",
"."
] | def EscapeXcodeDefine(s):
"""We must escape the defines that we give to XCode so that it knows not to
split on spaces and to respect backslash and quote literals. However, we
must not quote the define, or Xcode will incorrectly intepret variables
especially $(inherited)."""
return re.sub(_xcode_define_re, r'\\\1', s) | [
"def",
"EscapeXcodeDefine",
"(",
"s",
")",
":",
"return",
"re",
".",
"sub",
"(",
"_xcode_define_re",
",",
"r'\\\\\\1'",
",",
"s",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py#L558-L563 |
|
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/tools/scan-build-py/libscanbuild/report.py | python | chop | (prefix, filename) | return filename if not len(prefix) else os.path.relpath(filename, prefix) | Create 'filename' from '/prefix/filename' | Create 'filename' from '/prefix/filename' | [
"Create",
"filename",
"from",
"/",
"prefix",
"/",
"filename"
] | def chop(prefix, filename):
""" Create 'filename' from '/prefix/filename' """
return filename if not len(prefix) else os.path.relpath(filename, prefix) | [
"def",
"chop",
"(",
"prefix",
",",
"filename",
")",
":",
"return",
"filename",
"if",
"not",
"len",
"(",
"prefix",
")",
"else",
"os",
".",
"path",
".",
"relpath",
"(",
"filename",
",",
"prefix",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/tools/scan-build-py/libscanbuild/report.py#L439-L442 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ftplib.py | python | FTP.sendeprt | (self, host, port) | return self.voidcmd(cmd) | Send an EPRT command with the current host and the given port number. | Send an EPRT command with the current host and the given port number. | [
"Send",
"an",
"EPRT",
"command",
"with",
"the",
"current",
"host",
"and",
"the",
"given",
"port",
"number",
"."
] | def sendeprt(self, host, port):
'''Send an EPRT command with the current host and the given port number.'''
af = 0
if self.af == socket.AF_INET:
af = 1
if self.af == socket.AF_INET6:
af = 2
if af == 0:
raise error_proto('unsupported address family')
fields = ['', repr(af), host, repr(port), '']
cmd = 'EPRT ' + '|'.join(fields)
return self.voidcmd(cmd) | [
"def",
"sendeprt",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"af",
"=",
"0",
"if",
"self",
".",
"af",
"==",
"socket",
".",
"AF_INET",
":",
"af",
"=",
"1",
"if",
"self",
".",
"af",
"==",
"socket",
".",
"AF_INET6",
":",
"af",
"=",
"2",
"if",
"af",
"==",
"0",
":",
"raise",
"error_proto",
"(",
"'unsupported address family'",
")",
"fields",
"=",
"[",
"''",
",",
"repr",
"(",
"af",
")",
",",
"host",
",",
"repr",
"(",
"port",
")",
",",
"''",
"]",
"cmd",
"=",
"'EPRT '",
"+",
"'|'",
".",
"join",
"(",
"fields",
")",
"return",
"self",
".",
"voidcmd",
"(",
"cmd",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ftplib.py#L298-L309 |
|
tiny-dnn/tiny-dnn | c0f576f5cb7b35893f62127cb7aec18f77a3bcc5 | third_party/cpplint.py | python | RemoveMultiLineCommentsFromRange | (lines, begin, end) | Clears a range of lines for multi-line comments. | Clears a range of lines for multi-line comments. | [
"Clears",
"a",
"range",
"of",
"lines",
"for",
"multi",
"-",
"line",
"comments",
"."
] | def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '/**/' | [
"def",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"begin",
",",
"end",
")",
":",
"# Having // dummy comments makes the lines non-empty, so we will not get",
"# unnecessary blank line warnings later in the code.",
"for",
"i",
"in",
"range",
"(",
"begin",
",",
"end",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"'/**/'"
] | https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L1554-L1559 |
||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/_pswindows.py | python | per_cpu_times | () | return ret | Return system per-CPU times as a list of named tuples. | Return system per-CPU times as a list of named tuples. | [
"Return",
"system",
"per",
"-",
"CPU",
"times",
"as",
"a",
"list",
"of",
"named",
"tuples",
"."
] | def per_cpu_times():
"""Return system per-CPU times as a list of named tuples."""
ret = []
for cpu_t in cext.per_cpu_times():
user, system, idle = cpu_t
item = scputimes(user, system, idle)
ret.append(item)
return ret | [
"def",
"per_cpu_times",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"cpu_t",
"in",
"cext",
".",
"per_cpu_times",
"(",
")",
":",
"user",
",",
"system",
",",
"idle",
"=",
"cpu_t",
"item",
"=",
"scputimes",
"(",
"user",
",",
"system",
",",
"idle",
")",
"ret",
".",
"append",
"(",
"item",
")",
"return",
"ret"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/_pswindows.py#L135-L142 |
|
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/linalg.py | python | lstsq | (a, b, rcond='warn') | return _mx_nd_np.linalg.lstsq(a, b, rcond) | r"""
Return the least-squares solution to a linear matrix equation.
Solves the equation :math:`a x = b` by computing a vector `x` that
minimizes the squared Euclidean 2-norm :math:`\| b - a x \|^2_2`.
The equation may be under-, well-, or over-determined (i.e., the
number of linearly independent rows of `a` can be less than, equal
to, or greater than its number of linearly independent columns).
If `a` is square and of full rank, then `x` (but for round-off error)
is the "exact" solution of the equation.
Parameters
----------
a : (M, N) ndarray
"Coefficient" matrix.
b : {(M,), (M, K)} ndarray
Ordinate or "dependent variable" values. If `b` is two-dimensional,
the least-squares solution is calculated for each of the `K` columns
of `b`.
rcond : float, optional
Cut-off ratio for small singular values of `a`.
For the purposes of rank determination, singular values are treated
as zero if they are smaller than `rcond` times the largest singular
value of `a`
The default of ``warn`` or ``-1`` will use the machine precision as
`rcond` parameter. The default of ``None`` will use the machine
precision times `max(M, N)`.
Returns
-------
x : {(N,), (N, K)} ndarray
Least-squares solution. If `b` is two-dimensional,
the solutions are in the `K` columns of `x`.
residuals : {(1,), (K,), (0,)} ndarray
Sums of residuals.
Squared Euclidean 2-norm for each column in ``b - a*x``.
If the rank of `a` is < N or M <= N, this is an empty array.
If `b` is 1-dimensional, this is a (1,) shape array.
Otherwise the shape is (K,).
rank : int
Rank of matrix `a`.
s : (min(M, N),) ndarray
Singular values of `a`.
Raises
------
MXNetError
If computation does not converge.
Notes
-----
If `b` is a matrix, then all array results are returned as matrices.
Examples
--------
>>> x = np.array([0, 1, 2, 3])
>>> y = np.array([-1, 0.2, 0.9, 2.1])
>>> A = np.vstack([x, np.ones(len(x))]).T
>>> A
array([[ 0., 1.],
[ 1., 1.],
[ 2., 1.],
[ 3., 1.]])
>>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
>>> m, c
(1.0 -0.95) # may vary | r"""
Return the least-squares solution to a linear matrix equation. | [
"r",
"Return",
"the",
"least",
"-",
"squares",
"solution",
"to",
"a",
"linear",
"matrix",
"equation",
"."
] | def lstsq(a, b, rcond='warn'):
r"""
Return the least-squares solution to a linear matrix equation.
Solves the equation :math:`a x = b` by computing a vector `x` that
minimizes the squared Euclidean 2-norm :math:`\| b - a x \|^2_2`.
The equation may be under-, well-, or over-determined (i.e., the
number of linearly independent rows of `a` can be less than, equal
to, or greater than its number of linearly independent columns).
If `a` is square and of full rank, then `x` (but for round-off error)
is the "exact" solution of the equation.
Parameters
----------
a : (M, N) ndarray
"Coefficient" matrix.
b : {(M,), (M, K)} ndarray
Ordinate or "dependent variable" values. If `b` is two-dimensional,
the least-squares solution is calculated for each of the `K` columns
of `b`.
rcond : float, optional
Cut-off ratio for small singular values of `a`.
For the purposes of rank determination, singular values are treated
as zero if they are smaller than `rcond` times the largest singular
value of `a`
The default of ``warn`` or ``-1`` will use the machine precision as
`rcond` parameter. The default of ``None`` will use the machine
precision times `max(M, N)`.
Returns
-------
x : {(N,), (N, K)} ndarray
Least-squares solution. If `b` is two-dimensional,
the solutions are in the `K` columns of `x`.
residuals : {(1,), (K,), (0,)} ndarray
Sums of residuals.
Squared Euclidean 2-norm for each column in ``b - a*x``.
If the rank of `a` is < N or M <= N, this is an empty array.
If `b` is 1-dimensional, this is a (1,) shape array.
Otherwise the shape is (K,).
rank : int
Rank of matrix `a`.
s : (min(M, N),) ndarray
Singular values of `a`.
Raises
------
MXNetError
If computation does not converge.
Notes
-----
If `b` is a matrix, then all array results are returned as matrices.
Examples
--------
>>> x = np.array([0, 1, 2, 3])
>>> y = np.array([-1, 0.2, 0.9, 2.1])
>>> A = np.vstack([x, np.ones(len(x))]).T
>>> A
array([[ 0., 1.],
[ 1., 1.],
[ 2., 1.],
[ 3., 1.]])
>>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
>>> m, c
(1.0 -0.95) # may vary
"""
return _mx_nd_np.linalg.lstsq(a, b, rcond) | [
"def",
"lstsq",
"(",
"a",
",",
"b",
",",
"rcond",
"=",
"'warn'",
")",
":",
"return",
"_mx_nd_np",
".",
"linalg",
".",
"lstsq",
"(",
"a",
",",
"b",
",",
"rcond",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/linalg.py#L438-L506 |
|
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/image/image.py | python | CastAug.__call__ | (self, src) | return src | Augmenter body | Augmenter body | [
"Augmenter",
"body"
] | def __call__(self, src):
"""Augmenter body"""
src = src.astype(self.typ)
return src | [
"def",
"__call__",
"(",
"self",
",",
"src",
")",
":",
"src",
"=",
"src",
".",
"astype",
"(",
"self",
".",
"typ",
")",
"return",
"src"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/image/image.py#L1165-L1168 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/attrs/attr/_make.py | python | _CountingAttr.default | (self, meth) | return meth | Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0 | Decorator that allows to set the default for an attribute. | [
"Decorator",
"that",
"allows",
"to",
"set",
"the",
"default",
"for",
"an",
"attribute",
"."
] | def default(self, meth):
"""
Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0
"""
if self._default is not NOTHING:
raise DefaultAlreadySetError()
self._default = Factory(meth, takes_self=True)
return meth | [
"def",
"default",
"(",
"self",
",",
"meth",
")",
":",
"if",
"self",
".",
"_default",
"is",
"not",
"NOTHING",
":",
"raise",
"DefaultAlreadySetError",
"(",
")",
"self",
".",
"_default",
"=",
"Factory",
"(",
"meth",
",",
"takes_self",
"=",
"True",
")",
"return",
"meth"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/attrs/attr/_make.py#L2810-L2825 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/gzip.py | python | GzipFile.fileno | (self) | return self.fileobj.fileno() | Invoke the underlying file object's fileno() method.
This will raise AttributeError if the underlying file object
doesn't support fileno(). | Invoke the underlying file object's fileno() method. | [
"Invoke",
"the",
"underlying",
"file",
"object",
"s",
"fileno",
"()",
"method",
"."
] | def fileno(self):
"""Invoke the underlying file object's fileno() method.
This will raise AttributeError if the underlying file object
doesn't support fileno().
"""
return self.fileobj.fileno() | [
"def",
"fileno",
"(",
"self",
")",
":",
"return",
"self",
".",
"fileobj",
".",
"fileno",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/gzip.py#L394-L400 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/xrc.py | python | XmlNodeEasy | (*args, **kwargs) | return val | XmlNodeEasy(int type, String name, String content=EmptyString) -> XmlNode | XmlNodeEasy(int type, String name, String content=EmptyString) -> XmlNode | [
"XmlNodeEasy",
"(",
"int",
"type",
"String",
"name",
"String",
"content",
"=",
"EmptyString",
")",
"-",
">",
"XmlNode"
] | def XmlNodeEasy(*args, **kwargs):
"""XmlNodeEasy(int type, String name, String content=EmptyString) -> XmlNode"""
val = _xrc.new_XmlNodeEasy(*args, **kwargs)
return val | [
"def",
"XmlNodeEasy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_xrc",
".",
"new_XmlNodeEasy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/xrc.py#L498-L501 |
|
lightvector/KataGo | 20d34784703c5b4000643d3ccc43bb37d418f3b5 | python/sgfmill/sgf.py | python | Node.get_setup_stones | (self) | return bp, wp, ep | Retrieve Add Black / Add White / Add Empty properties from a node.
Returns a tuple (black_points, white_points, empty_points)
Each value is a set of pairs (row, col). | Retrieve Add Black / Add White / Add Empty properties from a node. | [
"Retrieve",
"Add",
"Black",
"/",
"Add",
"White",
"/",
"Add",
"Empty",
"properties",
"from",
"a",
"node",
"."
] | def get_setup_stones(self):
"""Retrieve Add Black / Add White / Add Empty properties from a node.
Returns a tuple (black_points, white_points, empty_points)
Each value is a set of pairs (row, col).
"""
try:
bp = self.get("AB")
except KeyError:
bp = set()
try:
wp = self.get("AW")
except KeyError:
wp = set()
try:
ep = self.get("AE")
except KeyError:
ep = set()
return bp, wp, ep | [
"def",
"get_setup_stones",
"(",
"self",
")",
":",
"try",
":",
"bp",
"=",
"self",
".",
"get",
"(",
"\"AB\"",
")",
"except",
"KeyError",
":",
"bp",
"=",
"set",
"(",
")",
"try",
":",
"wp",
"=",
"self",
".",
"get",
"(",
"\"AW\"",
")",
"except",
"KeyError",
":",
"wp",
"=",
"set",
"(",
")",
"try",
":",
"ep",
"=",
"self",
".",
"get",
"(",
"\"AE\"",
")",
"except",
"KeyError",
":",
"ep",
"=",
"set",
"(",
")",
"return",
"bp",
",",
"wp",
",",
"ep"
] | https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/sgfmill/sgf.py#L236-L256 |
|
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TNEANet.IntAttrValueEI | (self, *args) | return _snap.TNEANet_IntAttrValueEI(self, *args) | IntAttrValueEI(TNEANet self, TInt EId, TIntV Values)
Parameters:
EId: TInt const &
Values: TIntV &
IntAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TIntV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TIntV & | IntAttrValueEI(TNEANet self, TInt EId, TIntV Values) | [
"IntAttrValueEI",
"(",
"TNEANet",
"self",
"TInt",
"EId",
"TIntV",
"Values",
")"
] | def IntAttrValueEI(self, *args):
"""
IntAttrValueEI(TNEANet self, TInt EId, TIntV Values)
Parameters:
EId: TInt const &
Values: TIntV &
IntAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TIntV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.TNEANet_IntAttrValueEI(self, *args) | [
"def",
"IntAttrValueEI",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TNEANet_IntAttrValueEI",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L21635-L21651 |
|
RGF-team/rgf | 272afb85b4c91571f576e5fc83ecfacce3672eb4 | python-package/rgf/utils.py | python | RGFClassifierMixin.predict | (self, X) | return np.asarray(list(self._classes_map.values()))[np.searchsorted(list(self._classes_map.keys()), y)] | Predict class for X.
The predicted class of an input sample is computed.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted classes. | Predict class for X. | [
"Predict",
"class",
"for",
"X",
"."
] | def predict(self, X):
"""
Predict class for X.
The predicted class of an input sample is computed.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted classes.
"""
y = self.predict_proba(X)
y = np.argmax(y, axis=1)
return np.asarray(list(self._classes_map.values()))[np.searchsorted(list(self._classes_map.keys()), y)] | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"y",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"y",
"=",
"np",
".",
"argmax",
"(",
"y",
",",
"axis",
"=",
"1",
")",
"return",
"np",
".",
"asarray",
"(",
"list",
"(",
"self",
".",
"_classes_map",
".",
"values",
"(",
")",
")",
")",
"[",
"np",
".",
"searchsorted",
"(",
"list",
"(",
"self",
".",
"_classes_map",
".",
"keys",
"(",
")",
")",
",",
"y",
")",
"]"
] | https://github.com/RGF-team/rgf/blob/272afb85b4c91571f576e5fc83ecfacce3672eb4/python-package/rgf/utils.py#L569-L587 |
|
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2B_DIGEST_SYMCIPHER.fromTpm | (buf) | return buf.createObj(TPM2B_DIGEST_SYMCIPHER) | Returns new TPM2B_DIGEST_SYMCIPHER object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPM2B_DIGEST_SYMCIPHER object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPM2B_DIGEST_SYMCIPHER",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPM2B_DIGEST_SYMCIPHER object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPM2B_DIGEST_SYMCIPHER) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPM2B_DIGEST_SYMCIPHER",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L18248-L18252 |
|
devosoft/avida | c6179ffc617fdbc962b5a9c4de3e889e0ef2d94c | avida-core/support/utils/AvidaUtils/BoostPythonTool.py | python | generate | (env) | Adds builders and construction variables for Boost.Python to an
Environment. | Adds builders and construction variables for Boost.Python to an
Environment. | [
"Adds",
"builders",
"and",
"construction",
"variables",
"for",
"Boost",
".",
"Python",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""
Adds builders and construction variables for Boost.Python to an
Environment.
"""
env.SetDefault(
BOOST_PYTHON_TOOL_ERR = '',
BOOST_PYTHON_CPPFLAGS = ['$PYTHON_BASECFLAGS'],
BOOST_PYTHON_CPPDEFINES = [],
BOOST_PYTHON_CPPPATH = ['$boostIncludeDir', '$PYTHON_INCLUDEPY'],
BOOST_PYTHON_CXX_SUFFIX = '.boost.python.cpp',
BOOST_PYTHON_LIBPATH = ['$boostPythonLibDir'],
BOOST_PYTHON_LIBS = ['$boostPythonLib'],
BOOST_PYTHON_SHLINK = '$PYTHON_LDSHARED',
BOOST_PYTHON_LDMODULE = '$BOOST_PYTHON_SHLINK',
BOOST_PYTHON_LDMODULEFLAGS = '',
_BOOST_PYTHON_CPPINCFLAGS = '$( ${_concat(INCPREFIX, BOOST_PYTHON_CPPPATH, INCSUFFIX, __env__, RDirs, TARGET)} $)',
_BOOST_PYTHON_CPPDEFFLAGS = '${_defines(CPPDEFPREFIX, BOOST_PYTHON_CPPDEFINES, CPPDEFSUFFIX, __env__)}',
_BOOST_PYTHON_LIBFLAGS = '${_stripixes(LIBLINKPREFIX, BOOST_PYTHON_LIBS, LIBLINKSUFFIX, LIBPREFIX, LIBSUFFIX, __env__)}',
_BOOST_PYTHON_LIBDIRFLAGS = '$( ${_concat(LIBDIRPREFIX, BOOST_PYTHON_LIBPATH, LIBDIRSUFFIX, __env__, RDirs, TARGET)} $)',
BOOST_PYTHON_SHCXXCOM = '$SHCXX $SHCXXFLAGS $CPPFLAGS $BOOST_PYTHON_CPPFLAGS $_CPPDEFFLAGS $_BOOST_PYTHON_CPPDEFFLAGS $_CPPINCFLAGS $_BOOST_PYTHON_CPPINCFLAGS -c -o $TARGET $SOURCES',
BOOST_PYTHON_LDMODULECOM = '$BOOST_PYTHON_LDMODULE $BOOST_PYTHON_LDMODULEFLAGS -o ${TARGET} $SOURCES $_LIBDIRFLAGS $_BOOST_PYTHON_LIBDIRFLAGS $_LIBFLAGS $_BOOST_PYTHON_LIBFLAGS',
)
boost_python_ld_module_link_action = SCons.Action.Action("$BOOST_PYTHON_LDMODULECOM", "$BOOST_PYTHON_LDMODULECOMSTR")
boost_python_shared_object_builder = SCons.Builder.Builder(
action = [ ShCXXAction ],
prefix = '$SHOBJPREFIX',
suffix = '$SHOBJSUFFIX',
src_suffix = '$BOOST_PYTHON_CXX_SUFFIX',
source_scanner = SCons.Tool.SourceFileScanner,
single_source = True
)
boost_python_module_builder = SCons.Builder.Builder(
action = [ LdModuleLinkAction ],
prefix = '',
suffix = '$PYTHON_SO',
target_scanner = SCons.Tool.ProgramScanner,
src_suffix = '$SHOBJSUFFIX',
src_builder = 'BoostPythonSharedObject',
single_source = True
)
env.AppendUnique(BUILDERS = {'BoostPythonSharedObject' : boost_python_shared_object_builder})
env.AppendUnique(BUILDERS = {'BoostPythonModule' : boost_python_module_builder})
if env.subst('$runConfTests') in ['yes', '1']:
find(env) | [
"def",
"generate",
"(",
"env",
")",
":",
"env",
".",
"SetDefault",
"(",
"BOOST_PYTHON_TOOL_ERR",
"=",
"''",
",",
"BOOST_PYTHON_CPPFLAGS",
"=",
"[",
"'$PYTHON_BASECFLAGS'",
"]",
",",
"BOOST_PYTHON_CPPDEFINES",
"=",
"[",
"]",
",",
"BOOST_PYTHON_CPPPATH",
"=",
"[",
"'$boostIncludeDir'",
",",
"'$PYTHON_INCLUDEPY'",
"]",
",",
"BOOST_PYTHON_CXX_SUFFIX",
"=",
"'.boost.python.cpp'",
",",
"BOOST_PYTHON_LIBPATH",
"=",
"[",
"'$boostPythonLibDir'",
"]",
",",
"BOOST_PYTHON_LIBS",
"=",
"[",
"'$boostPythonLib'",
"]",
",",
"BOOST_PYTHON_SHLINK",
"=",
"'$PYTHON_LDSHARED'",
",",
"BOOST_PYTHON_LDMODULE",
"=",
"'$BOOST_PYTHON_SHLINK'",
",",
"BOOST_PYTHON_LDMODULEFLAGS",
"=",
"''",
",",
"_BOOST_PYTHON_CPPINCFLAGS",
"=",
"'$( ${_concat(INCPREFIX, BOOST_PYTHON_CPPPATH, INCSUFFIX, __env__, RDirs, TARGET)} $)'",
",",
"_BOOST_PYTHON_CPPDEFFLAGS",
"=",
"'${_defines(CPPDEFPREFIX, BOOST_PYTHON_CPPDEFINES, CPPDEFSUFFIX, __env__)}'",
",",
"_BOOST_PYTHON_LIBFLAGS",
"=",
"'${_stripixes(LIBLINKPREFIX, BOOST_PYTHON_LIBS, LIBLINKSUFFIX, LIBPREFIX, LIBSUFFIX, __env__)}'",
",",
"_BOOST_PYTHON_LIBDIRFLAGS",
"=",
"'$( ${_concat(LIBDIRPREFIX, BOOST_PYTHON_LIBPATH, LIBDIRSUFFIX, __env__, RDirs, TARGET)} $)'",
",",
"BOOST_PYTHON_SHCXXCOM",
"=",
"'$SHCXX $SHCXXFLAGS $CPPFLAGS $BOOST_PYTHON_CPPFLAGS $_CPPDEFFLAGS $_BOOST_PYTHON_CPPDEFFLAGS $_CPPINCFLAGS $_BOOST_PYTHON_CPPINCFLAGS -c -o $TARGET $SOURCES'",
",",
"BOOST_PYTHON_LDMODULECOM",
"=",
"'$BOOST_PYTHON_LDMODULE $BOOST_PYTHON_LDMODULEFLAGS -o ${TARGET} $SOURCES $_LIBDIRFLAGS $_BOOST_PYTHON_LIBDIRFLAGS $_LIBFLAGS $_BOOST_PYTHON_LIBFLAGS'",
",",
")",
"boost_python_ld_module_link_action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"\"$BOOST_PYTHON_LDMODULECOM\"",
",",
"\"$BOOST_PYTHON_LDMODULECOMSTR\"",
")",
"boost_python_shared_object_builder",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(",
"action",
"=",
"[",
"ShCXXAction",
"]",
",",
"prefix",
"=",
"'$SHOBJPREFIX'",
",",
"suffix",
"=",
"'$SHOBJSUFFIX'",
",",
"src_suffix",
"=",
"'$BOOST_PYTHON_CXX_SUFFIX'",
",",
"source_scanner",
"=",
"SCons",
".",
"Tool",
".",
"SourceFileScanner",
",",
"single_source",
"=",
"True",
")",
"boost_python_module_builder",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(",
"action",
"=",
"[",
"LdModuleLinkAction",
"]",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"'$PYTHON_SO'",
",",
"target_scanner",
"=",
"SCons",
".",
"Tool",
".",
"ProgramScanner",
",",
"src_suffix",
"=",
"'$SHOBJSUFFIX'",
",",
"src_builder",
"=",
"'BoostPythonSharedObject'",
",",
"single_source",
"=",
"True",
")",
"env",
".",
"AppendUnique",
"(",
"BUILDERS",
"=",
"{",
"'BoostPythonSharedObject'",
":",
"boost_python_shared_object_builder",
"}",
")",
"env",
".",
"AppendUnique",
"(",
"BUILDERS",
"=",
"{",
"'BoostPythonModule'",
":",
"boost_python_module_builder",
"}",
")",
"if",
"env",
".",
"subst",
"(",
"'$runConfTests'",
")",
"in",
"[",
"'yes'",
",",
"'1'",
"]",
":",
"find",
"(",
"env",
")"
] | https://github.com/devosoft/avida/blob/c6179ffc617fdbc962b5a9c4de3e889e0ef2d94c/avida-core/support/utils/AvidaUtils/BoostPythonTool.py#L83-L129 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/cluster/vq.py | python | _missing_warn | () | Print a warning when called. | Print a warning when called. | [
"Print",
"a",
"warning",
"when",
"called",
"."
] | def _missing_warn():
"""Print a warning when called."""
warnings.warn("One of the clusters is empty. "
"Re-run kmeans with a different initialization.") | [
"def",
"_missing_warn",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"\"One of the clusters is empty. \"",
"\"Re-run kmeans with a different initialization.\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/cluster/vq.py#L578-L581 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/runpy.py | python | _run_code | (code, run_globals, init_globals=None,
mod_name=None, mod_spec=None,
pkg_name=None, script_name=None) | return run_globals | Helper to run code in nominated namespace | Helper to run code in nominated namespace | [
"Helper",
"to",
"run",
"code",
"in",
"nominated",
"namespace"
] | def _run_code(code, run_globals, init_globals=None,
mod_name=None, mod_spec=None,
pkg_name=None, script_name=None):
"""Helper to run code in nominated namespace"""
if init_globals is not None:
run_globals.update(init_globals)
if mod_spec is None:
loader = None
fname = script_name
cached = None
else:
loader = mod_spec.loader
fname = mod_spec.origin
cached = mod_spec.cached
if pkg_name is None:
pkg_name = mod_spec.parent
run_globals.update(__name__ = mod_name,
__file__ = fname,
__cached__ = cached,
__doc__ = None,
__loader__ = loader,
__package__ = pkg_name,
__spec__ = mod_spec)
exec(code, run_globals)
return run_globals | [
"def",
"_run_code",
"(",
"code",
",",
"run_globals",
",",
"init_globals",
"=",
"None",
",",
"mod_name",
"=",
"None",
",",
"mod_spec",
"=",
"None",
",",
"pkg_name",
"=",
"None",
",",
"script_name",
"=",
"None",
")",
":",
"if",
"init_globals",
"is",
"not",
"None",
":",
"run_globals",
".",
"update",
"(",
"init_globals",
")",
"if",
"mod_spec",
"is",
"None",
":",
"loader",
"=",
"None",
"fname",
"=",
"script_name",
"cached",
"=",
"None",
"else",
":",
"loader",
"=",
"mod_spec",
".",
"loader",
"fname",
"=",
"mod_spec",
".",
"origin",
"cached",
"=",
"mod_spec",
".",
"cached",
"if",
"pkg_name",
"is",
"None",
":",
"pkg_name",
"=",
"mod_spec",
".",
"parent",
"run_globals",
".",
"update",
"(",
"__name__",
"=",
"mod_name",
",",
"__file__",
"=",
"fname",
",",
"__cached__",
"=",
"cached",
",",
"__doc__",
"=",
"None",
",",
"__loader__",
"=",
"loader",
",",
"__package__",
"=",
"pkg_name",
",",
"__spec__",
"=",
"mod_spec",
")",
"exec",
"(",
"code",
",",
"run_globals",
")",
"return",
"run_globals"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/runpy.py#L64-L88 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/combo.py | python | ComboPopup._setCallbackInfo | (*args, **kwargs) | return _combo.ComboPopup__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 _combo.ComboPopup__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"ComboPopup__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/combo.py#L607-L609 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py | python | Series.sort_values | (
self,
axis=0,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
ignore_index=False,
) | Sort by the values.
Sort a Series in ascending or descending order by some
criterion.
Parameters
----------
axis : {0 or 'index'}, default 0
Axis to direct sorting. The value 'index' is accepted for
compatibility with DataFrame.sort_values.
ascending : bool, default True
If True, sort values in ascending order, otherwise descending.
inplace : bool, default False
If True, perform operation in-place.
kind : {'quicksort', 'mergesort' or 'heapsort'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
information. 'mergesort' is the only stable algorithm.
na_position : {'first' or 'last'}, default 'last'
Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
the end.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
Returns
-------
Series
Series ordered by values.
See Also
--------
Series.sort_index : Sort by the Series indices.
DataFrame.sort_values : Sort DataFrame by the values along either axis.
DataFrame.sort_index : Sort DataFrame by indices.
Examples
--------
>>> s = pd.Series([np.nan, 1, 3, 10, 5])
>>> s
0 NaN
1 1.0
2 3.0
3 10.0
4 5.0
dtype: float64
Sort values ascending order (default behaviour)
>>> s.sort_values(ascending=True)
1 1.0
2 3.0
4 5.0
3 10.0
0 NaN
dtype: float64
Sort values descending order
>>> s.sort_values(ascending=False)
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values inplace
>>> s.sort_values(ascending=False, inplace=True)
>>> s
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values putting NAs first
>>> s.sort_values(na_position='first')
0 NaN
1 1.0
2 3.0
4 5.0
3 10.0
dtype: float64
Sort a series of strings
>>> s = pd.Series(['z', 'b', 'd', 'a', 'c'])
>>> s
0 z
1 b
2 d
3 a
4 c
dtype: object
>>> s.sort_values()
3 a
1 b
4 c
2 d
0 z
dtype: object | Sort by the values. | [
"Sort",
"by",
"the",
"values",
"."
] | def sort_values(
self,
axis=0,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
ignore_index=False,
):
"""
Sort by the values.
Sort a Series in ascending or descending order by some
criterion.
Parameters
----------
axis : {0 or 'index'}, default 0
Axis to direct sorting. The value 'index' is accepted for
compatibility with DataFrame.sort_values.
ascending : bool, default True
If True, sort values in ascending order, otherwise descending.
inplace : bool, default False
If True, perform operation in-place.
kind : {'quicksort', 'mergesort' or 'heapsort'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
information. 'mergesort' is the only stable algorithm.
na_position : {'first' or 'last'}, default 'last'
Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
the end.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
Returns
-------
Series
Series ordered by values.
See Also
--------
Series.sort_index : Sort by the Series indices.
DataFrame.sort_values : Sort DataFrame by the values along either axis.
DataFrame.sort_index : Sort DataFrame by indices.
Examples
--------
>>> s = pd.Series([np.nan, 1, 3, 10, 5])
>>> s
0 NaN
1 1.0
2 3.0
3 10.0
4 5.0
dtype: float64
Sort values ascending order (default behaviour)
>>> s.sort_values(ascending=True)
1 1.0
2 3.0
4 5.0
3 10.0
0 NaN
dtype: float64
Sort values descending order
>>> s.sort_values(ascending=False)
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values inplace
>>> s.sort_values(ascending=False, inplace=True)
>>> s
3 10.0
4 5.0
2 3.0
1 1.0
0 NaN
dtype: float64
Sort values putting NAs first
>>> s.sort_values(na_position='first')
0 NaN
1 1.0
2 3.0
4 5.0
3 10.0
dtype: float64
Sort a series of strings
>>> s = pd.Series(['z', 'b', 'd', 'a', 'c'])
>>> s
0 z
1 b
2 d
3 a
4 c
dtype: object
>>> s.sort_values()
3 a
1 b
4 c
2 d
0 z
dtype: object
"""
inplace = validate_bool_kwarg(inplace, "inplace")
# Validate the axis parameter
self._get_axis_number(axis)
# GH 5856/5853
if inplace and self._is_cached:
raise ValueError(
"This Series is a view of some other array, to "
"sort in-place you must create a copy"
)
def _try_kind_sort(arr):
# easier to ask forgiveness than permission
try:
# if kind==mergesort, it can fail for object dtype
return arr.argsort(kind=kind)
except TypeError:
# stable sort not available for object dtype
# uses the argsort default quicksort
return arr.argsort(kind="quicksort")
arr = self._values
sorted_index = np.empty(len(self), dtype=np.int32)
bad = isna(arr)
good = ~bad
idx = ibase.default_index(len(self))
argsorted = _try_kind_sort(arr[good])
if is_list_like(ascending):
if len(ascending) != 1:
raise ValueError(
f"Length of ascending ({len(ascending)}) must be 1 for Series"
)
ascending = ascending[0]
if not is_bool(ascending):
raise ValueError("ascending must be boolean")
if not ascending:
argsorted = argsorted[::-1]
if na_position == "last":
n = good.sum()
sorted_index[:n] = idx[good][argsorted]
sorted_index[n:] = idx[bad]
elif na_position == "first":
n = bad.sum()
sorted_index[n:] = idx[good][argsorted]
sorted_index[:n] = idx[bad]
else:
raise ValueError(f"invalid na_position: {na_position}")
result = self._constructor(arr[sorted_index], index=self.index[sorted_index])
if ignore_index:
result.index = ibase.default_index(len(sorted_index))
if inplace:
self._update_inplace(result)
else:
return result.__finalize__(self) | [
"def",
"sort_values",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"ascending",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"kind",
"=",
"\"quicksort\"",
",",
"na_position",
"=",
"\"last\"",
",",
"ignore_index",
"=",
"False",
",",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"\"inplace\"",
")",
"# Validate the axis parameter",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"# GH 5856/5853",
"if",
"inplace",
"and",
"self",
".",
"_is_cached",
":",
"raise",
"ValueError",
"(",
"\"This Series is a view of some other array, to \"",
"\"sort in-place you must create a copy\"",
")",
"def",
"_try_kind_sort",
"(",
"arr",
")",
":",
"# easier to ask forgiveness than permission",
"try",
":",
"# if kind==mergesort, it can fail for object dtype",
"return",
"arr",
".",
"argsort",
"(",
"kind",
"=",
"kind",
")",
"except",
"TypeError",
":",
"# stable sort not available for object dtype",
"# uses the argsort default quicksort",
"return",
"arr",
".",
"argsort",
"(",
"kind",
"=",
"\"quicksort\"",
")",
"arr",
"=",
"self",
".",
"_values",
"sorted_index",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"bad",
"=",
"isna",
"(",
"arr",
")",
"good",
"=",
"~",
"bad",
"idx",
"=",
"ibase",
".",
"default_index",
"(",
"len",
"(",
"self",
")",
")",
"argsorted",
"=",
"_try_kind_sort",
"(",
"arr",
"[",
"good",
"]",
")",
"if",
"is_list_like",
"(",
"ascending",
")",
":",
"if",
"len",
"(",
"ascending",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"f\"Length of ascending ({len(ascending)}) must be 1 for Series\"",
")",
"ascending",
"=",
"ascending",
"[",
"0",
"]",
"if",
"not",
"is_bool",
"(",
"ascending",
")",
":",
"raise",
"ValueError",
"(",
"\"ascending must be boolean\"",
")",
"if",
"not",
"ascending",
":",
"argsorted",
"=",
"argsorted",
"[",
":",
":",
"-",
"1",
"]",
"if",
"na_position",
"==",
"\"last\"",
":",
"n",
"=",
"good",
".",
"sum",
"(",
")",
"sorted_index",
"[",
":",
"n",
"]",
"=",
"idx",
"[",
"good",
"]",
"[",
"argsorted",
"]",
"sorted_index",
"[",
"n",
":",
"]",
"=",
"idx",
"[",
"bad",
"]",
"elif",
"na_position",
"==",
"\"first\"",
":",
"n",
"=",
"bad",
".",
"sum",
"(",
")",
"sorted_index",
"[",
"n",
":",
"]",
"=",
"idx",
"[",
"good",
"]",
"[",
"argsorted",
"]",
"sorted_index",
"[",
":",
"n",
"]",
"=",
"idx",
"[",
"bad",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"f\"invalid na_position: {na_position}\"",
")",
"result",
"=",
"self",
".",
"_constructor",
"(",
"arr",
"[",
"sorted_index",
"]",
",",
"index",
"=",
"self",
".",
"index",
"[",
"sorted_index",
"]",
")",
"if",
"ignore_index",
":",
"result",
".",
"index",
"=",
"ibase",
".",
"default_index",
"(",
"len",
"(",
"sorted_index",
")",
")",
"if",
"inplace",
":",
"self",
".",
"_update_inplace",
"(",
"result",
")",
"else",
":",
"return",
"result",
".",
"__finalize__",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py#L2816-L2996 |
||
facebook/wangle | 2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3 | build/fbcode_builder/fbcode_builder.py | python | FBCodeBuilder.fb_github_project_workdir | (self, project_and_path, github_org="facebook") | return self.github_project_workdir(github_org + "/" + project, path) | This helper lets Facebook-internal CI special-cases FB projects | This helper lets Facebook-internal CI special-cases FB projects | [
"This",
"helper",
"lets",
"Facebook",
"-",
"internal",
"CI",
"special",
"-",
"cases",
"FB",
"projects"
] | def fb_github_project_workdir(self, project_and_path, github_org="facebook"):
"This helper lets Facebook-internal CI special-cases FB projects"
project, path = project_and_path.split("/", 1)
return self.github_project_workdir(github_org + "/" + project, path) | [
"def",
"fb_github_project_workdir",
"(",
"self",
",",
"project_and_path",
",",
"github_org",
"=",
"\"facebook\"",
")",
":",
"project",
",",
"path",
"=",
"project_and_path",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"return",
"self",
".",
"github_project_workdir",
"(",
"github_org",
"+",
"\"/\"",
"+",
"project",
",",
"path",
")"
] | https://github.com/facebook/wangle/blob/2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3/build/fbcode_builder/fbcode_builder.py#L393-L396 |
|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/tensor_array_ops.py | python | _GraphTensorArrayV2._check_element_shape | (self, shape) | Changes the element shape of the array given a shape to merge with.
Args:
shape: A `TensorShape` object to merge with.
Raises:
ValueError: if the provided shape is incompatible with the current
element shape of the `TensorArray`. | Changes the element shape of the array given a shape to merge with. | [
"Changes",
"the",
"element",
"shape",
"of",
"the",
"array",
"given",
"a",
"shape",
"to",
"merge",
"with",
"."
] | def _check_element_shape(self, shape):
"""Changes the element shape of the array given a shape to merge with.
Args:
shape: A `TensorShape` object to merge with.
Raises:
ValueError: if the provided shape is incompatible with the current
element shape of the `TensorArray`.
"""
if not shape.is_compatible_with(self.element_shape):
raise ValueError("Inconsistent shapes: saw %s but expected %s " %
(shape, self.element_shape))
if self._infer_shape:
self._element_shape[0] = self.element_shape.merge_with(shape) | [
"def",
"_check_element_shape",
"(",
"self",
",",
"shape",
")",
":",
"if",
"not",
"shape",
".",
"is_compatible_with",
"(",
"self",
".",
"element_shape",
")",
":",
"raise",
"ValueError",
"(",
"\"Inconsistent shapes: saw %s but expected %s \"",
"%",
"(",
"shape",
",",
"self",
".",
"element_shape",
")",
")",
"if",
"self",
".",
"_infer_shape",
":",
"self",
".",
"_element_shape",
"[",
"0",
"]",
"=",
"self",
".",
"element_shape",
".",
"merge_with",
"(",
"shape",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/tensor_array_ops.py#L501-L515 |
||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/losses/python/metric_learning/metric_loss_ops.py | python | npairs_loss_multilabel | (sparse_labels, embeddings_anchor,
embeddings_positive, reg_lambda=0.002,
print_losses=False) | r"""Computes the npairs loss with multilabel data.
Npairs loss expects paired data where a pair is composed of samples from the
same labels and each pairs in the minibatch have different labels. The loss
has two components. The first component is the L2 regularizer on the
embedding vectors. The second component is the sum of cross entropy loss
which takes each row of the pair-wise similarity matrix as logits and
the remapped one-hot labels as labels. Here, the similarity is defined by the
dot product between two embedding vectors. S_{i,j} = f(x_i)^T f(x_j)
To deal with multilabel inputs, we use the count of label intersection
i.e. L_{i,j} = | set_of_labels_for(i) \cap set_of_labels_for(j) |
Then we normalize each rows of the count based label matrix so that each row
sums to one.
Args:
sparse_labels: List of 1-D Boolean `SparseTensor` of dense_shape
[batch_size/2, num_classes] labels for the anchor-pos pairs.
embeddings_anchor: 2-D `Tensor` of shape [batch_size/2, embedding_dim] for
the embedding vectors for the anchor images. Embeddings should not be
l2 normalized.
embeddings_positive: 2-D `Tensor` of shape [batch_size/2, embedding_dim] for
the embedding vectors for the positive images. Embeddings should not be
l2 normalized.
reg_lambda: Float. L2 regularization term on the embedding vectors.
print_losses: Boolean. Option to print the xent and l2loss.
Returns:
npairs_loss: tf.float32 scalar.
Raises:
TypeError: When the specified sparse_labels is not a `SparseTensor`. | r"""Computes the npairs loss with multilabel data. | [
"r",
"Computes",
"the",
"npairs",
"loss",
"with",
"multilabel",
"data",
"."
] | def npairs_loss_multilabel(sparse_labels, embeddings_anchor,
embeddings_positive, reg_lambda=0.002,
print_losses=False):
r"""Computes the npairs loss with multilabel data.
Npairs loss expects paired data where a pair is composed of samples from the
same labels and each pairs in the minibatch have different labels. The loss
has two components. The first component is the L2 regularizer on the
embedding vectors. The second component is the sum of cross entropy loss
which takes each row of the pair-wise similarity matrix as logits and
the remapped one-hot labels as labels. Here, the similarity is defined by the
dot product between two embedding vectors. S_{i,j} = f(x_i)^T f(x_j)
To deal with multilabel inputs, we use the count of label intersection
i.e. L_{i,j} = | set_of_labels_for(i) \cap set_of_labels_for(j) |
Then we normalize each rows of the count based label matrix so that each row
sums to one.
Args:
sparse_labels: List of 1-D Boolean `SparseTensor` of dense_shape
[batch_size/2, num_classes] labels for the anchor-pos pairs.
embeddings_anchor: 2-D `Tensor` of shape [batch_size/2, embedding_dim] for
the embedding vectors for the anchor images. Embeddings should not be
l2 normalized.
embeddings_positive: 2-D `Tensor` of shape [batch_size/2, embedding_dim] for
the embedding vectors for the positive images. Embeddings should not be
l2 normalized.
reg_lambda: Float. L2 regularization term on the embedding vectors.
print_losses: Boolean. Option to print the xent and l2loss.
Returns:
npairs_loss: tf.float32 scalar.
Raises:
TypeError: When the specified sparse_labels is not a `SparseTensor`.
"""
if False in [isinstance(
l, sparse_tensor.SparseTensor) for l in sparse_labels]:
raise TypeError(
'sparse_labels must be a list of SparseTensors, but got %s' % str(
sparse_labels))
with ops.name_scope('NpairsLossMultiLabel'):
# Add the regularizer on the embedding.
reg_anchor = math_ops.reduce_mean(
math_ops.reduce_sum(math_ops.square(embeddings_anchor), 1))
reg_positive = math_ops.reduce_mean(
math_ops.reduce_sum(math_ops.square(embeddings_positive), 1))
l2loss = math_ops.multiply(0.25 * reg_lambda,
reg_anchor + reg_positive, name='l2loss')
# Get per pair similarities.
similarity_matrix = math_ops.matmul(
embeddings_anchor, embeddings_positive, transpose_a=False,
transpose_b=True)
# TODO(coreylynch): need to check the sparse values
# TODO(coreylynch): are composed only of 0's and 1's.
multilabel_adjacency_matrix = _build_multilabel_adjacency(sparse_labels)
labels_remapped = math_ops.cast(multilabel_adjacency_matrix, dtypes.float32)
labels_remapped /= math_ops.reduce_sum(labels_remapped, 1, keepdims=True)
# Add the softmax loss.
xent_loss = nn.softmax_cross_entropy_with_logits(
logits=similarity_matrix, labels=labels_remapped)
xent_loss = math_ops.reduce_mean(xent_loss, name='xentropy')
if print_losses:
xent_loss = logging_ops.Print(
xent_loss, ['cross entropy:', xent_loss, 'l2loss:', l2loss])
return l2loss + xent_loss | [
"def",
"npairs_loss_multilabel",
"(",
"sparse_labels",
",",
"embeddings_anchor",
",",
"embeddings_positive",
",",
"reg_lambda",
"=",
"0.002",
",",
"print_losses",
"=",
"False",
")",
":",
"if",
"False",
"in",
"[",
"isinstance",
"(",
"l",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
"for",
"l",
"in",
"sparse_labels",
"]",
":",
"raise",
"TypeError",
"(",
"'sparse_labels must be a list of SparseTensors, but got %s'",
"%",
"str",
"(",
"sparse_labels",
")",
")",
"with",
"ops",
".",
"name_scope",
"(",
"'NpairsLossMultiLabel'",
")",
":",
"# Add the regularizer on the embedding.",
"reg_anchor",
"=",
"math_ops",
".",
"reduce_mean",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"square",
"(",
"embeddings_anchor",
")",
",",
"1",
")",
")",
"reg_positive",
"=",
"math_ops",
".",
"reduce_mean",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"square",
"(",
"embeddings_positive",
")",
",",
"1",
")",
")",
"l2loss",
"=",
"math_ops",
".",
"multiply",
"(",
"0.25",
"*",
"reg_lambda",
",",
"reg_anchor",
"+",
"reg_positive",
",",
"name",
"=",
"'l2loss'",
")",
"# Get per pair similarities.",
"similarity_matrix",
"=",
"math_ops",
".",
"matmul",
"(",
"embeddings_anchor",
",",
"embeddings_positive",
",",
"transpose_a",
"=",
"False",
",",
"transpose_b",
"=",
"True",
")",
"# TODO(coreylynch): need to check the sparse values",
"# TODO(coreylynch): are composed only of 0's and 1's.",
"multilabel_adjacency_matrix",
"=",
"_build_multilabel_adjacency",
"(",
"sparse_labels",
")",
"labels_remapped",
"=",
"math_ops",
".",
"cast",
"(",
"multilabel_adjacency_matrix",
",",
"dtypes",
".",
"float32",
")",
"labels_remapped",
"/=",
"math_ops",
".",
"reduce_sum",
"(",
"labels_remapped",
",",
"1",
",",
"keepdims",
"=",
"True",
")",
"# Add the softmax loss.",
"xent_loss",
"=",
"nn",
".",
"softmax_cross_entropy_with_logits",
"(",
"logits",
"=",
"similarity_matrix",
",",
"labels",
"=",
"labels_remapped",
")",
"xent_loss",
"=",
"math_ops",
".",
"reduce_mean",
"(",
"xent_loss",
",",
"name",
"=",
"'xentropy'",
")",
"if",
"print_losses",
":",
"xent_loss",
"=",
"logging_ops",
".",
"Print",
"(",
"xent_loss",
",",
"[",
"'cross entropy:'",
",",
"xent_loss",
",",
"'l2loss:'",
",",
"l2loss",
"]",
")",
"return",
"l2loss",
"+",
"xent_loss"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/losses/python/metric_learning/metric_loss_ops.py#L337-L408 |
||
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Modules/Scripted/DICOMLib/DICOMUtils.py | python | getDatabasePatientUIDByPatientName | (name) | return None | Get patient UID by patient name for easy loading of a patient | Get patient UID by patient name for easy loading of a patient | [
"Get",
"patient",
"UID",
"by",
"patient",
"name",
"for",
"easy",
"loading",
"of",
"a",
"patient"
] | def getDatabasePatientUIDByPatientName(name):
""" Get patient UID by patient name for easy loading of a patient
"""
if not slicer.dicomDatabase.isOpen:
raise OSError('DICOM module or database cannot be accessed')
patients = slicer.dicomDatabase.patients()
for patientUID in patients:
currentName = slicer.dicomDatabase.nameForPatient(patientUID)
if currentName == name:
return patientUID
return None | [
"def",
"getDatabasePatientUIDByPatientName",
"(",
"name",
")",
":",
"if",
"not",
"slicer",
".",
"dicomDatabase",
".",
"isOpen",
":",
"raise",
"OSError",
"(",
"'DICOM module or database cannot be accessed'",
")",
"patients",
"=",
"slicer",
".",
"dicomDatabase",
".",
"patients",
"(",
")",
"for",
"patientUID",
"in",
"patients",
":",
"currentName",
"=",
"slicer",
".",
"dicomDatabase",
".",
"nameForPatient",
"(",
"patientUID",
")",
"if",
"currentName",
"==",
"name",
":",
"return",
"patientUID",
"return",
"None"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMLib/DICOMUtils.py#L76-L87 |
|
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/framework/sparse_tensor.py | python | SparseTensor.indices | (self) | return self._indices | The indices of non-zero values in the represented dense tensor.
Returns:
A 2-D Tensor of int64 with dense_shape `[N, ndims]`, where `N` is the
number of non-zero values in the tensor, and `ndims` is the rank. | The indices of non-zero values in the represented dense tensor. | [
"The",
"indices",
"of",
"non",
"-",
"zero",
"values",
"in",
"the",
"represented",
"dense",
"tensor",
"."
] | def indices(self):
"""The indices of non-zero values in the represented dense tensor.
Returns:
A 2-D Tensor of int64 with dense_shape `[N, ndims]`, where `N` is the
number of non-zero values in the tensor, and `ndims` is the rank.
"""
return self._indices | [
"def",
"indices",
"(",
"self",
")",
":",
"return",
"self",
".",
"_indices"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/sparse_tensor.py#L151-L158 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/signal/util_ops.py | python | gcd | (a, b, name=None) | Returns the greatest common divisor via Euclid's algorithm.
Args:
a: The dividend. A scalar integer `Tensor`.
b: The divisor. A scalar integer `Tensor`.
name: An optional name for the operation.
Returns:
A scalar `Tensor` representing the greatest common divisor between `a` and
`b`.
Raises:
ValueError: If `a` or `b` are not scalar integers. | Returns the greatest common divisor via Euclid's algorithm. | [
"Returns",
"the",
"greatest",
"common",
"divisor",
"via",
"Euclid",
"s",
"algorithm",
"."
] | def gcd(a, b, name=None):
"""Returns the greatest common divisor via Euclid's algorithm.
Args:
a: The dividend. A scalar integer `Tensor`.
b: The divisor. A scalar integer `Tensor`.
name: An optional name for the operation.
Returns:
A scalar `Tensor` representing the greatest common divisor between `a` and
`b`.
Raises:
ValueError: If `a` or `b` are not scalar integers.
"""
with ops.name_scope(name, 'gcd', [a, b]):
a = ops.convert_to_tensor(a)
b = ops.convert_to_tensor(b)
a.shape.assert_has_rank(0)
b.shape.assert_has_rank(0)
if not a.dtype.is_integer:
raise ValueError('a must be an integer type. Got: %s' % a.dtype)
if not b.dtype.is_integer:
raise ValueError('b must be an integer type. Got: %s' % b.dtype)
# TPU requires static shape inference. GCD is used for subframe size
# computation, so we should prefer static computation where possible.
const_a = tensor_util.constant_value(a)
const_b = tensor_util.constant_value(b)
if const_a is not None and const_b is not None:
return ops.convert_to_tensor(fractions.gcd(const_a, const_b))
cond = lambda _, b: math_ops.greater(b, array_ops.zeros_like(b))
body = lambda a, b: [b, math_ops.mod(a, b)]
a, b = control_flow_ops.while_loop(cond, body, [a, b], back_prop=False)
return a | [
"def",
"gcd",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'gcd'",
",",
"[",
"a",
",",
"b",
"]",
")",
":",
"a",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"a",
")",
"b",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"b",
")",
"a",
".",
"shape",
".",
"assert_has_rank",
"(",
"0",
")",
"b",
".",
"shape",
".",
"assert_has_rank",
"(",
"0",
")",
"if",
"not",
"a",
".",
"dtype",
".",
"is_integer",
":",
"raise",
"ValueError",
"(",
"'a must be an integer type. Got: %s'",
"%",
"a",
".",
"dtype",
")",
"if",
"not",
"b",
".",
"dtype",
".",
"is_integer",
":",
"raise",
"ValueError",
"(",
"'b must be an integer type. Got: %s'",
"%",
"b",
".",
"dtype",
")",
"# TPU requires static shape inference. GCD is used for subframe size",
"# computation, so we should prefer static computation where possible.",
"const_a",
"=",
"tensor_util",
".",
"constant_value",
"(",
"a",
")",
"const_b",
"=",
"tensor_util",
".",
"constant_value",
"(",
"b",
")",
"if",
"const_a",
"is",
"not",
"None",
"and",
"const_b",
"is",
"not",
"None",
":",
"return",
"ops",
".",
"convert_to_tensor",
"(",
"fractions",
".",
"gcd",
"(",
"const_a",
",",
"const_b",
")",
")",
"cond",
"=",
"lambda",
"_",
",",
"b",
":",
"math_ops",
".",
"greater",
"(",
"b",
",",
"array_ops",
".",
"zeros_like",
"(",
"b",
")",
")",
"body",
"=",
"lambda",
"a",
",",
"b",
":",
"[",
"b",
",",
"math_ops",
".",
"mod",
"(",
"a",
",",
"b",
")",
"]",
"a",
",",
"b",
"=",
"control_flow_ops",
".",
"while_loop",
"(",
"cond",
",",
"body",
",",
"[",
"a",
",",
"b",
"]",
",",
"back_prop",
"=",
"False",
")",
"return",
"a"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/signal/util_ops.py#L30-L67 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.SetEmptySelection | (*args, **kwargs) | return _stc.StyledTextCtrl_SetEmptySelection(*args, **kwargs) | SetEmptySelection(self, int pos) | SetEmptySelection(self, int pos) | [
"SetEmptySelection",
"(",
"self",
"int",
"pos",
")"
] | def SetEmptySelection(*args, **kwargs):
"""SetEmptySelection(self, int pos)"""
return _stc.StyledTextCtrl_SetEmptySelection(*args, **kwargs) | [
"def",
"SetEmptySelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetEmptySelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3460-L3462 |
|
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/configobj/configobj.py | python | Section.as_bool | (self, key) | Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
``False``.
``as_bool`` is not case sensitive.
Any other input will raise a ``ValueError``.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_bool('a')
Traceback (most recent call last):
ValueError: Value "fish" is neither True nor False
>>> a['b'] = 'True'
>>> a.as_bool('b')
1
>>> a['b'] = 'off'
>>> a.as_bool('b')
0 | Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
``False``.
``as_bool`` is not case sensitive.
Any other input will raise a ``ValueError``.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_bool('a')
Traceback (most recent call last):
ValueError: Value "fish" is neither True nor False
>>> a['b'] = 'True'
>>> a.as_bool('b')
1
>>> a['b'] = 'off'
>>> a.as_bool('b')
0 | [
"Accepts",
"a",
"key",
"as",
"input",
".",
"The",
"corresponding",
"value",
"must",
"be",
"a",
"string",
"or",
"the",
"objects",
"(",
"True",
"or",
"1",
")",
"or",
"(",
"False",
"or",
"0",
")",
".",
"We",
"allow",
"0",
"and",
"1",
"to",
"retain",
"compatibility",
"with",
"Python",
"2",
".",
"2",
".",
"If",
"the",
"string",
"is",
"one",
"of",
"True",
"On",
"Yes",
"or",
"1",
"it",
"returns",
"True",
".",
"If",
"the",
"string",
"is",
"one",
"of",
"False",
"Off",
"No",
"or",
"0",
"it",
"returns",
"False",
".",
"as_bool",
"is",
"not",
"case",
"sensitive",
".",
"Any",
"other",
"input",
"will",
"raise",
"a",
"ValueError",
".",
">>>",
"a",
"=",
"ConfigObj",
"()",
">>>",
"a",
"[",
"a",
"]",
"=",
"fish",
">>>",
"a",
".",
"as_bool",
"(",
"a",
")",
"Traceback",
"(",
"most",
"recent",
"call",
"last",
")",
":",
"ValueError",
":",
"Value",
"fish",
"is",
"neither",
"True",
"nor",
"False",
">>>",
"a",
"[",
"b",
"]",
"=",
"True",
">>>",
"a",
".",
"as_bool",
"(",
"b",
")",
"1",
">>>",
"a",
"[",
"b",
"]",
"=",
"off",
">>>",
"a",
".",
"as_bool",
"(",
"b",
")",
"0"
] | def as_bool(self, key):
"""
Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
``False``.
``as_bool`` is not case sensitive.
Any other input will raise a ``ValueError``.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_bool('a')
Traceback (most recent call last):
ValueError: Value "fish" is neither True nor False
>>> a['b'] = 'True'
>>> a.as_bool('b')
1
>>> a['b'] = 'off'
>>> a.as_bool('b')
0
"""
val = self[key]
if val == True:
return True
elif val == False:
return False
else:
try:
if not isinstance(val, basestring):
# TODO: Why do we raise a KeyError here?
raise KeyError()
else:
return self.main._bools[val.lower()]
except KeyError:
raise ValueError('Value "%s" is neither True nor False' % val) | [
"def",
"as_bool",
"(",
"self",
",",
"key",
")",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"if",
"val",
"==",
"True",
":",
"return",
"True",
"elif",
"val",
"==",
"False",
":",
"return",
"False",
"else",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"basestring",
")",
":",
"# TODO: Why do we raise a KeyError here?",
"raise",
"KeyError",
"(",
")",
"else",
":",
"return",
"self",
".",
"main",
".",
"_bools",
"[",
"val",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Value \"%s\" is neither True nor False'",
"%",
"val",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/configobj/configobj.py#L940-L981 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/__init__.py | python | Environment.can_add | (self, dist) | return py_compat and compatible_platforms(dist.platform, self.platform) | Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned. | Is distribution `dist` acceptable for this environment? | [
"Is",
"distribution",
"dist",
"acceptable",
"for",
"this",
"environment?"
] | def can_add(self, dist):
"""Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned.
"""
py_compat = (
self.python is None
or dist.py_version is None
or dist.py_version == self.python
)
return py_compat and compatible_platforms(dist.platform, self.platform) | [
"def",
"can_add",
"(",
"self",
",",
"dist",
")",
":",
"py_compat",
"=",
"(",
"self",
".",
"python",
"is",
"None",
"or",
"dist",
".",
"py_version",
"is",
"None",
"or",
"dist",
".",
"py_version",
"==",
"self",
".",
"python",
")",
"return",
"py_compat",
"and",
"compatible_platforms",
"(",
"dist",
".",
"platform",
",",
"self",
".",
"platform",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/__init__.py#L987-L999 |
|
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Import/App/ap203_configuration_controlled_3d_design_of_mechanical_parts_and_assemblies_mim_lf.py | python | gbsf_check_point | (pnt,) | return FALSE | :param pnt
:type pnt:point | :param pnt
:type pnt:point | [
":",
"param",
"pnt",
":",
"type",
"pnt",
":",
"point"
] | def gbsf_check_point(pnt,):
'''
:param pnt
:type pnt:point
'''
if ('AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.CARTESIAN_POINT' == TYPEOF(pnt)):
return TRUE
else:
if ('AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.POINT_ON_CURVE' == TYPEOF(pnt)):
return gbsf_check_curve(pnt.point_on_curve.basis_curve)
else:
if ('AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.POINT_ON_SURFACE' == TYPEOF(pnt)):
return gbsf_check_surface(pnt.point_on_surface.basis_surface)
else:
if ('AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.DEGENERATE_PCURVE' == TYPEOF(pnt)):
return gbsf_check_curve(pnt.degenerate_pcurve.reference_to_curve.representation.items[1]) and gbsf_check_surface(pnt.degenerate_pcurve.basis_surface)
return FALSE | [
"def",
"gbsf_check_point",
"(",
"pnt",
",",
")",
":",
"if",
"(",
"'AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.CARTESIAN_POINT'",
"==",
"TYPEOF",
"(",
"pnt",
")",
")",
":",
"return",
"TRUE",
"else",
":",
"if",
"(",
"'AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.POINT_ON_CURVE'",
"==",
"TYPEOF",
"(",
"pnt",
")",
")",
":",
"return",
"gbsf_check_curve",
"(",
"pnt",
".",
"point_on_curve",
".",
"basis_curve",
")",
"else",
":",
"if",
"(",
"'AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.POINT_ON_SURFACE'",
"==",
"TYPEOF",
"(",
"pnt",
")",
")",
":",
"return",
"gbsf_check_surface",
"(",
"pnt",
".",
"point_on_surface",
".",
"basis_surface",
")",
"else",
":",
"if",
"(",
"'AP203_CONFIGURATION_CONTROLLED_3D_DESIGN_OF_MECHANICAL_PARTS_AND_ASSEMBLIES_MIM_LF.DEGENERATE_PCURVE'",
"==",
"TYPEOF",
"(",
"pnt",
")",
")",
":",
"return",
"gbsf_check_curve",
"(",
"pnt",
".",
"degenerate_pcurve",
".",
"reference_to_curve",
".",
"representation",
".",
"items",
"[",
"1",
"]",
")",
"and",
"gbsf_check_surface",
"(",
"pnt",
".",
"degenerate_pcurve",
".",
"basis_surface",
")",
"return",
"FALSE"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Import/App/ap203_configuration_controlled_3d_design_of_mechanical_parts_and_assemblies_mim_lf.py#L39463-L39479 |
|
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Tools/ar.py | python | configure | (conf) | Finds the ar program and sets the default flags in ``conf.env.ARFLAGS`` | Finds the ar program and sets the default flags in ``conf.env.ARFLAGS`` | [
"Finds",
"the",
"ar",
"program",
"and",
"sets",
"the",
"default",
"flags",
"in",
"conf",
".",
"env",
".",
"ARFLAGS"
] | def configure(conf):
"""Finds the ar program and sets the default flags in ``conf.env.ARFLAGS``"""
conf.find_program('ar', var='AR')
conf.add_os_flags('ARFLAGS')
if not conf.env.ARFLAGS:
conf.env.ARFLAGS = ['rcs'] | [
"def",
"configure",
"(",
"conf",
")",
":",
"conf",
".",
"find_program",
"(",
"'ar'",
",",
"var",
"=",
"'AR'",
")",
"conf",
".",
"add_os_flags",
"(",
"'ARFLAGS'",
")",
"if",
"not",
"conf",
".",
"env",
".",
"ARFLAGS",
":",
"conf",
".",
"env",
".",
"ARFLAGS",
"=",
"[",
"'rcs'",
"]"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/ar.py#L18-L23 |
||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/sites/client.py | python | SitesClient.download_attachment | (self, uri_or_entry, file_path) | Downloads an attachment file to disk.
Args:
uri_or_entry: string The full URL to download the file from.
file_path: string The full path to save the file to.
Raises:
gdata.client.RequestError: on error response from server. | Downloads an attachment file to disk. | [
"Downloads",
"an",
"attachment",
"file",
"to",
"disk",
"."
] | def download_attachment(self, uri_or_entry, file_path):
"""Downloads an attachment file to disk.
Args:
uri_or_entry: string The full URL to download the file from.
file_path: string The full path to save the file to.
Raises:
gdata.client.RequestError: on error response from server.
"""
uri = uri_or_entry
if isinstance(uri_or_entry, gdata.sites.data.ContentEntry):
uri = uri_or_entry.content.src
f = open(file_path, 'wb')
try:
f.write(self._get_file_content(uri))
except gdata.client.RequestError, e:
f.close()
raise e
f.flush()
f.close() | [
"def",
"download_attachment",
"(",
"self",
",",
"uri_or_entry",
",",
"file_path",
")",
":",
"uri",
"=",
"uri_or_entry",
"if",
"isinstance",
"(",
"uri_or_entry",
",",
"gdata",
".",
"sites",
".",
"data",
".",
"ContentEntry",
")",
":",
"uri",
"=",
"uri_or_entry",
".",
"content",
".",
"src",
"f",
"=",
"open",
"(",
"file_path",
",",
"'wb'",
")",
"try",
":",
"f",
".",
"write",
"(",
"self",
".",
"_get_file_content",
"(",
"uri",
")",
")",
"except",
"gdata",
".",
"client",
".",
"RequestError",
",",
"e",
":",
"f",
".",
"close",
"(",
")",
"raise",
"e",
"f",
".",
"flush",
"(",
")",
"f",
".",
"close",
"(",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/sites/client.py#L339-L360 |
||
baidu/AnyQ | d94d450d2aaa5f7ed73424b10aa4539835b97527 | tools/simnet/train/paddle/nets/gru.py | python | GRU.predict | (self, left, right) | Forward network | Forward network | [
"Forward",
"network"
] | def predict(self, left, right):
"""
Forward network
"""
# embedding layer
emb_layer = layers.EmbeddingLayer(self.dict_size, self.emb_dim, "emb")
left_emb = emb_layer.ops(left)
right_emb = emb_layer.ops(right)
# Presentation context
gru_layer = layers.DynamicGRULayer(self.gru_dim, "gru")
left_gru = gru_layer.ops(left_emb)
right_gru = gru_layer.ops(right_emb)
last_layer = layers.SequenceLastStepLayer()
left_last = last_layer.ops(left_gru)
right_last = last_layer.ops(right_gru)
# matching layer
if self.task_mode == "pairwise":
relu_layer = layers.FCLayer(self.hidden_dim, "relu", "relu")
left_relu = relu_layer.ops(left_last)
right_relu = relu_layer.ops(right_last)
cos_sim_layer = layers.CosSimLayer()
pred = cos_sim_layer.ops(left_relu, right_relu)
return left_relu, pred
else:
concat_layer = layers.ConcatLayer(1)
concat = concat_layer.ops([left_last, right_last])
relu_layer = layers.FCLayer(self.hidden_dim, "relu", "relu")
concat_fc = relu_layer.ops(concat)
softmax_layer = layers.FCLayer(2, "softmax", "cos_sim")
pred = softmax_layer.ops(concat_fc)
return left_last, pred | [
"def",
"predict",
"(",
"self",
",",
"left",
",",
"right",
")",
":",
"# embedding layer",
"emb_layer",
"=",
"layers",
".",
"EmbeddingLayer",
"(",
"self",
".",
"dict_size",
",",
"self",
".",
"emb_dim",
",",
"\"emb\"",
")",
"left_emb",
"=",
"emb_layer",
".",
"ops",
"(",
"left",
")",
"right_emb",
"=",
"emb_layer",
".",
"ops",
"(",
"right",
")",
"# Presentation context",
"gru_layer",
"=",
"layers",
".",
"DynamicGRULayer",
"(",
"self",
".",
"gru_dim",
",",
"\"gru\"",
")",
"left_gru",
"=",
"gru_layer",
".",
"ops",
"(",
"left_emb",
")",
"right_gru",
"=",
"gru_layer",
".",
"ops",
"(",
"right_emb",
")",
"last_layer",
"=",
"layers",
".",
"SequenceLastStepLayer",
"(",
")",
"left_last",
"=",
"last_layer",
".",
"ops",
"(",
"left_gru",
")",
"right_last",
"=",
"last_layer",
".",
"ops",
"(",
"right_gru",
")",
"# matching layer",
"if",
"self",
".",
"task_mode",
"==",
"\"pairwise\"",
":",
"relu_layer",
"=",
"layers",
".",
"FCLayer",
"(",
"self",
".",
"hidden_dim",
",",
"\"relu\"",
",",
"\"relu\"",
")",
"left_relu",
"=",
"relu_layer",
".",
"ops",
"(",
"left_last",
")",
"right_relu",
"=",
"relu_layer",
".",
"ops",
"(",
"right_last",
")",
"cos_sim_layer",
"=",
"layers",
".",
"CosSimLayer",
"(",
")",
"pred",
"=",
"cos_sim_layer",
".",
"ops",
"(",
"left_relu",
",",
"right_relu",
")",
"return",
"left_relu",
",",
"pred",
"else",
":",
"concat_layer",
"=",
"layers",
".",
"ConcatLayer",
"(",
"1",
")",
"concat",
"=",
"concat_layer",
".",
"ops",
"(",
"[",
"left_last",
",",
"right_last",
"]",
")",
"relu_layer",
"=",
"layers",
".",
"FCLayer",
"(",
"self",
".",
"hidden_dim",
",",
"\"relu\"",
",",
"\"relu\"",
")",
"concat_fc",
"=",
"relu_layer",
".",
"ops",
"(",
"concat",
")",
"softmax_layer",
"=",
"layers",
".",
"FCLayer",
"(",
"2",
",",
"\"softmax\"",
",",
"\"cos_sim\"",
")",
"pred",
"=",
"softmax_layer",
".",
"ops",
"(",
"concat_fc",
")",
"return",
"left_last",
",",
"pred"
] | https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/paddle/nets/gru.py#L34-L64 |
||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.put | (self, ch) | This puts a characters at the current cursor position. | This puts a characters at the current cursor position. | [
"This",
"puts",
"a",
"characters",
"at",
"the",
"current",
"cursor",
"position",
"."
] | def put (self, ch):
'''This puts a characters at the current cursor position.
'''
if isinstance(ch, bytes):
ch = self._decode(ch)
self.put_abs (self.cur_r, self.cur_c, ch) | [
"def",
"put",
"(",
"self",
",",
"ch",
")",
":",
"if",
"isinstance",
"(",
"ch",
",",
"bytes",
")",
":",
"ch",
"=",
"self",
".",
"_decode",
"(",
"ch",
")",
"self",
".",
"put_abs",
"(",
"self",
".",
"cur_r",
",",
"self",
".",
"cur_c",
",",
"ch",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L211-L218 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/listobj.py | python | _ListPayloadMixin.clamp_index | (self, idx) | return builder.load(idxptr) | Clamp the index in [0, size]. | Clamp the index in [0, size]. | [
"Clamp",
"the",
"index",
"in",
"[",
"0",
"size",
"]",
"."
] | def clamp_index(self, idx):
"""
Clamp the index in [0, size].
"""
builder = self._builder
idxptr = cgutils.alloca_once_value(builder, idx)
zero = ir.Constant(idx.type, 0)
size = self.size
underflow = self._builder.icmp_signed('<', idx, zero)
with builder.if_then(underflow, likely=False):
builder.store(zero, idxptr)
overflow = self._builder.icmp_signed('>=', idx, size)
with builder.if_then(overflow, likely=False):
builder.store(size, idxptr)
return builder.load(idxptr) | [
"def",
"clamp_index",
"(",
"self",
",",
"idx",
")",
":",
"builder",
"=",
"self",
".",
"_builder",
"idxptr",
"=",
"cgutils",
".",
"alloca_once_value",
"(",
"builder",
",",
"idx",
")",
"zero",
"=",
"ir",
".",
"Constant",
"(",
"idx",
".",
"type",
",",
"0",
")",
"size",
"=",
"self",
".",
"size",
"underflow",
"=",
"self",
".",
"_builder",
".",
"icmp_signed",
"(",
"'<'",
",",
"idx",
",",
"zero",
")",
"with",
"builder",
".",
"if_then",
"(",
"underflow",
",",
"likely",
"=",
"False",
")",
":",
"builder",
".",
"store",
"(",
"zero",
",",
"idxptr",
")",
"overflow",
"=",
"self",
".",
"_builder",
".",
"icmp_signed",
"(",
"'>='",
",",
"idx",
",",
"size",
")",
"with",
"builder",
".",
"if_then",
"(",
"overflow",
",",
"likely",
"=",
"False",
")",
":",
"builder",
".",
"store",
"(",
"size",
",",
"idxptr",
")",
"return",
"builder",
".",
"load",
"(",
"idxptr",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/listobj.py#L86-L103 |
|
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/optim/optimizer.py | python | Optimizer.zero_grad | (self, set_to_none: bool = False) | r"""Sets the gradients of all optimized :class:`torch.Tensor` s to zero.
Args:
set_to_none (bool): instead of setting to zero, set the grads to None.
This will in general have lower memory footprint, and can modestly improve performance.
However, it changes certain behaviors. For example:
1. When the user tries to access a gradient and perform manual ops on it,
a None attribute or a Tensor full of 0s will behave differently.
2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
are guaranteed to be None for params that did not receive a gradient.
3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
(in one case it does the step with a gradient of 0 and in the other it skips
the step altogether). | r"""Sets the gradients of all optimized :class:`torch.Tensor` s to zero. | [
"r",
"Sets",
"the",
"gradients",
"of",
"all",
"optimized",
":",
"class",
":",
"torch",
".",
"Tensor",
"s",
"to",
"zero",
"."
] | def zero_grad(self, set_to_none: bool = False):
r"""Sets the gradients of all optimized :class:`torch.Tensor` s to zero.
Args:
set_to_none (bool): instead of setting to zero, set the grads to None.
This will in general have lower memory footprint, and can modestly improve performance.
However, it changes certain behaviors. For example:
1. When the user tries to access a gradient and perform manual ops on it,
a None attribute or a Tensor full of 0s will behave differently.
2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
are guaranteed to be None for params that did not receive a gradient.
3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
(in one case it does the step with a gradient of 0 and in the other it skips
the step altogether).
"""
foreach = self.defaults.get('foreach', False)
if not hasattr(self, "_zero_grad_profile_name"):
self._hook_for_profile()
if foreach:
per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list))
with torch.autograd.profiler.record_function(self._zero_grad_profile_name):
for group in self.param_groups:
for p in group['params']:
if p.grad is not None:
if set_to_none:
p.grad = None
else:
if p.grad.grad_fn is not None:
p.grad.detach_()
else:
p.grad.requires_grad_(False)
if (not foreach or p.grad.is_sparse):
p.grad.zero_()
else:
per_device_and_dtype_grads[p.grad.device][p.grad.dtype].append(p.grad)
if foreach:
for _, per_dtype_grads in per_device_and_dtype_grads.items():
for grads in per_dtype_grads.values():
torch._foreach_zero_(grads) | [
"def",
"zero_grad",
"(",
"self",
",",
"set_to_none",
":",
"bool",
"=",
"False",
")",
":",
"foreach",
"=",
"self",
".",
"defaults",
".",
"get",
"(",
"'foreach'",
",",
"False",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_zero_grad_profile_name\"",
")",
":",
"self",
".",
"_hook_for_profile",
"(",
")",
"if",
"foreach",
":",
"per_device_and_dtype_grads",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"list",
")",
")",
"with",
"torch",
".",
"autograd",
".",
"profiler",
".",
"record_function",
"(",
"self",
".",
"_zero_grad_profile_name",
")",
":",
"for",
"group",
"in",
"self",
".",
"param_groups",
":",
"for",
"p",
"in",
"group",
"[",
"'params'",
"]",
":",
"if",
"p",
".",
"grad",
"is",
"not",
"None",
":",
"if",
"set_to_none",
":",
"p",
".",
"grad",
"=",
"None",
"else",
":",
"if",
"p",
".",
"grad",
".",
"grad_fn",
"is",
"not",
"None",
":",
"p",
".",
"grad",
".",
"detach_",
"(",
")",
"else",
":",
"p",
".",
"grad",
".",
"requires_grad_",
"(",
"False",
")",
"if",
"(",
"not",
"foreach",
"or",
"p",
".",
"grad",
".",
"is_sparse",
")",
":",
"p",
".",
"grad",
".",
"zero_",
"(",
")",
"else",
":",
"per_device_and_dtype_grads",
"[",
"p",
".",
"grad",
".",
"device",
"]",
"[",
"p",
".",
"grad",
".",
"dtype",
"]",
".",
"append",
"(",
"p",
".",
"grad",
")",
"if",
"foreach",
":",
"for",
"_",
",",
"per_dtype_grads",
"in",
"per_device_and_dtype_grads",
".",
"items",
"(",
")",
":",
"for",
"grads",
"in",
"per_dtype_grads",
".",
"values",
"(",
")",
":",
"torch",
".",
"_foreach_zero_",
"(",
"grads",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/optim/optimizer.py#L189-L228 |
||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/Paste/paste/exceptions/errormiddleware.py | python | ErrorMiddleware.__call__ | (self, environ, start_response) | The WSGI application interface. | The WSGI application interface. | [
"The",
"WSGI",
"application",
"interface",
"."
] | def __call__(self, environ, start_response):
"""
The WSGI application interface.
"""
# We want to be careful about not sending headers twice,
# and the content type that the app has committed to (if there
# is an exception in the iterator body of the response)
if environ.get('paste.throw_errors'):
return self.application(environ, start_response)
environ['paste.throw_errors'] = True
try:
__traceback_supplement__ = Supplement, self, environ
sr_checker = ResponseStartChecker(start_response)
app_iter = self.application(environ, sr_checker)
return self.make_catching_iter(app_iter, environ, sr_checker)
except:
exc_info = sys.exc_info()
try:
for expect in environ.get('paste.expected_exceptions', []):
if isinstance(exc_info[1], expect):
raise
start_response('500 Internal Server Error',
[('content-type', 'text/html')],
exc_info)
# @@: it would be nice to deal with bad content types here
response = self.exception_handler(exc_info, environ)
if six.PY3:
response = response.encode('utf8')
return [response]
finally:
# clean up locals...
exc_info = None | [
"def",
"__call__",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"# We want to be careful about not sending headers twice,",
"# and the content type that the app has committed to (if there",
"# is an exception in the iterator body of the response)",
"if",
"environ",
".",
"get",
"(",
"'paste.throw_errors'",
")",
":",
"return",
"self",
".",
"application",
"(",
"environ",
",",
"start_response",
")",
"environ",
"[",
"'paste.throw_errors'",
"]",
"=",
"True",
"try",
":",
"__traceback_supplement__",
"=",
"Supplement",
",",
"self",
",",
"environ",
"sr_checker",
"=",
"ResponseStartChecker",
"(",
"start_response",
")",
"app_iter",
"=",
"self",
".",
"application",
"(",
"environ",
",",
"sr_checker",
")",
"return",
"self",
".",
"make_catching_iter",
"(",
"app_iter",
",",
"environ",
",",
"sr_checker",
")",
"except",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"try",
":",
"for",
"expect",
"in",
"environ",
".",
"get",
"(",
"'paste.expected_exceptions'",
",",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"exc_info",
"[",
"1",
"]",
",",
"expect",
")",
":",
"raise",
"start_response",
"(",
"'500 Internal Server Error'",
",",
"[",
"(",
"'content-type'",
",",
"'text/html'",
")",
"]",
",",
"exc_info",
")",
"# @@: it would be nice to deal with bad content types here",
"response",
"=",
"self",
".",
"exception_handler",
"(",
"exc_info",
",",
"environ",
")",
"if",
"six",
".",
"PY3",
":",
"response",
"=",
"response",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"[",
"response",
"]",
"finally",
":",
"# clean up locals...",
"exc_info",
"=",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/exceptions/errormiddleware.py#L128-L160 |
||
ucbrise/confluo | 578883a4f7fbbb4aea78c342d366f5122ef598f7 | pyclient/confluo/rpc/client.py | python | RpcClient.archive | (self, offset=-1) | Archives the atomic multilog until provided offset.
Args:
offset: Offset until which multilog should be archived (-1 for full archival).
Raises:
ValueError. | Archives the atomic multilog until provided offset. | [
"Archives",
"the",
"atomic",
"multilog",
"until",
"provided",
"offset",
"."
] | def archive(self, offset=-1):
""" Archives the atomic multilog until provided offset.
Args:
offset: Offset until which multilog should be archived (-1 for full archival).
Raises:
ValueError.
"""
if self.cur_m_id_ == -1:
raise ValueError("Must set atomic multilog first.")
self.client_.archive(self.cur_m_id_, offset) | [
"def",
"archive",
"(",
"self",
",",
"offset",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"cur_m_id_",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"Must set atomic multilog first.\"",
")",
"self",
".",
"client_",
".",
"archive",
"(",
"self",
".",
"cur_m_id_",
",",
"offset",
")"
] | https://github.com/ucbrise/confluo/blob/578883a4f7fbbb4aea78c342d366f5122ef598f7/pyclient/confluo/rpc/client.py#L206-L216 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Canvas.addtag_below | (self, newtag, tagOrId) | Add tag NEWTAG to all items below TAGORID. | Add tag NEWTAG to all items below TAGORID. | [
"Add",
"tag",
"NEWTAG",
"to",
"all",
"items",
"below",
"TAGORID",
"."
] | def addtag_below(self, newtag, tagOrId):
"""Add tag NEWTAG to all items below TAGORID."""
self.addtag(newtag, 'below', tagOrId) | [
"def",
"addtag_below",
"(",
"self",
",",
"newtag",
",",
"tagOrId",
")",
":",
"self",
".",
"addtag",
"(",
"newtag",
",",
"'below'",
",",
"tagOrId",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L2251-L2253 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/_abcoll.py | python | Mapping.get | (self, key, default=None) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | [
"D",
".",
"get",
"(",
"k",
"[",
"d",
"]",
")",
"-",
">",
"D",
"[",
"k",
"]",
"if",
"k",
"in",
"D",
"else",
"d",
".",
"d",
"defaults",
"to",
"None",
"."
] | def get(self, key, default=None):
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
try:
return self[key]
except KeyError:
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/_abcoll.py#L360-L365 |
||
Yijunmaverick/GenerativeFaceCompletion | f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2 | scripts/cpp_lint.py | python | _CppLintState.SetCountingStyle | (self, counting_style) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style | [
"def",
"SetCountingStyle",
"(",
"self",
",",
"counting_style",
")",
":",
"self",
".",
"counting",
"=",
"counting_style"
] | https://github.com/Yijunmaverick/GenerativeFaceCompletion/blob/f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2/scripts/cpp_lint.py#L713-L715 |
||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/nets.py | python | simple_img_conv_pool | (input,
num_filters,
filter_size,
pool_size,
pool_stride,
pool_padding=0,
pool_type='max',
global_pooling=False,
conv_stride=1,
conv_padding=0,
conv_dilation=1,
conv_groups=1,
param_attr=None,
bias_attr=None,
act=None,
use_cudnn=True) | return pool_out | r"""
:api_attr: Static Graph
The simple_img_conv_pool api is composed of :ref:`api_fluid_layers_conv2d` and :ref:`api_fluid_layers_pool2d` .
Args:
input (Variable): 4-D Tensor, shape is [N, C, H, W], data type can be float32 or float64.
num_filters(int): The number of filters. It is the same as the output channels.
filter_size (int|list|tuple): The filter size. If filter_size is a list or
tuple, it must contain two integers, (filter_size_H, filter_size_W). Otherwise,
the filter_size_H = filter_size_W = filter_size.
pool_size (int|list|tuple): The pooling size of pool2d layer. If pool_size
is a list or tuple, it must contain two integers, (pool_size_H, pool_size_W).
Otherwise, the pool_size_H = pool_size_W = pool_size.
pool_stride (int|list|tuple): The pooling stride of pool2d layer. If pool_stride
is a list or tuple, it must contain two integers, (pooling_stride_H, pooling_stride_W).
Otherwise, the pooling_stride_H = pooling_stride_W = pool_stride.
pool_padding (int|list|tuple): The padding of pool2d layer. If pool_padding is a list or
tuple, it must contain two integers, (pool_padding_H, pool_padding_W).
Otherwise, the pool_padding_H = pool_padding_W = pool_padding. Default 0.
pool_type (str): Pooling type can be :math:`max` for max-pooling or :math:`avg` for
average-pooling. Default :math:`max`.
global_pooling (bool): Whether to use the global pooling. If global_pooling = true,
pool_size and pool_padding while be ignored. Default False
conv_stride (int|list|tuple): The stride size of the conv2d Layer. If stride is a
list or tuple, it must contain two integers, (conv_stride_H, conv_stride_W). Otherwise,
the conv_stride_H = conv_stride_W = conv_stride. Default: conv_stride = 1.
conv_padding (int|list|tuple): The padding size of the conv2d Layer. If padding is
a list or tuple, it must contain two integers, (conv_padding_H, conv_padding_W).
Otherwise, the conv_padding_H = conv_padding_W = conv_padding. Default: conv_padding = 0.
conv_dilation (int|list|tuple): The dilation size of the conv2d Layer. If dilation is
a list or tuple, it must contain two integers, (conv_dilation_H, conv_dilation_W).
Otherwise, the conv_dilation_H = conv_dilation_W = conv_dilation. Default: conv_dilation = 1.
conv_groups (int): The groups number of the conv2d Layer. According to grouped
convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
the first half of the filters is only connected to the first half
of the input channels, while the second half of the filters is only
connected to the second half of the input channels. Default: groups=1.
param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights
of conv2d. If it is set to None or one attribute of ParamAttr, conv2d
will create ParamAttr as param_attr. If the Initializer of the param_attr
is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`.
Default: None.
bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv2d.
If it is set to False, no bias will be added to the output units.
If it is set to None or one attribute of ParamAttr, conv2d
will create ParamAttr as bias_attr. If the Initializer of the bias_attr
is not set, the bias is initialized zero. Default: None.
act (str): Activation type for conv2d, if it is set to None, activation is not
appended. Default: None.
use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn
library is installed. Default: True
Return:
4-D Tensor, the result of input after conv2d and pool2d, with the same data type as :attr:`input`
Return Type:
Variable
Examples:
.. code-block:: python
import paddle.fluid as fluid
import paddle
paddle.enable_static()
img = fluid.data(name='img', shape=[100, 1, 28, 28], dtype='float32')
conv_pool = fluid.nets.simple_img_conv_pool(input=img,
filter_size=5,
num_filters=20,
pool_size=2,
pool_stride=2,
act="relu") | r"""
:api_attr: Static Graph | [
"r",
":",
"api_attr",
":",
"Static",
"Graph"
] | def simple_img_conv_pool(input,
num_filters,
filter_size,
pool_size,
pool_stride,
pool_padding=0,
pool_type='max',
global_pooling=False,
conv_stride=1,
conv_padding=0,
conv_dilation=1,
conv_groups=1,
param_attr=None,
bias_attr=None,
act=None,
use_cudnn=True):
r"""
:api_attr: Static Graph
The simple_img_conv_pool api is composed of :ref:`api_fluid_layers_conv2d` and :ref:`api_fluid_layers_pool2d` .
Args:
input (Variable): 4-D Tensor, shape is [N, C, H, W], data type can be float32 or float64.
num_filters(int): The number of filters. It is the same as the output channels.
filter_size (int|list|tuple): The filter size. If filter_size is a list or
tuple, it must contain two integers, (filter_size_H, filter_size_W). Otherwise,
the filter_size_H = filter_size_W = filter_size.
pool_size (int|list|tuple): The pooling size of pool2d layer. If pool_size
is a list or tuple, it must contain two integers, (pool_size_H, pool_size_W).
Otherwise, the pool_size_H = pool_size_W = pool_size.
pool_stride (int|list|tuple): The pooling stride of pool2d layer. If pool_stride
is a list or tuple, it must contain two integers, (pooling_stride_H, pooling_stride_W).
Otherwise, the pooling_stride_H = pooling_stride_W = pool_stride.
pool_padding (int|list|tuple): The padding of pool2d layer. If pool_padding is a list or
tuple, it must contain two integers, (pool_padding_H, pool_padding_W).
Otherwise, the pool_padding_H = pool_padding_W = pool_padding. Default 0.
pool_type (str): Pooling type can be :math:`max` for max-pooling or :math:`avg` for
average-pooling. Default :math:`max`.
global_pooling (bool): Whether to use the global pooling. If global_pooling = true,
pool_size and pool_padding while be ignored. Default False
conv_stride (int|list|tuple): The stride size of the conv2d Layer. If stride is a
list or tuple, it must contain two integers, (conv_stride_H, conv_stride_W). Otherwise,
the conv_stride_H = conv_stride_W = conv_stride. Default: conv_stride = 1.
conv_padding (int|list|tuple): The padding size of the conv2d Layer. If padding is
a list or tuple, it must contain two integers, (conv_padding_H, conv_padding_W).
Otherwise, the conv_padding_H = conv_padding_W = conv_padding. Default: conv_padding = 0.
conv_dilation (int|list|tuple): The dilation size of the conv2d Layer. If dilation is
a list or tuple, it must contain two integers, (conv_dilation_H, conv_dilation_W).
Otherwise, the conv_dilation_H = conv_dilation_W = conv_dilation. Default: conv_dilation = 1.
conv_groups (int): The groups number of the conv2d Layer. According to grouped
convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
the first half of the filters is only connected to the first half
of the input channels, while the second half of the filters is only
connected to the second half of the input channels. Default: groups=1.
param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights
of conv2d. If it is set to None or one attribute of ParamAttr, conv2d
will create ParamAttr as param_attr. If the Initializer of the param_attr
is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`.
Default: None.
bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv2d.
If it is set to False, no bias will be added to the output units.
If it is set to None or one attribute of ParamAttr, conv2d
will create ParamAttr as bias_attr. If the Initializer of the bias_attr
is not set, the bias is initialized zero. Default: None.
act (str): Activation type for conv2d, if it is set to None, activation is not
appended. Default: None.
use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn
library is installed. Default: True
Return:
4-D Tensor, the result of input after conv2d and pool2d, with the same data type as :attr:`input`
Return Type:
Variable
Examples:
.. code-block:: python
import paddle.fluid as fluid
import paddle
paddle.enable_static()
img = fluid.data(name='img', shape=[100, 1, 28, 28], dtype='float32')
conv_pool = fluid.nets.simple_img_conv_pool(input=img,
filter_size=5,
num_filters=20,
pool_size=2,
pool_stride=2,
act="relu")
"""
conv_out = layers.conv2d(
input=input,
num_filters=num_filters,
filter_size=filter_size,
stride=conv_stride,
padding=conv_padding,
dilation=conv_dilation,
groups=conv_groups,
param_attr=param_attr,
bias_attr=bias_attr,
act=act,
use_cudnn=use_cudnn)
pool_out = layers.pool2d(
input=conv_out,
pool_size=pool_size,
pool_type=pool_type,
pool_stride=pool_stride,
pool_padding=pool_padding,
global_pooling=global_pooling,
use_cudnn=use_cudnn)
return pool_out | [
"def",
"simple_img_conv_pool",
"(",
"input",
",",
"num_filters",
",",
"filter_size",
",",
"pool_size",
",",
"pool_stride",
",",
"pool_padding",
"=",
"0",
",",
"pool_type",
"=",
"'max'",
",",
"global_pooling",
"=",
"False",
",",
"conv_stride",
"=",
"1",
",",
"conv_padding",
"=",
"0",
",",
"conv_dilation",
"=",
"1",
",",
"conv_groups",
"=",
"1",
",",
"param_attr",
"=",
"None",
",",
"bias_attr",
"=",
"None",
",",
"act",
"=",
"None",
",",
"use_cudnn",
"=",
"True",
")",
":",
"conv_out",
"=",
"layers",
".",
"conv2d",
"(",
"input",
"=",
"input",
",",
"num_filters",
"=",
"num_filters",
",",
"filter_size",
"=",
"filter_size",
",",
"stride",
"=",
"conv_stride",
",",
"padding",
"=",
"conv_padding",
",",
"dilation",
"=",
"conv_dilation",
",",
"groups",
"=",
"conv_groups",
",",
"param_attr",
"=",
"param_attr",
",",
"bias_attr",
"=",
"bias_attr",
",",
"act",
"=",
"act",
",",
"use_cudnn",
"=",
"use_cudnn",
")",
"pool_out",
"=",
"layers",
".",
"pool2d",
"(",
"input",
"=",
"conv_out",
",",
"pool_size",
"=",
"pool_size",
",",
"pool_type",
"=",
"pool_type",
",",
"pool_stride",
"=",
"pool_stride",
",",
"pool_padding",
"=",
"pool_padding",
",",
"global_pooling",
"=",
"global_pooling",
",",
"use_cudnn",
"=",
"use_cudnn",
")",
"return",
"pool_out"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/nets.py#L30-L141 |
|
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | ImmediatePointerArgument.GetLogArg | (self) | return "static_cast<const void*>(%s)" % self.name | Overridden from Argument. | Overridden from Argument. | [
"Overridden",
"from",
"Argument",
"."
] | def GetLogArg(self):
"""Overridden from Argument."""
return "static_cast<const void*>(%s)" % self.name | [
"def",
"GetLogArg",
"(",
"self",
")",
":",
"return",
"\"static_cast<const void*>(%s)\"",
"%",
"self",
".",
"name"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L8914-L8916 |
|
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/barostats.py | python | BaroMHT.get_ebaro | (self) | return self.thermostat.ethermo + self.kin + self.pot | Calculates the barostat conserved quantity. | Calculates the barostat conserved quantity. | [
"Calculates",
"the",
"barostat",
"conserved",
"quantity",
"."
] | def get_ebaro(self):
"""Calculates the barostat conserved quantity."""
return self.thermostat.ethermo + self.kin + self.pot | [
"def",
"get_ebaro",
"(",
"self",
")",
":",
"return",
"self",
".",
"thermostat",
".",
"ethermo",
"+",
"self",
".",
"kin",
"+",
"self",
".",
"pot"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/barostats.py#L415-L418 |
|
vgteam/vg | cf4d516a5e9ee5163c783e4437ddf16b18a4b561 | vgci/mine-logs.py | python | load_mapeval_runtimes | (map_times_path) | return None | read the runtimes out of map_times.txt, assuming first line is a header | read the runtimes out of map_times.txt, assuming first line is a header | [
"read",
"the",
"runtimes",
"out",
"of",
"map_times",
".",
"txt",
"assuming",
"first",
"line",
"is",
"a",
"header"
] | def load_mapeval_runtimes(map_times_path):
"""
read the runtimes out of map_times.txt, assuming first line is a header
"""
try:
map_times_dict = {}
with open(map_times_path) as map_times_file:
lines = [line for line in map_times_file]
for line in lines[1:]:
toks = line.split('\t')
map_times_dict[toks[0]] = toks[1]
return map_times_dict
except:
pass
return None | [
"def",
"load_mapeval_runtimes",
"(",
"map_times_path",
")",
":",
"try",
":",
"map_times_dict",
"=",
"{",
"}",
"with",
"open",
"(",
"map_times_path",
")",
"as",
"map_times_file",
":",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"map_times_file",
"]",
"for",
"line",
"in",
"lines",
"[",
"1",
":",
"]",
":",
"toks",
"=",
"line",
".",
"split",
"(",
"'\\t'",
")",
"map_times_dict",
"[",
"toks",
"[",
"0",
"]",
"]",
"=",
"toks",
"[",
"1",
"]",
"return",
"map_times_dict",
"except",
":",
"pass",
"return",
"None"
] | https://github.com/vgteam/vg/blob/cf4d516a5e9ee5163c783e4437ddf16b18a4b561/vgci/mine-logs.py#L55-L69 |
|
rampageX/firmware-mod-kit | c94cd6aeee50d92ec5280a6dba6d74828fd3606b | src/binwalk-2.1.1/src/binwalk/modules/hashmatch.py | python | HashMatch._compare_files | (self, file1, file2) | return None | Fuzzy diff two files.
@file1 - The first file to diff.
@file2 - The second file to diff.
Returns the match percentage.
Returns None on error. | Fuzzy diff two files. | [
"Fuzzy",
"diff",
"two",
"files",
"."
] | def _compare_files(self, file1, file2):
'''
Fuzzy diff two files.
@file1 - The first file to diff.
@file2 - The second file to diff.
Returns the match percentage.
Returns None on error.
'''
status = 0
file1_dup = False
file2_dup = False
if not self.filter_by_name or os.path.basename(file1) == os.path.basename(file2):
if os.path.exists(file1) and os.path.exists(file2):
hash1 = ctypes.create_string_buffer(self.FUZZY_MAX_RESULT)
hash2 = ctypes.create_string_buffer(self.FUZZY_MAX_RESULT)
# Check if the last file1 or file2 matches this file1 or file2; no need to re-hash if they match.
if file1 == self.last_file1.name and self.last_file1.hash:
file1_dup = True
else:
self.last_file1.name = file1
if file2 == self.last_file2.name and self.last_file2.hash:
file2_dup = True
else:
self.last_file2.name = file2
try:
if self.strings:
if file1_dup:
file1_strings = self.last_file1.strings
else:
self.last_file1.strings = file1_strings = self._get_strings(file1)
if file2_dup:
file2_strings = self.last_file2.strings
else:
self.last_file2.strings = file2_strings = self._get_strings(file2)
if file1_strings == file2_strings:
return 100
else:
if file1_dup:
hash1 = self.last_file1.hash
else:
status |= self.lib.fuzzy_hash_buf(file1_strings, len(file1_strings), hash1)
if file2_dup:
hash2 = self.last_file2.hash
else:
status |= self.lib.fuzzy_hash_buf(file2_strings, len(file2_strings), hash2)
else:
if file1_dup:
hash1 = self.last_file1.hash
else:
status |= self.lib.fuzzy_hash_filename(file1, hash1)
if file2_dup:
hash2 = self.last_file2.hash
else:
status |= self.lib.fuzzy_hash_filename(file2, hash2)
if status == 0:
if not file1_dup:
self.last_file1.hash = hash1
if not file2_dup:
self.last_file2.hash = hash2
if hash1.raw == hash2.raw:
return 100
else:
return self.lib.fuzzy_compare(hash1, hash2)
except Exception as e:
binwalk.core.common.warning("Exception while doing fuzzy hash: %s" % str(e))
return None | [
"def",
"_compare_files",
"(",
"self",
",",
"file1",
",",
"file2",
")",
":",
"status",
"=",
"0",
"file1_dup",
"=",
"False",
"file2_dup",
"=",
"False",
"if",
"not",
"self",
".",
"filter_by_name",
"or",
"os",
".",
"path",
".",
"basename",
"(",
"file1",
")",
"==",
"os",
".",
"path",
".",
"basename",
"(",
"file2",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file1",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"file2",
")",
":",
"hash1",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"self",
".",
"FUZZY_MAX_RESULT",
")",
"hash2",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"self",
".",
"FUZZY_MAX_RESULT",
")",
"# Check if the last file1 or file2 matches this file1 or file2; no need to re-hash if they match.",
"if",
"file1",
"==",
"self",
".",
"last_file1",
".",
"name",
"and",
"self",
".",
"last_file1",
".",
"hash",
":",
"file1_dup",
"=",
"True",
"else",
":",
"self",
".",
"last_file1",
".",
"name",
"=",
"file1",
"if",
"file2",
"==",
"self",
".",
"last_file2",
".",
"name",
"and",
"self",
".",
"last_file2",
".",
"hash",
":",
"file2_dup",
"=",
"True",
"else",
":",
"self",
".",
"last_file2",
".",
"name",
"=",
"file2",
"try",
":",
"if",
"self",
".",
"strings",
":",
"if",
"file1_dup",
":",
"file1_strings",
"=",
"self",
".",
"last_file1",
".",
"strings",
"else",
":",
"self",
".",
"last_file1",
".",
"strings",
"=",
"file1_strings",
"=",
"self",
".",
"_get_strings",
"(",
"file1",
")",
"if",
"file2_dup",
":",
"file2_strings",
"=",
"self",
".",
"last_file2",
".",
"strings",
"else",
":",
"self",
".",
"last_file2",
".",
"strings",
"=",
"file2_strings",
"=",
"self",
".",
"_get_strings",
"(",
"file2",
")",
"if",
"file1_strings",
"==",
"file2_strings",
":",
"return",
"100",
"else",
":",
"if",
"file1_dup",
":",
"hash1",
"=",
"self",
".",
"last_file1",
".",
"hash",
"else",
":",
"status",
"|=",
"self",
".",
"lib",
".",
"fuzzy_hash_buf",
"(",
"file1_strings",
",",
"len",
"(",
"file1_strings",
")",
",",
"hash1",
")",
"if",
"file2_dup",
":",
"hash2",
"=",
"self",
".",
"last_file2",
".",
"hash",
"else",
":",
"status",
"|=",
"self",
".",
"lib",
".",
"fuzzy_hash_buf",
"(",
"file2_strings",
",",
"len",
"(",
"file2_strings",
")",
",",
"hash2",
")",
"else",
":",
"if",
"file1_dup",
":",
"hash1",
"=",
"self",
".",
"last_file1",
".",
"hash",
"else",
":",
"status",
"|=",
"self",
".",
"lib",
".",
"fuzzy_hash_filename",
"(",
"file1",
",",
"hash1",
")",
"if",
"file2_dup",
":",
"hash2",
"=",
"self",
".",
"last_file2",
".",
"hash",
"else",
":",
"status",
"|=",
"self",
".",
"lib",
".",
"fuzzy_hash_filename",
"(",
"file2",
",",
"hash2",
")",
"if",
"status",
"==",
"0",
":",
"if",
"not",
"file1_dup",
":",
"self",
".",
"last_file1",
".",
"hash",
"=",
"hash1",
"if",
"not",
"file2_dup",
":",
"self",
".",
"last_file2",
".",
"hash",
"=",
"hash2",
"if",
"hash1",
".",
"raw",
"==",
"hash2",
".",
"raw",
":",
"return",
"100",
"else",
":",
"return",
"self",
".",
"lib",
".",
"fuzzy_compare",
"(",
"hash1",
",",
"hash2",
")",
"except",
"Exception",
"as",
"e",
":",
"binwalk",
".",
"core",
".",
"common",
".",
"warning",
"(",
"\"Exception while doing fuzzy hash: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"return",
"None"
] | https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/modules/hashmatch.py#L120-L200 |
|
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/importers/common/importer.py | python | ImporterEngine.get_nodes_in_import_order | (self, nodes: typing.Mapping[str, typing.Any]) | return result | Returns the nodes in an order that is suitable to import. That means
each node is guaranteed to appear after the nodes it relies on. | Returns the nodes in an order that is suitable to import. That means
each node is guaranteed to appear after the nodes it relies on. | [
"Returns",
"the",
"nodes",
"in",
"an",
"order",
"that",
"is",
"suitable",
"to",
"import",
".",
"That",
"means",
"each",
"node",
"is",
"guaranteed",
"to",
"appear",
"after",
"the",
"nodes",
"it",
"relies",
"on",
"."
] | def get_nodes_in_import_order(self, nodes: typing.Mapping[str, typing.Any]):
"""
Returns the nodes in an order that is suitable to import. That means
each node is guaranteed to appear after the nodes it relies on.
"""
pending_nodes = list(nodes.values())
ordered_nodes = []
node_processed = len(pending_nodes) > 0
outputs_available = {}
while node_processed:
node_processed = False
for current_node in pending_nodes:
# Find a node which already has all of its input nodes in the ordered list.
if current_node.operation_type != "Skip":
if all((input_id in outputs_available) for input_id in current_node.inputs if input_id):
pending_nodes.remove(current_node)
ordered_nodes.append(current_node)
node_processed = True
for o in current_node.outputs:
outputs_available[o] = True
pending_nodes = [n for n in pending_nodes if n.operation_type != "Skip"]
if len(pending_nodes) > 0:
_logger.info("### ignoring the following nodes because their inputs are not satisfiable:")
for node in pending_nodes:
_logger.info(" {}({})".format(node.operation_type, node.id))
result = []
for current_node in ordered_nodes:
if current_node.operation_type != "Input" or any(current_node.outputs[0] in node.inputs
for node in ordered_nodes):
result.append(current_node)
return result | [
"def",
"get_nodes_in_import_order",
"(",
"self",
",",
"nodes",
":",
"typing",
".",
"Mapping",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
")",
":",
"pending_nodes",
"=",
"list",
"(",
"nodes",
".",
"values",
"(",
")",
")",
"ordered_nodes",
"=",
"[",
"]",
"node_processed",
"=",
"len",
"(",
"pending_nodes",
")",
">",
"0",
"outputs_available",
"=",
"{",
"}",
"while",
"node_processed",
":",
"node_processed",
"=",
"False",
"for",
"current_node",
"in",
"pending_nodes",
":",
"# Find a node which already has all of its input nodes in the ordered list.",
"if",
"current_node",
".",
"operation_type",
"!=",
"\"Skip\"",
":",
"if",
"all",
"(",
"(",
"input_id",
"in",
"outputs_available",
")",
"for",
"input_id",
"in",
"current_node",
".",
"inputs",
"if",
"input_id",
")",
":",
"pending_nodes",
".",
"remove",
"(",
"current_node",
")",
"ordered_nodes",
".",
"append",
"(",
"current_node",
")",
"node_processed",
"=",
"True",
"for",
"o",
"in",
"current_node",
".",
"outputs",
":",
"outputs_available",
"[",
"o",
"]",
"=",
"True",
"pending_nodes",
"=",
"[",
"n",
"for",
"n",
"in",
"pending_nodes",
"if",
"n",
".",
"operation_type",
"!=",
"\"Skip\"",
"]",
"if",
"len",
"(",
"pending_nodes",
")",
">",
"0",
":",
"_logger",
".",
"info",
"(",
"\"### ignoring the following nodes because their inputs are not satisfiable:\"",
")",
"for",
"node",
"in",
"pending_nodes",
":",
"_logger",
".",
"info",
"(",
"\" {}({})\"",
".",
"format",
"(",
"node",
".",
"operation_type",
",",
"node",
".",
"id",
")",
")",
"result",
"=",
"[",
"]",
"for",
"current_node",
"in",
"ordered_nodes",
":",
"if",
"current_node",
".",
"operation_type",
"!=",
"\"Input\"",
"or",
"any",
"(",
"current_node",
".",
"outputs",
"[",
"0",
"]",
"in",
"node",
".",
"inputs",
"for",
"node",
"in",
"ordered_nodes",
")",
":",
"result",
".",
"append",
"(",
"current_node",
")",
"return",
"result"
] | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/common/importer.py#L341-L374 |
|
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntHI.GetDat | (self, *args) | return _snap.TIntHI_GetDat(self, *args) | GetDat(TIntHI self) -> TInt
GetDat(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > * | GetDat(TIntHI self) -> TInt
GetDat(TIntHI self) -> TInt | [
"GetDat",
"(",
"TIntHI",
"self",
")",
"-",
">",
"TInt",
"GetDat",
"(",
"TIntHI",
"self",
")",
"-",
">",
"TInt"
] | def GetDat(self, *args):
"""
GetDat(TIntHI self) -> TInt
GetDat(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > *
"""
return _snap.TIntHI_GetDat(self, *args) | [
"def",
"GetDat",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntHI_GetDat",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19067-L19076 |
|
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/md/compute.py | python | ThermodynamicQuantities.pressure_tensor | (self) | return self._cpp_obj.pressure_tensor | Instantaneous pressure tensor of the group \
:math:`[\\mathrm{pressure}]`.
(:math:`P_{xx}`, :math:`P_{xy}`, :math:`P_{xz}`, :math:`P_{yy}`,
:math:`P_{yz}`, :math:`P_{zz}`). calculated as:
.. math::
P_{ij} = \\left[\\sum_{k \\in \\mathrm{filter}} m_k
\\vec{v}_{k,i} \\cdot \\vec{v}_{k,j} + \\sum_{k \\in
\\mathrm{filter}} \\sum_{l} \\frac{1}{2} \\left(\\vec{r}_{kl,i}
\\cdot \\vec{F}_{kl,j} + \\vec{r}_{kl,j} \\cdot \\vec{F}_{kl,i}
\\right) \\right]/V
where :math:`V` is the total simulation box volume (or area in 2D). | Instantaneous pressure tensor of the group \
:math:`[\\mathrm{pressure}]`. | [
"Instantaneous",
"pressure",
"tensor",
"of",
"the",
"group",
"\\",
":",
"math",
":",
"[",
"\\\\",
"mathrm",
"{",
"pressure",
"}",
"]",
"."
] | def pressure_tensor(self):
"""Instantaneous pressure tensor of the group \
:math:`[\\mathrm{pressure}]`.
(:math:`P_{xx}`, :math:`P_{xy}`, :math:`P_{xz}`, :math:`P_{yy}`,
:math:`P_{yz}`, :math:`P_{zz}`). calculated as:
.. math::
P_{ij} = \\left[\\sum_{k \\in \\mathrm{filter}} m_k
\\vec{v}_{k,i} \\cdot \\vec{v}_{k,j} + \\sum_{k \\in
\\mathrm{filter}} \\sum_{l} \\frac{1}{2} \\left(\\vec{r}_{kl,i}
\\cdot \\vec{F}_{kl,j} + \\vec{r}_{kl,j} \\cdot \\vec{F}_{kl,i}
\\right) \\right]/V
where :math:`V` is the total simulation box volume (or area in 2D).
"""
self._cpp_obj.compute(self._simulation.timestep)
return self._cpp_obj.pressure_tensor | [
"def",
"pressure_tensor",
"(",
"self",
")",
":",
"self",
".",
"_cpp_obj",
".",
"compute",
"(",
"self",
".",
"_simulation",
".",
"timestep",
")",
"return",
"self",
".",
"_cpp_obj",
".",
"pressure_tensor"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/md/compute.py#L96-L114 |
|
perilouswithadollarsign/cstrike15_src | f82112a2388b841d72cb62ca48ab1846dfcc11c8 | thirdparty/protobuf-2.5.0/python/google/protobuf/reflection.py | python | ParseMessage | (descriptor, byte_str) | return new_msg | Generate a new Message instance from this Descriptor and a byte string.
Args:
descriptor: Protobuf Descriptor object
byte_str: Serialized protocol buffer byte string
Returns:
Newly created protobuf Message object. | Generate a new Message instance from this Descriptor and a byte string. | [
"Generate",
"a",
"new",
"Message",
"instance",
"from",
"this",
"Descriptor",
"and",
"a",
"byte",
"string",
"."
] | def ParseMessage(descriptor, byte_str):
"""Generate a new Message instance from this Descriptor and a byte string.
Args:
descriptor: Protobuf Descriptor object
byte_str: Serialized protocol buffer byte string
Returns:
Newly created protobuf Message object.
"""
class _ResultClass(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor
new_msg = _ResultClass()
new_msg.ParseFromString(byte_str)
return new_msg | [
"def",
"ParseMessage",
"(",
"descriptor",
",",
"byte_str",
")",
":",
"class",
"_ResultClass",
"(",
"message",
".",
"Message",
")",
":",
"__metaclass__",
"=",
"GeneratedProtocolMessageType",
"DESCRIPTOR",
"=",
"descriptor",
"new_msg",
"=",
"_ResultClass",
"(",
")",
"new_msg",
".",
"ParseFromString",
"(",
"byte_str",
")",
"return",
"new_msg"
] | https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/reflection.py#L152-L169 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/typing.py | python | get_type_hints | (obj, globalns=None, localns=None) | return hints | Return type hints for an object.
This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals, and if necessary
adds Optional[t] if a default value equal to None is set.
The argument may be a module, class, method, or function. The annotations
are returned as a dictionary. For classes, annotations include also
inherited members.
TypeError is raised if the argument is not of a type that can contain
annotations, and an empty dictionary is returned if no annotations are
present.
BEWARE -- the behavior of globalns and localns is counterintuitive
(unless you are familiar with how eval() and exec() work). The
search order is locals first, then globals.
- If no dict arguments are passed, an attempt is made to use the
globals from obj (or the respective module's globals for classes),
and these are also used as the locals. If the object does not appear
to have globals, an empty dictionary is used.
- If one dict argument is passed, it is used for both globals and
locals.
- If two dict arguments are passed, they specify globals and
locals, respectively. | Return type hints for an object. | [
"Return",
"type",
"hints",
"for",
"an",
"object",
"."
] | def get_type_hints(obj, globalns=None, localns=None):
"""Return type hints for an object.
This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals, and if necessary
adds Optional[t] if a default value equal to None is set.
The argument may be a module, class, method, or function. The annotations
are returned as a dictionary. For classes, annotations include also
inherited members.
TypeError is raised if the argument is not of a type that can contain
annotations, and an empty dictionary is returned if no annotations are
present.
BEWARE -- the behavior of globalns and localns is counterintuitive
(unless you are familiar with how eval() and exec() work). The
search order is locals first, then globals.
- If no dict arguments are passed, an attempt is made to use the
globals from obj (or the respective module's globals for classes),
and these are also used as the locals. If the object does not appear
to have globals, an empty dictionary is used.
- If one dict argument is passed, it is used for both globals and
locals.
- If two dict arguments are passed, they specify globals and
locals, respectively.
"""
if getattr(obj, '__no_type_check__', None):
return {}
# Classes require a special treatment.
if isinstance(obj, type):
hints = {}
for base in reversed(obj.__mro__):
if globalns is None:
base_globals = sys.modules[base.__module__].__dict__
else:
base_globals = globalns
ann = base.__dict__.get('__annotations__', {})
for name, value in ann.items():
if value is None:
value = type(None)
if isinstance(value, str):
value = ForwardRef(value, is_argument=False)
value = _eval_type(value, base_globals, localns)
hints[name] = value
return hints
if globalns is None:
if isinstance(obj, types.ModuleType):
globalns = obj.__dict__
else:
nsobj = obj
# Find globalns for the unwrapped object.
while hasattr(nsobj, '__wrapped__'):
nsobj = nsobj.__wrapped__
globalns = getattr(nsobj, '__globals__', {})
if localns is None:
localns = globalns
elif localns is None:
localns = globalns
hints = getattr(obj, '__annotations__', None)
if hints is None:
# Return empty annotations for something that _could_ have them.
if isinstance(obj, _allowed_types):
return {}
else:
raise TypeError('{!r} is not a module, class, method, '
'or function.'.format(obj))
defaults = _get_defaults(obj)
hints = dict(hints)
for name, value in hints.items():
if value is None:
value = type(None)
if isinstance(value, str):
value = ForwardRef(value)
value = _eval_type(value, globalns, localns)
if name in defaults and defaults[name] is None:
value = Optional[value]
hints[name] = value
return hints | [
"def",
"get_type_hints",
"(",
"obj",
",",
"globalns",
"=",
"None",
",",
"localns",
"=",
"None",
")",
":",
"if",
"getattr",
"(",
"obj",
",",
"'__no_type_check__'",
",",
"None",
")",
":",
"return",
"{",
"}",
"# Classes require a special treatment.",
"if",
"isinstance",
"(",
"obj",
",",
"type",
")",
":",
"hints",
"=",
"{",
"}",
"for",
"base",
"in",
"reversed",
"(",
"obj",
".",
"__mro__",
")",
":",
"if",
"globalns",
"is",
"None",
":",
"base_globals",
"=",
"sys",
".",
"modules",
"[",
"base",
".",
"__module__",
"]",
".",
"__dict__",
"else",
":",
"base_globals",
"=",
"globalns",
"ann",
"=",
"base",
".",
"__dict__",
".",
"get",
"(",
"'__annotations__'",
",",
"{",
"}",
")",
"for",
"name",
",",
"value",
"in",
"ann",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"type",
"(",
"None",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"ForwardRef",
"(",
"value",
",",
"is_argument",
"=",
"False",
")",
"value",
"=",
"_eval_type",
"(",
"value",
",",
"base_globals",
",",
"localns",
")",
"hints",
"[",
"name",
"]",
"=",
"value",
"return",
"hints",
"if",
"globalns",
"is",
"None",
":",
"if",
"isinstance",
"(",
"obj",
",",
"types",
".",
"ModuleType",
")",
":",
"globalns",
"=",
"obj",
".",
"__dict__",
"else",
":",
"nsobj",
"=",
"obj",
"# Find globalns for the unwrapped object.",
"while",
"hasattr",
"(",
"nsobj",
",",
"'__wrapped__'",
")",
":",
"nsobj",
"=",
"nsobj",
".",
"__wrapped__",
"globalns",
"=",
"getattr",
"(",
"nsobj",
",",
"'__globals__'",
",",
"{",
"}",
")",
"if",
"localns",
"is",
"None",
":",
"localns",
"=",
"globalns",
"elif",
"localns",
"is",
"None",
":",
"localns",
"=",
"globalns",
"hints",
"=",
"getattr",
"(",
"obj",
",",
"'__annotations__'",
",",
"None",
")",
"if",
"hints",
"is",
"None",
":",
"# Return empty annotations for something that _could_ have them.",
"if",
"isinstance",
"(",
"obj",
",",
"_allowed_types",
")",
":",
"return",
"{",
"}",
"else",
":",
"raise",
"TypeError",
"(",
"'{!r} is not a module, class, method, '",
"'or function.'",
".",
"format",
"(",
"obj",
")",
")",
"defaults",
"=",
"_get_defaults",
"(",
"obj",
")",
"hints",
"=",
"dict",
"(",
"hints",
")",
"for",
"name",
",",
"value",
"in",
"hints",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"type",
"(",
"None",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"ForwardRef",
"(",
"value",
")",
"value",
"=",
"_eval_type",
"(",
"value",
",",
"globalns",
",",
"localns",
")",
"if",
"name",
"in",
"defaults",
"and",
"defaults",
"[",
"name",
"]",
"is",
"None",
":",
"value",
"=",
"Optional",
"[",
"value",
"]",
"hints",
"[",
"name",
"]",
"=",
"value",
"return",
"hints"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/typing.py#L934-L1017 |
|
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py | python | MSVSProject.__init__ | (self, path, name = None, dependencies = None, guid = None,
spec = None, build_file = None, config_platform_overrides = None,
fixpath_prefix = None) | Initializes the project.
Args:
path: Absolute path to the project file.
name: Name of project. If None, the name will be the same as the base
name of the project file.
dependencies: List of other Project objects this project is dependent
upon, if not None.
guid: GUID to use for project, if not None.
spec: Dictionary specifying how to build this project.
build_file: Filename of the .gyp file that the vcproj file comes from.
config_platform_overrides: optional dict of configuration platforms to
used in place of the default for this target.
fixpath_prefix: the path used to adjust the behavior of _fixpath | Initializes the project. | [
"Initializes",
"the",
"project",
"."
] | def __init__(self, path, name = None, dependencies = None, guid = None,
spec = None, build_file = None, config_platform_overrides = None,
fixpath_prefix = None):
"""Initializes the project.
Args:
path: Absolute path to the project file.
name: Name of project. If None, the name will be the same as the base
name of the project file.
dependencies: List of other Project objects this project is dependent
upon, if not None.
guid: GUID to use for project, if not None.
spec: Dictionary specifying how to build this project.
build_file: Filename of the .gyp file that the vcproj file comes from.
config_platform_overrides: optional dict of configuration platforms to
used in place of the default for this target.
fixpath_prefix: the path used to adjust the behavior of _fixpath
"""
self.path = path
self.guid = guid
self.spec = spec
self.build_file = build_file
# Use project filename if name not specified
self.name = name or os.path.splitext(os.path.basename(path))[0]
# Copy passed lists (or set to empty lists)
self.dependencies = list(dependencies or [])
self.entry_type_guid = ENTRY_TYPE_GUIDS['project']
if config_platform_overrides:
self.config_platform_overrides = config_platform_overrides
else:
self.config_platform_overrides = {}
self.fixpath_prefix = fixpath_prefix
self.msbuild_toolset = None | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"name",
"=",
"None",
",",
"dependencies",
"=",
"None",
",",
"guid",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"build_file",
"=",
"None",
",",
"config_platform_overrides",
"=",
"None",
",",
"fixpath_prefix",
"=",
"None",
")",
":",
"self",
".",
"path",
"=",
"path",
"self",
".",
"guid",
"=",
"guid",
"self",
".",
"spec",
"=",
"spec",
"self",
".",
"build_file",
"=",
"build_file",
"# Use project filename if name not specified",
"self",
".",
"name",
"=",
"name",
"or",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]",
"# Copy passed lists (or set to empty lists)",
"self",
".",
"dependencies",
"=",
"list",
"(",
"dependencies",
"or",
"[",
"]",
")",
"self",
".",
"entry_type_guid",
"=",
"ENTRY_TYPE_GUIDS",
"[",
"'project'",
"]",
"if",
"config_platform_overrides",
":",
"self",
".",
"config_platform_overrides",
"=",
"config_platform_overrides",
"else",
":",
"self",
".",
"config_platform_overrides",
"=",
"{",
"}",
"self",
".",
"fixpath_prefix",
"=",
"fixpath_prefix",
"self",
".",
"msbuild_toolset",
"=",
"None"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py#L112-L147 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/internals/array_manager.py | python | SingleArrayManager.idelete | (self, indexer) | return self | Delete selected locations in-place (new array, same ArrayManager) | Delete selected locations in-place (new array, same ArrayManager) | [
"Delete",
"selected",
"locations",
"in",
"-",
"place",
"(",
"new",
"array",
"same",
"ArrayManager",
")"
] | def idelete(self, indexer) -> SingleArrayManager:
"""
Delete selected locations in-place (new array, same ArrayManager)
"""
to_keep = np.ones(self.shape[0], dtype=np.bool_)
to_keep[indexer] = False
self.arrays = [self.arrays[0][to_keep]]
self._axes = [self._axes[0][to_keep]]
return self | [
"def",
"idelete",
"(",
"self",
",",
"indexer",
")",
"->",
"SingleArrayManager",
":",
"to_keep",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"np",
".",
"bool_",
")",
"to_keep",
"[",
"indexer",
"]",
"=",
"False",
"self",
".",
"arrays",
"=",
"[",
"self",
".",
"arrays",
"[",
"0",
"]",
"[",
"to_keep",
"]",
"]",
"self",
".",
"_axes",
"=",
"[",
"self",
".",
"_axes",
"[",
"0",
"]",
"[",
"to_keep",
"]",
"]",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/array_manager.py#L1292-L1301 |
|
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/data_flow_ops.py | python | ConditionalAccumulator.take_grad | (self, num_required, name=None) | return out | Attempts to extract the average gradient from the accumulator.
The operation blocks until sufficient number of gradients have been
successfully applied to the accumulator.
Once successful, the following actions are also triggered:
- Counter of accumulated gradients is reset to 0.
- Aggregated gradient is reset to 0 tensor.
- Accumulator's internal time step is incremented by 1.
Args:
num_required: Number of gradients that needs to have been aggregated
name: Optional name for the operation
Returns:
A tensor holding the value of the average gradient.
Raises:
InvalidArgumentError: If num_required < 1 | Attempts to extract the average gradient from the accumulator. | [
"Attempts",
"to",
"extract",
"the",
"average",
"gradient",
"from",
"the",
"accumulator",
"."
] | def take_grad(self, num_required, name=None):
"""Attempts to extract the average gradient from the accumulator.
The operation blocks until sufficient number of gradients have been
successfully applied to the accumulator.
Once successful, the following actions are also triggered:
- Counter of accumulated gradients is reset to 0.
- Aggregated gradient is reset to 0 tensor.
- Accumulator's internal time step is incremented by 1.
Args:
num_required: Number of gradients that needs to have been aggregated
name: Optional name for the operation
Returns:
A tensor holding the value of the average gradient.
Raises:
InvalidArgumentError: If num_required < 1
"""
out = gen_data_flow_ops.accumulator_take_gradient(
self._accumulator_ref, num_required, dtype=self._dtype, name=name)
out.set_shape(self._shape)
return out | [
"def",
"take_grad",
"(",
"self",
",",
"num_required",
",",
"name",
"=",
"None",
")",
":",
"out",
"=",
"gen_data_flow_ops",
".",
"accumulator_take_gradient",
"(",
"self",
".",
"_accumulator_ref",
",",
"num_required",
",",
"dtype",
"=",
"self",
".",
"_dtype",
",",
"name",
"=",
"name",
")",
"out",
".",
"set_shape",
"(",
"self",
".",
"_shape",
")",
"return",
"out"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L1212-L1237 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | Font.GetDefaultEncoding | (*args, **kwargs) | return _gdi_.Font_GetDefaultEncoding(*args, **kwargs) | GetDefaultEncoding() -> int
Returns the encoding used for all fonts created with an encoding of
``wx.FONTENCODING_DEFAULT``. | GetDefaultEncoding() -> int | [
"GetDefaultEncoding",
"()",
"-",
">",
"int"
] | def GetDefaultEncoding(*args, **kwargs):
"""
GetDefaultEncoding() -> int
Returns the encoding used for all fonts created with an encoding of
``wx.FONTENCODING_DEFAULT``.
"""
return _gdi_.Font_GetDefaultEncoding(*args, **kwargs) | [
"def",
"GetDefaultEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Font_GetDefaultEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2597-L2604 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/sparse/base.py | python | spmatrix.tocsr | (self, copy=False) | return self.tocoo(copy=copy).tocsr(copy=False) | Convert this matrix to Compressed Sparse Row format.
With copy=False, the data/indices may be shared between this matrix and
the resultant csr_matrix. | Convert this matrix to Compressed Sparse Row format. | [
"Convert",
"this",
"matrix",
"to",
"Compressed",
"Sparse",
"Row",
"format",
"."
] | def tocsr(self, copy=False):
"""Convert this matrix to Compressed Sparse Row format.
With copy=False, the data/indices may be shared between this matrix and
the resultant csr_matrix.
"""
return self.tocoo(copy=copy).tocsr(copy=False) | [
"def",
"tocsr",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"return",
"self",
".",
"tocoo",
"(",
"copy",
"=",
"copy",
")",
".",
"tocsr",
"(",
"copy",
"=",
"False",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/base.py#L884-L890 |
|
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | cmake/developer_package/cpplint/cpplint.py | python | IsBlockInNameSpace | (nesting_state, is_forward_declaration) | return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo)) | Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace. | Checks that the new block is directly in a namespace. | [
"Checks",
"that",
"the",
"new",
"block",
"is",
"directly",
"in",
"a",
"namespace",
"."
] | def IsBlockInNameSpace(nesting_state, is_forward_declaration):
"""Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace.
"""
if is_forward_declaration:
return len(nesting_state.stack) >= 1 and (
isinstance(nesting_state.stack[-1], _NamespaceInfo))
return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo)) | [
"def",
"IsBlockInNameSpace",
"(",
"nesting_state",
",",
"is_forward_declaration",
")",
":",
"if",
"is_forward_declaration",
":",
"return",
"len",
"(",
"nesting_state",
".",
"stack",
")",
">=",
"1",
"and",
"(",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_NamespaceInfo",
")",
")",
"return",
"(",
"len",
"(",
"nesting_state",
".",
"stack",
")",
">",
"1",
"and",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"check_namespace_indentation",
"and",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"2",
"]",
",",
"_NamespaceInfo",
")",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/cmake/developer_package/cpplint/cpplint.py#L6005-L6021 |
|
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/tools/grit/grit/node/base.py | python | Node.GetNodeById | (self, id) | return None | Returns the node in the subtree parented by this node that has a 'name'
attribute matching 'id'. Returns None if no such node is found. | Returns the node in the subtree parented by this node that has a 'name'
attribute matching 'id'. Returns None if no such node is found. | [
"Returns",
"the",
"node",
"in",
"the",
"subtree",
"parented",
"by",
"this",
"node",
"that",
"has",
"a",
"name",
"attribute",
"matching",
"id",
".",
"Returns",
"None",
"if",
"no",
"such",
"node",
"is",
"found",
"."
] | def GetNodeById(self, id):
'''Returns the node in the subtree parented by this node that has a 'name'
attribute matching 'id'. Returns None if no such node is found.
'''
for node in self:
if 'name' in node.attrs and node.attrs['name'] == id:
return node
return None | [
"def",
"GetNodeById",
"(",
"self",
",",
"id",
")",
":",
"for",
"node",
"in",
"self",
":",
"if",
"'name'",
"in",
"node",
".",
"attrs",
"and",
"node",
".",
"attrs",
"[",
"'name'",
"]",
"==",
"id",
":",
"return",
"node",
"return",
"None"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/node/base.py#L444-L451 |
|
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTarget.DisableAllWatchpoints | (self) | return _lldb.SBTarget_DisableAllWatchpoints(self) | DisableAllWatchpoints(self) -> bool | DisableAllWatchpoints(self) -> bool | [
"DisableAllWatchpoints",
"(",
"self",
")",
"-",
">",
"bool"
] | def DisableAllWatchpoints(self):
"""DisableAllWatchpoints(self) -> bool"""
return _lldb.SBTarget_DisableAllWatchpoints(self) | [
"def",
"DisableAllWatchpoints",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBTarget_DisableAllWatchpoints",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L9217-L9219 |
|
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/image-classification/symbols/resnext.py | python | resnext | (units, num_stages, filter_list, num_classes, num_group, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, dtype='float32', memonger=False) | return mx.sym.SoftmaxOutput(data=fc1, name='softmax') | Return ResNeXt symbol of
Parameters
----------
units : list
Number of units in each stage
num_stages : int
Number of stage
filter_list : list
Channel size of each stage
num_classes : int
Ouput size of symbol
num_groupes: int
Number of conv groups
dataset : str
Dataset type, only cifar10 and imagenet supports
workspace : int
Workspace used in convolution operator
dtype : str
Precision (float32 or float16) | Return ResNeXt symbol of
Parameters
----------
units : list
Number of units in each stage
num_stages : int
Number of stage
filter_list : list
Channel size of each stage
num_classes : int
Ouput size of symbol
num_groupes: int
Number of conv groups
dataset : str
Dataset type, only cifar10 and imagenet supports
workspace : int
Workspace used in convolution operator
dtype : str
Precision (float32 or float16) | [
"Return",
"ResNeXt",
"symbol",
"of",
"Parameters",
"----------",
"units",
":",
"list",
"Number",
"of",
"units",
"in",
"each",
"stage",
"num_stages",
":",
"int",
"Number",
"of",
"stage",
"filter_list",
":",
"list",
"Channel",
"size",
"of",
"each",
"stage",
"num_classes",
":",
"int",
"Ouput",
"size",
"of",
"symbol",
"num_groupes",
":",
"int",
"Number",
"of",
"conv",
"groups",
"dataset",
":",
"str",
"Dataset",
"type",
"only",
"cifar10",
"and",
"imagenet",
"supports",
"workspace",
":",
"int",
"Workspace",
"used",
"in",
"convolution",
"operator",
"dtype",
":",
"str",
"Precision",
"(",
"float32",
"or",
"float16",
")"
] | def resnext(units, num_stages, filter_list, num_classes, num_group, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, dtype='float32', memonger=False):
"""Return ResNeXt symbol of
Parameters
----------
units : list
Number of units in each stage
num_stages : int
Number of stage
filter_list : list
Channel size of each stage
num_classes : int
Ouput size of symbol
num_groupes: int
Number of conv groups
dataset : str
Dataset type, only cifar10 and imagenet supports
workspace : int
Workspace used in convolution operator
dtype : str
Precision (float32 or float16)
"""
num_unit = len(units)
assert(num_unit == num_stages)
data = mx.sym.Variable(name='data')
if dtype == 'float32':
data = mx.sym.identity(data=data, name='id')
else:
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
data = mx.sym.BatchNorm(data=data, fix_gamma=True, eps=2e-5, momentum=bn_mom, name='bn_data')
(nchannel, height, width) = image_shape
if height <= 32: # such as cifar10
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(3, 3), stride=(1,1), pad=(1, 1),
no_bias=True, name="conv0", workspace=workspace)
else: # often expected to be 224 such as imagenet
body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(7, 7), stride=(2,2), pad=(3, 3),
no_bias=True, name="conv0", workspace=workspace)
body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0')
body = mx.sym.Activation(data=body, act_type='relu', name='relu0')
body = mx.sym.Pooling(data=body, kernel=(3, 3), stride=(2,2), pad=(1,1), pool_type='max')
for i in range(num_stages):
body = residual_unit(body, filter_list[i+1], (1 if i==0 else 2, 1 if i==0 else 2), False,
name='stage%d_unit%d' % (i + 1, 1), bottle_neck=bottle_neck, num_group=num_group,
bn_mom=bn_mom, workspace=workspace, memonger=memonger)
for j in range(units[i]-1):
body = residual_unit(body, filter_list[i+1], (1,1), True, name='stage%d_unit%d' % (i + 1, j + 2),
bottle_neck=bottle_neck, num_group=num_group, bn_mom=bn_mom, workspace=workspace, memonger=memonger)
pool1 = mx.sym.Pooling(data=body, global_pool=True, kernel=(7, 7), pool_type='avg', name='pool1')
flat = mx.sym.Flatten(data=pool1)
fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name='fc1')
if dtype == 'float16':
fc1 = mx.sym.Cast(data=fc1, dtype=np.float32)
return mx.sym.SoftmaxOutput(data=fc1, name='softmax') | [
"def",
"resnext",
"(",
"units",
",",
"num_stages",
",",
"filter_list",
",",
"num_classes",
",",
"num_group",
",",
"image_shape",
",",
"bottle_neck",
"=",
"True",
",",
"bn_mom",
"=",
"0.9",
",",
"workspace",
"=",
"256",
",",
"dtype",
"=",
"'float32'",
",",
"memonger",
"=",
"False",
")",
":",
"num_unit",
"=",
"len",
"(",
"units",
")",
"assert",
"(",
"num_unit",
"==",
"num_stages",
")",
"data",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"name",
"=",
"'data'",
")",
"if",
"dtype",
"==",
"'float32'",
":",
"data",
"=",
"mx",
".",
"sym",
".",
"identity",
"(",
"data",
"=",
"data",
",",
"name",
"=",
"'id'",
")",
"else",
":",
"if",
"dtype",
"==",
"'float16'",
":",
"data",
"=",
"mx",
".",
"sym",
".",
"Cast",
"(",
"data",
"=",
"data",
",",
"dtype",
"=",
"np",
".",
"float16",
")",
"data",
"=",
"mx",
".",
"sym",
".",
"BatchNorm",
"(",
"data",
"=",
"data",
",",
"fix_gamma",
"=",
"True",
",",
"eps",
"=",
"2e-5",
",",
"momentum",
"=",
"bn_mom",
",",
"name",
"=",
"'bn_data'",
")",
"(",
"nchannel",
",",
"height",
",",
"width",
")",
"=",
"image_shape",
"if",
"height",
"<=",
"32",
":",
"# such as cifar10",
"body",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"data",
",",
"num_filter",
"=",
"filter_list",
"[",
"0",
"]",
",",
"kernel",
"=",
"(",
"3",
",",
"3",
")",
",",
"stride",
"=",
"(",
"1",
",",
"1",
")",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"no_bias",
"=",
"True",
",",
"name",
"=",
"\"conv0\"",
",",
"workspace",
"=",
"workspace",
")",
"else",
":",
"# often expected to be 224 such as imagenet",
"body",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"data",
",",
"num_filter",
"=",
"filter_list",
"[",
"0",
"]",
",",
"kernel",
"=",
"(",
"7",
",",
"7",
")",
",",
"stride",
"=",
"(",
"2",
",",
"2",
")",
",",
"pad",
"=",
"(",
"3",
",",
"3",
")",
",",
"no_bias",
"=",
"True",
",",
"name",
"=",
"\"conv0\"",
",",
"workspace",
"=",
"workspace",
")",
"body",
"=",
"mx",
".",
"sym",
".",
"BatchNorm",
"(",
"data",
"=",
"body",
",",
"fix_gamma",
"=",
"False",
",",
"eps",
"=",
"2e-5",
",",
"momentum",
"=",
"bn_mom",
",",
"name",
"=",
"'bn0'",
")",
"body",
"=",
"mx",
".",
"sym",
".",
"Activation",
"(",
"data",
"=",
"body",
",",
"act_type",
"=",
"'relu'",
",",
"name",
"=",
"'relu0'",
")",
"body",
"=",
"mx",
".",
"sym",
".",
"Pooling",
"(",
"data",
"=",
"body",
",",
"kernel",
"=",
"(",
"3",
",",
"3",
")",
",",
"stride",
"=",
"(",
"2",
",",
"2",
")",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"pool_type",
"=",
"'max'",
")",
"for",
"i",
"in",
"range",
"(",
"num_stages",
")",
":",
"body",
"=",
"residual_unit",
"(",
"body",
",",
"filter_list",
"[",
"i",
"+",
"1",
"]",
",",
"(",
"1",
"if",
"i",
"==",
"0",
"else",
"2",
",",
"1",
"if",
"i",
"==",
"0",
"else",
"2",
")",
",",
"False",
",",
"name",
"=",
"'stage%d_unit%d'",
"%",
"(",
"i",
"+",
"1",
",",
"1",
")",
",",
"bottle_neck",
"=",
"bottle_neck",
",",
"num_group",
"=",
"num_group",
",",
"bn_mom",
"=",
"bn_mom",
",",
"workspace",
"=",
"workspace",
",",
"memonger",
"=",
"memonger",
")",
"for",
"j",
"in",
"range",
"(",
"units",
"[",
"i",
"]",
"-",
"1",
")",
":",
"body",
"=",
"residual_unit",
"(",
"body",
",",
"filter_list",
"[",
"i",
"+",
"1",
"]",
",",
"(",
"1",
",",
"1",
")",
",",
"True",
",",
"name",
"=",
"'stage%d_unit%d'",
"%",
"(",
"i",
"+",
"1",
",",
"j",
"+",
"2",
")",
",",
"bottle_neck",
"=",
"bottle_neck",
",",
"num_group",
"=",
"num_group",
",",
"bn_mom",
"=",
"bn_mom",
",",
"workspace",
"=",
"workspace",
",",
"memonger",
"=",
"memonger",
")",
"pool1",
"=",
"mx",
".",
"sym",
".",
"Pooling",
"(",
"data",
"=",
"body",
",",
"global_pool",
"=",
"True",
",",
"kernel",
"=",
"(",
"7",
",",
"7",
")",
",",
"pool_type",
"=",
"'avg'",
",",
"name",
"=",
"'pool1'",
")",
"flat",
"=",
"mx",
".",
"sym",
".",
"Flatten",
"(",
"data",
"=",
"pool1",
")",
"fc1",
"=",
"mx",
".",
"sym",
".",
"FullyConnected",
"(",
"data",
"=",
"flat",
",",
"num_hidden",
"=",
"num_classes",
",",
"name",
"=",
"'fc1'",
")",
"if",
"dtype",
"==",
"'float16'",
":",
"fc1",
"=",
"mx",
".",
"sym",
".",
"Cast",
"(",
"data",
"=",
"fc1",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"return",
"mx",
".",
"sym",
".",
"SoftmaxOutput",
"(",
"data",
"=",
"fc1",
",",
"name",
"=",
"'softmax'",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/image-classification/symbols/resnext.py#L101-L155 |
|
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBVariablesOptions.SetIncludeRecognizedArguments | (self, arg2) | return _lldb.SBVariablesOptions_SetIncludeRecognizedArguments(self, arg2) | SetIncludeRecognizedArguments(SBVariablesOptions self, bool arg2) | SetIncludeRecognizedArguments(SBVariablesOptions self, bool arg2) | [
"SetIncludeRecognizedArguments",
"(",
"SBVariablesOptions",
"self",
"bool",
"arg2",
")"
] | def SetIncludeRecognizedArguments(self, arg2):
"""SetIncludeRecognizedArguments(SBVariablesOptions self, bool arg2)"""
return _lldb.SBVariablesOptions_SetIncludeRecognizedArguments(self, arg2) | [
"def",
"SetIncludeRecognizedArguments",
"(",
"self",
",",
"arg2",
")",
":",
"return",
"_lldb",
".",
"SBVariablesOptions_SetIncludeRecognizedArguments",
"(",
"self",
",",
"arg2",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15063-L15065 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/network/cache.py | python | suppressed_cache_errors | () | If we can't access the cache then we can just skip caching and process
requests as if caching wasn't enabled. | If we can't access the cache then we can just skip caching and process | [
"If",
"we",
"can",
"t",
"access",
"the",
"cache",
"then",
"we",
"can",
"just",
"skip",
"caching",
"and",
"process"
] | def suppressed_cache_errors():
# type: () -> Iterator[None]
"""If we can't access the cache then we can just skip caching and process
requests as if caching wasn't enabled.
"""
try:
yield
except OSError:
pass | [
"def",
"suppressed_cache_errors",
"(",
")",
":",
"# type: () -> Iterator[None]",
"try",
":",
"yield",
"except",
"OSError",
":",
"pass"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/network/cache.py#L49-L65 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | PageSetupDialogData.GetEnablePrinter | (*args, **kwargs) | return _windows_.PageSetupDialogData_GetEnablePrinter(*args, **kwargs) | GetEnablePrinter(self) -> bool | GetEnablePrinter(self) -> bool | [
"GetEnablePrinter",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetEnablePrinter(*args, **kwargs):
"""GetEnablePrinter(self) -> bool"""
return _windows_.PageSetupDialogData_GetEnablePrinter(*args, **kwargs) | [
"def",
"GetEnablePrinter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_GetEnablePrinter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L4902-L4904 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py | python | WichmannHill.getstate | (self) | return self.VERSION, self._seed, self.gauss_next | Return internal state; can be passed to setstate() later. | Return internal state; can be passed to setstate() later. | [
"Return",
"internal",
"state",
";",
"can",
"be",
"passed",
"to",
"setstate",
"()",
"later",
"."
] | def getstate(self):
"""Return internal state; can be passed to setstate() later."""
return self.VERSION, self._seed, self.gauss_next | [
"def",
"getstate",
"(",
"self",
")",
":",
"return",
"self",
".",
"VERSION",
",",
"self",
".",
"_seed",
",",
"self",
".",
"gauss_next"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py#L715-L717 |
|
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppocr/data/imaug/east_process.py | python | EASTProcessTrain.check_and_validate_polys | (self, polys, tags, img_height, img_width) | return np.array(validated_polys), np.array(validated_tags) | check so that the text poly is in the same direction,
and also filter some invalid polygons
:param polys:
:param tags:
:return: | check so that the text poly is in the same direction,
and also filter some invalid polygons
:param polys:
:param tags:
:return: | [
"check",
"so",
"that",
"the",
"text",
"poly",
"is",
"in",
"the",
"same",
"direction",
"and",
"also",
"filter",
"some",
"invalid",
"polygons",
":",
"param",
"polys",
":",
":",
"param",
"tags",
":",
":",
"return",
":"
] | def check_and_validate_polys(self, polys, tags, img_height, img_width):
"""
check so that the text poly is in the same direction,
and also filter some invalid polygons
:param polys:
:param tags:
:return:
"""
h, w = img_height, img_width
if polys.shape[0] == 0:
return polys
polys[:, :, 0] = np.clip(polys[:, :, 0], 0, w - 1)
polys[:, :, 1] = np.clip(polys[:, :, 1], 0, h - 1)
validated_polys = []
validated_tags = []
for poly, tag in zip(polys, tags):
p_area = self.polygon_area(poly)
#invalid poly
if abs(p_area) < 1:
continue
if p_area > 0:
#'poly in wrong direction'
if not tag:
tag = True #reversed cases should be ignore
poly = poly[(0, 3, 2, 1), :]
validated_polys.append(poly)
validated_tags.append(tag)
return np.array(validated_polys), np.array(validated_tags) | [
"def",
"check_and_validate_polys",
"(",
"self",
",",
"polys",
",",
"tags",
",",
"img_height",
",",
"img_width",
")",
":",
"h",
",",
"w",
"=",
"img_height",
",",
"img_width",
"if",
"polys",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"polys",
"polys",
"[",
":",
",",
":",
",",
"0",
"]",
"=",
"np",
".",
"clip",
"(",
"polys",
"[",
":",
",",
":",
",",
"0",
"]",
",",
"0",
",",
"w",
"-",
"1",
")",
"polys",
"[",
":",
",",
":",
",",
"1",
"]",
"=",
"np",
".",
"clip",
"(",
"polys",
"[",
":",
",",
":",
",",
"1",
"]",
",",
"0",
",",
"h",
"-",
"1",
")",
"validated_polys",
"=",
"[",
"]",
"validated_tags",
"=",
"[",
"]",
"for",
"poly",
",",
"tag",
"in",
"zip",
"(",
"polys",
",",
"tags",
")",
":",
"p_area",
"=",
"self",
".",
"polygon_area",
"(",
"poly",
")",
"#invalid poly",
"if",
"abs",
"(",
"p_area",
")",
"<",
"1",
":",
"continue",
"if",
"p_area",
">",
"0",
":",
"#'poly in wrong direction'",
"if",
"not",
"tag",
":",
"tag",
"=",
"True",
"#reversed cases should be ignore",
"poly",
"=",
"poly",
"[",
"(",
"0",
",",
"3",
",",
"2",
",",
"1",
")",
",",
":",
"]",
"validated_polys",
".",
"append",
"(",
"poly",
")",
"validated_tags",
".",
"append",
"(",
"tag",
")",
"return",
"np",
".",
"array",
"(",
"validated_polys",
")",
",",
"np",
".",
"array",
"(",
"validated_tags",
")"
] | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/data/imaug/east_process.py#L107-L135 |
|
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_common.py | python | unicode2utf8 | (string: Optional[str]) | Some Proton APIs expect a null terminated string. Convert python text
types to UTF8 to avoid zero bytes introduced by other multi-byte encodings.
This method will throw if the string cannot be converted. | Some Proton APIs expect a null terminated string. Convert python text
types to UTF8 to avoid zero bytes introduced by other multi-byte encodings.
This method will throw if the string cannot be converted. | [
"Some",
"Proton",
"APIs",
"expect",
"a",
"null",
"terminated",
"string",
".",
"Convert",
"python",
"text",
"types",
"to",
"UTF8",
"to",
"avoid",
"zero",
"bytes",
"introduced",
"by",
"other",
"multi",
"-",
"byte",
"encodings",
".",
"This",
"method",
"will",
"throw",
"if",
"the",
"string",
"cannot",
"be",
"converted",
"."
] | def unicode2utf8(string: Optional[str]) -> Optional[str]:
"""Some Proton APIs expect a null terminated string. Convert python text
types to UTF8 to avoid zero bytes introduced by other multi-byte encodings.
This method will throw if the string cannot be converted.
"""
if string is None:
return None
elif isinstance(string, str):
# The swig binding converts py3 str -> utf8 char* and back automatically
return string
# Anything else illegal - specifically python3 bytes
raise TypeError("Unrecognized string type: %r (%s)" % (string, type(string))) | [
"def",
"unicode2utf8",
"(",
"string",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"string",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"# The swig binding converts py3 str -> utf8 char* and back automatically",
"return",
"string",
"# Anything else illegal - specifically python3 bytes",
"raise",
"TypeError",
"(",
"\"Unrecognized string type: %r (%s)\"",
"%",
"(",
"string",
",",
"type",
"(",
"string",
")",
")",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_common.py#L48-L59 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/mailbox.py | python | MaildirMessage.set_flags | (self, flags) | Set the given flags and unset all others. | Set the given flags and unset all others. | [
"Set",
"the",
"given",
"flags",
"and",
"unset",
"all",
"others",
"."
] | def set_flags(self, flags):
"""Set the given flags and unset all others."""
self._info = '2,' + ''.join(sorted(flags)) | [
"def",
"set_flags",
"(",
"self",
",",
"flags",
")",
":",
"self",
".",
"_info",
"=",
"'2,'",
"+",
"''",
".",
"join",
"(",
"sorted",
"(",
"flags",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mailbox.py#L1553-L1555 |
||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | IdentifyDriver | (*args) | return _gdal.IdentifyDriver(*args) | r"""IdentifyDriver(char const * utf8_path, char ** papszSiblings=None) -> Driver | r"""IdentifyDriver(char const * utf8_path, char ** papszSiblings=None) -> Driver | [
"r",
"IdentifyDriver",
"(",
"char",
"const",
"*",
"utf8_path",
"char",
"**",
"papszSiblings",
"=",
"None",
")",
"-",
">",
"Driver"
] | def IdentifyDriver(*args):
r"""IdentifyDriver(char const * utf8_path, char ** papszSiblings=None) -> Driver"""
return _gdal.IdentifyDriver(*args) | [
"def",
"IdentifyDriver",
"(",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"IdentifyDriver",
"(",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L4141-L4143 |
|
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | utils/vim-lldb/python-vim-lldb/lldb_controller.py | python | LLDBController.doAttach | (self, process_name) | Handle process attach. | Handle process attach. | [
"Handle",
"process",
"attach",
"."
] | def doAttach(self, process_name):
""" Handle process attach. """
error = lldb.SBError()
self.processListener = lldb.SBListener("process_event_listener")
self.target = self.dbg.CreateTarget('')
self.process = self.target.AttachToProcessWithName(
self.processListener, process_name, False, error)
if not error.Success():
sys.stderr.write("Error during attach: " + str(error))
return
self.ui.activate()
self.pid = self.process.GetProcessID()
print("Attached to %s (pid=%d)" % (process_name, self.pid)) | [
"def",
"doAttach",
"(",
"self",
",",
"process_name",
")",
":",
"error",
"=",
"lldb",
".",
"SBError",
"(",
")",
"self",
".",
"processListener",
"=",
"lldb",
".",
"SBListener",
"(",
"\"process_event_listener\"",
")",
"self",
".",
"target",
"=",
"self",
".",
"dbg",
".",
"CreateTarget",
"(",
"''",
")",
"self",
".",
"process",
"=",
"self",
".",
"target",
".",
"AttachToProcessWithName",
"(",
"self",
".",
"processListener",
",",
"process_name",
",",
"False",
",",
"error",
")",
"if",
"not",
"error",
".",
"Success",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Error during attach: \"",
"+",
"str",
"(",
"error",
")",
")",
"return",
"self",
".",
"ui",
".",
"activate",
"(",
")",
"self",
".",
"pid",
"=",
"self",
".",
"process",
".",
"GetProcessID",
"(",
")",
"print",
"(",
"\"Attached to %s (pid=%d)\"",
"%",
"(",
"process_name",
",",
"self",
".",
"pid",
")",
")"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/vim-lldb/python-vim-lldb/lldb_controller.py#L154-L169 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/dom/expatbuilder.py | python | ExpatBuilder.parseString | (self, string) | return doc | Parse a document from a string, returning the document node. | Parse a document from a string, returning the document node. | [
"Parse",
"a",
"document",
"from",
"a",
"string",
"returning",
"the",
"document",
"node",
"."
] | def parseString(self, string):
"""Parse a document from a string, returning the document node."""
parser = self.getParser()
try:
parser.Parse(string, True)
self._setup_subset(string)
except ParseEscape:
pass
doc = self.document
self.reset()
self._parser = None
return doc | [
"def",
"parseString",
"(",
"self",
",",
"string",
")",
":",
"parser",
"=",
"self",
".",
"getParser",
"(",
")",
"try",
":",
"parser",
".",
"Parse",
"(",
"string",
",",
"True",
")",
"self",
".",
"_setup_subset",
"(",
"string",
")",
"except",
"ParseEscape",
":",
"pass",
"doc",
"=",
"self",
".",
"document",
"self",
".",
"reset",
"(",
")",
"self",
".",
"_parser",
"=",
"None",
"return",
"doc"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/dom/expatbuilder.py#L219-L230 |
|
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/random_ops.py | python | parameterized_truncated_normal | (shape,
means=0.0,
stddevs=1.0,
minvals=-2.0,
maxvals=2.0,
dtype=dtypes.float32,
seed=None,
name=None) | Outputs random values from a truncated normal distribution.
The generated values follow a normal distribution with specified mean and
standard deviation, except that values whose magnitude is more than 2 standard
deviations from the mean are dropped and re-picked.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
means: A 0-D Tensor or Python value of type `dtype`. The mean of the
truncated normal distribution.
stddevs: A 0-D Tensor or Python value of type `dtype`. The standard
deviation of the truncated normal distribution.
minvals: A 0-D Tensor or Python value of type `dtype`. The minimum value of
the truncated normal distribution.
maxvals: A 0-D Tensor or Python value of type `dtype`. The maximum value of
the truncated normal distribution.
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
name: A name for the operation (optional).
Returns:
A tensor of the specified shape filled with random truncated normal values. | Outputs random values from a truncated normal distribution. | [
"Outputs",
"random",
"values",
"from",
"a",
"truncated",
"normal",
"distribution",
"."
] | def parameterized_truncated_normal(shape,
means=0.0,
stddevs=1.0,
minvals=-2.0,
maxvals=2.0,
dtype=dtypes.float32,
seed=None,
name=None):
"""Outputs random values from a truncated normal distribution.
The generated values follow a normal distribution with specified mean and
standard deviation, except that values whose magnitude is more than 2 standard
deviations from the mean are dropped and re-picked.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
means: A 0-D Tensor or Python value of type `dtype`. The mean of the
truncated normal distribution.
stddevs: A 0-D Tensor or Python value of type `dtype`. The standard
deviation of the truncated normal distribution.
minvals: A 0-D Tensor or Python value of type `dtype`. The minimum value of
the truncated normal distribution.
maxvals: A 0-D Tensor or Python value of type `dtype`. The maximum value of
the truncated normal distribution.
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
name: A name for the operation (optional).
Returns:
A tensor of the specified shape filled with random truncated normal values.
"""
with ops.op_scope([shape, means, stddevs, minvals, maxvals], name,
"parameterized_truncated_normal") as name:
shape_tensor = _ShapeTensor(shape)
means_tensor = ops.convert_to_tensor(means, dtype=dtype, name="means")
stddevs_tensor = ops.convert_to_tensor(stddevs, dtype=dtype, name="stddevs")
minvals_tensor = ops.convert_to_tensor(minvals, dtype=dtype, name="minvals")
maxvals_tensor = ops.convert_to_tensor(maxvals, dtype=dtype, name="maxvals")
seed1, seed2 = random_seed.get_seed(seed)
rnd = gen_random_ops._parameterized_truncated_normal(shape_tensor,
means_tensor,
stddevs_tensor,
minvals_tensor,
maxvals_tensor,
seed=seed1,
seed2=seed2)
return rnd | [
"def",
"parameterized_truncated_normal",
"(",
"shape",
",",
"means",
"=",
"0.0",
",",
"stddevs",
"=",
"1.0",
",",
"minvals",
"=",
"-",
"2.0",
",",
"maxvals",
"=",
"2.0",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"shape",
",",
"means",
",",
"stddevs",
",",
"minvals",
",",
"maxvals",
"]",
",",
"name",
",",
"\"parameterized_truncated_normal\"",
")",
"as",
"name",
":",
"shape_tensor",
"=",
"_ShapeTensor",
"(",
"shape",
")",
"means_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"means",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"\"means\"",
")",
"stddevs_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"stddevs",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"\"stddevs\"",
")",
"minvals_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"minvals",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"\"minvals\"",
")",
"maxvals_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"maxvals",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"\"maxvals\"",
")",
"seed1",
",",
"seed2",
"=",
"random_seed",
".",
"get_seed",
"(",
"seed",
")",
"rnd",
"=",
"gen_random_ops",
".",
"_parameterized_truncated_normal",
"(",
"shape_tensor",
",",
"means_tensor",
",",
"stddevs_tensor",
",",
"minvals_tensor",
",",
"maxvals_tensor",
",",
"seed",
"=",
"seed1",
",",
"seed2",
"=",
"seed2",
")",
"return",
"rnd"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/random_ops.py#L90-L139 |
||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_presenter.py | python | BackgroundCorrectionsPresenter._update_start_and_end_x_in_view_and_model | (self, run: str, group: str, start_x: float, end_x: float) | Updates the start and end x in the view and model using the provided values. | Updates the start and end x in the view and model using the provided values. | [
"Updates",
"the",
"start",
"and",
"end",
"x",
"in",
"the",
"view",
"and",
"model",
"using",
"the",
"provided",
"values",
"."
] | def _update_start_and_end_x_in_view_and_model(self, run: str, group: str, start_x: float, end_x: float) -> None:
"""Updates the start and end x in the view and model using the provided values."""
if self.view.is_run_group_displayed(run, group):
self.view.set_start_x(run, group, start_x)
self.view.set_end_x(run, group, end_x)
self.model.set_start_x(run, group, start_x)
self.model.set_end_x(run, group, end_x) | [
"def",
"_update_start_and_end_x_in_view_and_model",
"(",
"self",
",",
"run",
":",
"str",
",",
"group",
":",
"str",
",",
"start_x",
":",
"float",
",",
"end_x",
":",
"float",
")",
"->",
"None",
":",
"if",
"self",
".",
"view",
".",
"is_run_group_displayed",
"(",
"run",
",",
"group",
")",
":",
"self",
".",
"view",
".",
"set_start_x",
"(",
"run",
",",
"group",
",",
"start_x",
")",
"self",
".",
"view",
".",
"set_end_x",
"(",
"run",
",",
"group",
",",
"end_x",
")",
"self",
".",
"model",
".",
"set_start_x",
"(",
"run",
",",
"group",
",",
"start_x",
")",
"self",
".",
"model",
".",
"set_end_x",
"(",
"run",
",",
"group",
",",
"end_x",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_presenter.py#L174-L180 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py | python | BufferedReader.__init__ | (self, raw, buffer_size=DEFAULT_BUFFER_SIZE) | Create a new buffered reader using the given readable raw IO object. | Create a new buffered reader using the given readable raw IO object. | [
"Create",
"a",
"new",
"buffered",
"reader",
"using",
"the",
"given",
"readable",
"raw",
"IO",
"object",
"."
] | def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
"""Create a new buffered reader using the given readable raw IO object.
"""
if not raw.readable():
raise OSError('"raw" argument must be readable.')
_BufferedIOMixin.__init__(self, raw)
if buffer_size <= 0:
raise ValueError("invalid buffer size")
self.buffer_size = buffer_size
self._reset_read_buf()
self._read_lock = Lock() | [
"def",
"__init__",
"(",
"self",
",",
"raw",
",",
"buffer_size",
"=",
"DEFAULT_BUFFER_SIZE",
")",
":",
"if",
"not",
"raw",
".",
"readable",
"(",
")",
":",
"raise",
"OSError",
"(",
"'\"raw\" argument must be readable.'",
")",
"_BufferedIOMixin",
".",
"__init__",
"(",
"self",
",",
"raw",
")",
"if",
"buffer_size",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"invalid buffer size\"",
")",
"self",
".",
"buffer_size",
"=",
"buffer_size",
"self",
".",
"_reset_read_buf",
"(",
")",
"self",
".",
"_read_lock",
"=",
"Lock",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py#L992-L1003 |
||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py | python | gpaths | (paths, local_path='', include_non_existing=True) | return _fix_paths(paths, local_path, include_non_existing) | Apply glob to paths and prepend local_path if needed. | Apply glob to paths and prepend local_path if needed. | [
"Apply",
"glob",
"to",
"paths",
"and",
"prepend",
"local_path",
"if",
"needed",
"."
] | def gpaths(paths, local_path='', include_non_existing=True):
"""Apply glob to paths and prepend local_path if needed.
"""
if is_string(paths):
paths = (paths,)
return _fix_paths(paths, local_path, include_non_existing) | [
"def",
"gpaths",
"(",
"paths",
",",
"local_path",
"=",
"''",
",",
"include_non_existing",
"=",
"True",
")",
":",
"if",
"is_string",
"(",
"paths",
")",
":",
"paths",
"=",
"(",
"paths",
",",
")",
"return",
"_fix_paths",
"(",
"paths",
",",
"local_path",
",",
"include_non_existing",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py#L244-L249 |
|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailbox.py | python | mbox.__init__ | (self, path, factory=None, create=True) | Initialize an mbox mailbox. | Initialize an mbox mailbox. | [
"Initialize",
"an",
"mbox",
"mailbox",
"."
] | def __init__(self, path, factory=None, create=True):
"""Initialize an mbox mailbox."""
self._message_factory = mboxMessage
_mboxMMDF.__init__(self, path, factory, create) | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"factory",
"=",
"None",
",",
"create",
"=",
"True",
")",
":",
"self",
".",
"_message_factory",
"=",
"mboxMessage",
"_mboxMMDF",
".",
"__init__",
"(",
"self",
",",
"path",
",",
"factory",
",",
"create",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailbox.py#L819-L822 |
||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | PhysicsTools/HeppyCore/python/utils/castorBaseDir.py | python | getUserAndArea | (user) | return user, area | Factor out the magic user hack for use in other classes | Factor out the magic user hack for use in other classes | [
"Factor",
"out",
"the",
"magic",
"user",
"hack",
"for",
"use",
"in",
"other",
"classes"
] | def getUserAndArea(user):
"""Factor out the magic user hack for use in other classes"""
area = 'user'
tokens = user.split('_')
if tokens and len(tokens) > 1:
user = tokens[0]
area = tokens[1]
return user, area | [
"def",
"getUserAndArea",
"(",
"user",
")",
":",
"area",
"=",
"'user'",
"tokens",
"=",
"user",
".",
"split",
"(",
"'_'",
")",
"if",
"tokens",
"and",
"len",
"(",
"tokens",
")",
">",
"1",
":",
"user",
"=",
"tokens",
"[",
"0",
"]",
"area",
"=",
"tokens",
"[",
"1",
"]",
"return",
"user",
",",
"area"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/HeppyCore/python/utils/castorBaseDir.py#L7-L16 |
|
D-X-Y/caffe-faster-rcnn | eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb | scripts/cpp_lint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [ or <, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"or",
"<",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
startchar = line[pos]
if startchar not in '({[<':
return (line, clean_lines.NumLines(), -1)
if startchar == '(': endchar = ')'
if startchar == '[': endchar = ']'
if startchar == '{': endchar = '}'
if startchar == '<': endchar = '>'
# Check first line
(end_pos, num_open) = FindEndOfExpressionInLine(
line, pos, 0, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, num_open) = FindEndOfExpressionInLine(
line, 0, num_open, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find endchar before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"startchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"startchar",
"not",
"in",
"'({[<'",
":",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")",
"if",
"startchar",
"==",
"'('",
":",
"endchar",
"=",
"')'",
"if",
"startchar",
"==",
"'['",
":",
"endchar",
"=",
"']'",
"if",
"startchar",
"==",
"'{'",
":",
"endchar",
"=",
"'}'",
"if",
"startchar",
"==",
"'<'",
":",
"endchar",
"=",
"'>'",
"# Check first line",
"(",
"end_pos",
",",
"num_open",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"pos",
",",
"0",
",",
"startchar",
",",
"endchar",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Continue scanning forward",
"while",
"linenum",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
"-",
"1",
":",
"linenum",
"+=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"(",
"end_pos",
",",
"num_open",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"0",
",",
"num_open",
",",
"startchar",
",",
"endchar",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Did not find endchar before end of file, give up",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")"
] | https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/scripts/cpp_lint.py#L1258-L1301 |
|
OAID/Caffe-HRT | aae71e498ab842c6f92bcc23fc668423615a4d65 | scripts/cpp_lint.py | python | Search | (pattern, s) | return _regexp_compile_cache[pattern].search(s) | Searches the string for the pattern, caching the compiled regexp. | Searches the string for the pattern, caching the compiled regexp. | [
"Searches",
"the",
"string",
"for",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) | [
"def",
"Search",
"(",
"pattern",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pattern",
"]",
".",
"search",
"(",
"s",
")"
] | https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L543-L547 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | PreSplitterWindow | (*args, **kwargs) | return val | PreSplitterWindow() -> SplitterWindow
Precreate a SplitterWindow for 2-phase creation. | PreSplitterWindow() -> SplitterWindow | [
"PreSplitterWindow",
"()",
"-",
">",
"SplitterWindow"
] | def PreSplitterWindow(*args, **kwargs):
"""
PreSplitterWindow() -> SplitterWindow
Precreate a SplitterWindow for 2-phase creation.
"""
val = _windows_.new_PreSplitterWindow(*args, **kwargs)
return val | [
"def",
"PreSplitterWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_windows_",
".",
"new_PreSplitterWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1672-L1679 |
|
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | libs/lv2/lv2specgen/lv2specgen.py | python | rdfsPropertyInfo | (term, m) | return doc | Generate HTML for properties: Domain, range | Generate HTML for properties: Domain, range | [
"Generate",
"HTML",
"for",
"properties",
":",
"Domain",
"range"
] | def rdfsPropertyInfo(term, m):
"""Generate HTML for properties: Domain, range"""
global classranges
global classdomains
doc = ""
range = ""
domain = ""
# Find subPropertyOf information
rlist = ''
first = True
for st in findStatements(m, term, rdfs.subPropertyOf, None):
k = getTermLink(getObject(st), term, rdfs.subPropertyOf)
rlist += getProperty(k, first)
first = False
if rlist != '':
doc += '<tr><th>Sub-property of</th>' + rlist
# Domain stuff
domains = findStatements(m, term, rdfs.domain, None)
domainsdoc = ""
first = True
for d in domains:
union = findOne(m, getObject(d), owl.unionOf, None)
if union:
uris = parseCollection(m, getObject(union))
for uri in uris:
domainsdoc += getProperty(getTermLink(uri, term, rdfs.domain), first)
add(classdomains, uri, term)
else:
if not isBlank(getObject(d)):
domainsdoc += getProperty(getTermLink(getObject(d), term, rdfs.domain), first)
first = False
if (len(domainsdoc) > 0):
doc += "<tr><th>Domain</th>%s" % domainsdoc
# Range stuff
ranges = findStatements(m, term, rdfs.range, None)
rangesdoc = ""
first = True
for r in ranges:
union = findOne(m, getObject(r), owl.unionOf, None)
if union:
uris = parseCollection(m, getObject(union))
for uri in uris:
rangesdoc += getProperty(getTermLink(uri, term, rdfs.range), first)
add(classranges, uri, term)
first = False
else:
if not isBlank(getObject(r)):
rangesdoc += getProperty(getTermLink(getObject(r), term, rdfs.range), first)
first = False
if (len(rangesdoc) > 0):
doc += "<tr><th>Range</th>%s" % rangesdoc
return doc | [
"def",
"rdfsPropertyInfo",
"(",
"term",
",",
"m",
")",
":",
"global",
"classranges",
"global",
"classdomains",
"doc",
"=",
"\"\"",
"range",
"=",
"\"\"",
"domain",
"=",
"\"\"",
"# Find subPropertyOf information",
"rlist",
"=",
"''",
"first",
"=",
"True",
"for",
"st",
"in",
"findStatements",
"(",
"m",
",",
"term",
",",
"rdfs",
".",
"subPropertyOf",
",",
"None",
")",
":",
"k",
"=",
"getTermLink",
"(",
"getObject",
"(",
"st",
")",
",",
"term",
",",
"rdfs",
".",
"subPropertyOf",
")",
"rlist",
"+=",
"getProperty",
"(",
"k",
",",
"first",
")",
"first",
"=",
"False",
"if",
"rlist",
"!=",
"''",
":",
"doc",
"+=",
"'<tr><th>Sub-property of</th>'",
"+",
"rlist",
"# Domain stuff",
"domains",
"=",
"findStatements",
"(",
"m",
",",
"term",
",",
"rdfs",
".",
"domain",
",",
"None",
")",
"domainsdoc",
"=",
"\"\"",
"first",
"=",
"True",
"for",
"d",
"in",
"domains",
":",
"union",
"=",
"findOne",
"(",
"m",
",",
"getObject",
"(",
"d",
")",
",",
"owl",
".",
"unionOf",
",",
"None",
")",
"if",
"union",
":",
"uris",
"=",
"parseCollection",
"(",
"m",
",",
"getObject",
"(",
"union",
")",
")",
"for",
"uri",
"in",
"uris",
":",
"domainsdoc",
"+=",
"getProperty",
"(",
"getTermLink",
"(",
"uri",
",",
"term",
",",
"rdfs",
".",
"domain",
")",
",",
"first",
")",
"add",
"(",
"classdomains",
",",
"uri",
",",
"term",
")",
"else",
":",
"if",
"not",
"isBlank",
"(",
"getObject",
"(",
"d",
")",
")",
":",
"domainsdoc",
"+=",
"getProperty",
"(",
"getTermLink",
"(",
"getObject",
"(",
"d",
")",
",",
"term",
",",
"rdfs",
".",
"domain",
")",
",",
"first",
")",
"first",
"=",
"False",
"if",
"(",
"len",
"(",
"domainsdoc",
")",
">",
"0",
")",
":",
"doc",
"+=",
"\"<tr><th>Domain</th>%s\"",
"%",
"domainsdoc",
"# Range stuff",
"ranges",
"=",
"findStatements",
"(",
"m",
",",
"term",
",",
"rdfs",
".",
"range",
",",
"None",
")",
"rangesdoc",
"=",
"\"\"",
"first",
"=",
"True",
"for",
"r",
"in",
"ranges",
":",
"union",
"=",
"findOne",
"(",
"m",
",",
"getObject",
"(",
"r",
")",
",",
"owl",
".",
"unionOf",
",",
"None",
")",
"if",
"union",
":",
"uris",
"=",
"parseCollection",
"(",
"m",
",",
"getObject",
"(",
"union",
")",
")",
"for",
"uri",
"in",
"uris",
":",
"rangesdoc",
"+=",
"getProperty",
"(",
"getTermLink",
"(",
"uri",
",",
"term",
",",
"rdfs",
".",
"range",
")",
",",
"first",
")",
"add",
"(",
"classranges",
",",
"uri",
",",
"term",
")",
"first",
"=",
"False",
"else",
":",
"if",
"not",
"isBlank",
"(",
"getObject",
"(",
"r",
")",
")",
":",
"rangesdoc",
"+=",
"getProperty",
"(",
"getTermLink",
"(",
"getObject",
"(",
"r",
")",
",",
"term",
",",
"rdfs",
".",
"range",
")",
",",
"first",
")",
"first",
"=",
"False",
"if",
"(",
"len",
"(",
"rangesdoc",
")",
">",
"0",
")",
":",
"doc",
"+=",
"\"<tr><th>Range</th>%s\"",
"%",
"rangesdoc",
"return",
"doc"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/libs/lv2/lv2specgen/lv2specgen.py#L377-L432 |
|
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | python/pyarrow/parquet.py | python | ParquetDatasetPiece.open | (self) | return reader | Return instance of ParquetFile. | Return instance of ParquetFile. | [
"Return",
"instance",
"of",
"ParquetFile",
"."
] | def open(self):
"""
Return instance of ParquetFile.
"""
reader = self.open_file_func(self.path)
if not isinstance(reader, ParquetFile):
reader = ParquetFile(reader, **self.file_options)
return reader | [
"def",
"open",
"(",
"self",
")",
":",
"reader",
"=",
"self",
".",
"open_file_func",
"(",
"self",
".",
"path",
")",
"if",
"not",
"isinstance",
"(",
"reader",
",",
"ParquetFile",
")",
":",
"reader",
"=",
"ParquetFile",
"(",
"reader",
",",
"*",
"*",
"self",
".",
"file_options",
")",
"return",
"reader"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/parquet.py#L867-L874 |
|
kristjankorjus/Replicating-DeepMind | 68539394e792b34a4d6b430a2eb73b8b8f91d8db | sandbox/chessboard.py | python | make_chessboard | (n) | return make_chessboard_any_size(84, n) | Create a 84x84 chessboard with small square size n pixels. | Create a 84x84 chessboard with small square size n pixels. | [
"Create",
"a",
"84x84",
"chessboard",
"with",
"small",
"square",
"size",
"n",
"pixels",
"."
] | def make_chessboard(n):
""" Create a 84x84 chessboard with small square size n pixels.
"""
return make_chessboard_any_size(84, n) | [
"def",
"make_chessboard",
"(",
"n",
")",
":",
"return",
"make_chessboard_any_size",
"(",
"84",
",",
"n",
")"
] | https://github.com/kristjankorjus/Replicating-DeepMind/blob/68539394e792b34a4d6b430a2eb73b8b8f91d8db/sandbox/chessboard.py#L31-L34 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/batch.py | python | Batch.to_dict | (self) | return batch_dict | Convert the Batch object into the format required for Layer1. | Convert the Batch object into the format required for Layer1. | [
"Convert",
"the",
"Batch",
"object",
"into",
"the",
"format",
"required",
"for",
"Layer1",
"."
] | def to_dict(self):
"""
Convert the Batch object into the format required for Layer1.
"""
batch_dict = {}
key_list = []
for key in self.keys:
if isinstance(key, tuple):
hash_key, range_key = key
else:
hash_key = key
range_key = None
k = self.table.layer2.build_key_from_values(self.table.schema,
hash_key, range_key)
key_list.append(k)
batch_dict['Keys'] = key_list
if self.attributes_to_get:
batch_dict['AttributesToGet'] = self.attributes_to_get
if self.consistent_read:
batch_dict['ConsistentRead'] = True
else:
batch_dict['ConsistentRead'] = False
return batch_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"batch_dict",
"=",
"{",
"}",
"key_list",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"keys",
":",
"if",
"isinstance",
"(",
"key",
",",
"tuple",
")",
":",
"hash_key",
",",
"range_key",
"=",
"key",
"else",
":",
"hash_key",
"=",
"key",
"range_key",
"=",
"None",
"k",
"=",
"self",
".",
"table",
".",
"layer2",
".",
"build_key_from_values",
"(",
"self",
".",
"table",
".",
"schema",
",",
"hash_key",
",",
"range_key",
")",
"key_list",
".",
"append",
"(",
"k",
")",
"batch_dict",
"[",
"'Keys'",
"]",
"=",
"key_list",
"if",
"self",
".",
"attributes_to_get",
":",
"batch_dict",
"[",
"'AttributesToGet'",
"]",
"=",
"self",
".",
"attributes_to_get",
"if",
"self",
".",
"consistent_read",
":",
"batch_dict",
"[",
"'ConsistentRead'",
"]",
"=",
"True",
"else",
":",
"batch_dict",
"[",
"'ConsistentRead'",
"]",
"=",
"False",
"return",
"batch_dict"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/batch.py#L58-L80 |
|
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/processing/gui/wrappers.py | python | ExpressionWidgetWrapper.__init__ | (self, param, dialog, row=0, col=0, **kwargs) | .. deprecated:: 3.4
Do not use, will be removed in QGIS 4.0 | .. deprecated:: 3.4
Do not use, will be removed in QGIS 4.0 | [
"..",
"deprecated",
"::",
"3",
".",
"4",
"Do",
"not",
"use",
"will",
"be",
"removed",
"in",
"QGIS",
"4",
".",
"0"
] | def __init__(self, param, dialog, row=0, col=0, **kwargs):
"""
.. deprecated:: 3.4
Do not use, will be removed in QGIS 4.0
"""
from warnings import warn
warn("StringWidgetWrapper is deprecated and will be removed in QGIS 4.0", DeprecationWarning)
super().__init__(param, dialog, row, col, **kwargs)
self.context = dataobjects.createContext() | [
"def",
"__init__",
"(",
"self",
",",
"param",
",",
"dialog",
",",
"row",
"=",
"0",
",",
"col",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"StringWidgetWrapper is deprecated and will be removed in QGIS 4.0\"",
",",
"DeprecationWarning",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"param",
",",
"dialog",
",",
"row",
",",
"col",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"context",
"=",
"dataobjects",
".",
"createContext",
"(",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/processing/gui/wrappers.py#L1391-L1401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.