nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/fhir | d77f57706c1a168529b0b87ca7ccb1c0113e83c2 | py/setup.py | python | _parse_requirements | (path: str) | Parses a requirements.txt file into a list of strings. | Parses a requirements.txt file into a list of strings. | [
"Parses",
"a",
"requirements",
".",
"txt",
"file",
"into",
"a",
"list",
"of",
"strings",
"."
] | def _parse_requirements(path: str) -> List[str]:
"""Parses a requirements.txt file into a list of strings."""
with open(os.path.join(_HERE, path), 'r') as f:
return [
line.rstrip()
for line in f
if not (line.isspace() or line.startswith('#'))
] | [
"def",
"_parse_requirements",
"(",
"path",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"_HERE",
",",
"path",
")",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"[",
"line",
".",
"r... | https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/setup.py#L100-L107 | ||
opencv/opencv | 76aff8478883858f0e46746044348ebb16dc3c67 | samples/dnn/person_reid.py | python | normalize | (nparray, order=2, axis=0) | return nparray / (norm + np.finfo(np.float32).eps) | Normalize a N-D numpy array along the specified axis.
:param nparry: the array of vectors to be normalized
:param order: order of the norm
:param axis: the axis of x along which to compute the vector norms | Normalize a N-D numpy array along the specified axis.
:param nparry: the array of vectors to be normalized
:param order: order of the norm
:param axis: the axis of x along which to compute the vector norms | [
"Normalize",
"a",
"N",
"-",
"D",
"numpy",
"array",
"along",
"the",
"specified",
"axis",
".",
":",
"param",
"nparry",
":",
"the",
"array",
"of",
"vectors",
"to",
"be",
"normalized",
":",
"param",
"order",
":",
"order",
"of",
"the",
"norm",
":",
"param",... | def normalize(nparray, order=2, axis=0):
"""
Normalize a N-D numpy array along the specified axis.
:param nparry: the array of vectors to be normalized
:param order: order of the norm
:param axis: the axis of x along which to compute the vector norms
"""
norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True)
return nparray / (norm + np.finfo(np.float32).eps) | [
"def",
"normalize",
"(",
"nparray",
",",
"order",
"=",
"2",
",",
"axis",
"=",
"0",
")",
":",
"norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"nparray",
",",
"ord",
"=",
"order",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"True",
")",
"... | https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/samples/dnn/person_reid.py#L116-L124 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/flatnotebook.py | python | PageContainer.OnMouseEnterWindow | (self, event) | Handles the wx.EVT_ENTER_WINDOW event for L{PageContainer}. | Handles the wx.EVT_ENTER_WINDOW event for L{PageContainer}. | [
"Handles",
"the",
"wx",
".",
"EVT_ENTER_WINDOW",
"event",
"for",
"L",
"{",
"PageContainer",
"}",
"."
] | def OnMouseEnterWindow(self, event):
""" Handles the wx.EVT_ENTER_WINDOW event for L{PageContainer}. """
self._nLeftButtonStatus = FNB_BTN_NONE
self._nXButtonStatus = FNB_BTN_NONE
self._nRightButtonStatus = FNB_BTN_NONE
self._nLeftClickZone = FNB_BTN_NONE
self._nArrowDownButtonStatus = FNB_BTN_NONE
event.Skip() | [
"def",
"OnMouseEnterWindow",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_nLeftButtonStatus",
"=",
"FNB_BTN_NONE",
"self",
".",
"_nXButtonStatus",
"=",
"FNB_BTN_NONE",
"self",
".",
"_nRightButtonStatus",
"=",
"FNB_BTN_NONE",
"self",
".",
"_nLeftClickZone",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L4538-L4547 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/json/_json.py | python | JsonReader._get_object_parser | (self, json) | return obj | Parses a json document into a pandas object. | Parses a json document into a pandas object. | [
"Parses",
"a",
"json",
"document",
"into",
"a",
"pandas",
"object",
"."
] | def _get_object_parser(self, json):
"""
Parses a json document into a pandas object.
"""
typ = self.typ
dtype = self.dtype
kwargs = {
"orient": self.orient,
"dtype": self.dtype,
"convert_axes": self.convert_axes,
"convert_dates": self.convert_dates,
"keep_default_dates": self.keep_default_dates,
"numpy": self.numpy,
"precise_float": self.precise_float,
"date_unit": self.date_unit,
}
obj = None
if typ == "frame":
obj = FrameParser(json, **kwargs).parse()
if typ == "series" or obj is None:
if not isinstance(dtype, bool):
kwargs["dtype"] = dtype
obj = SeriesParser(json, **kwargs).parse()
return obj | [
"def",
"_get_object_parser",
"(",
"self",
",",
"json",
")",
":",
"typ",
"=",
"self",
".",
"typ",
"dtype",
"=",
"self",
".",
"dtype",
"kwargs",
"=",
"{",
"\"orient\"",
":",
"self",
".",
"orient",
",",
"\"dtype\"",
":",
"self",
".",
"dtype",
",",
"\"co... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/json/_json.py#L735-L760 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/mutex.py | python | mutex.testandset | (self) | Atomic test-and-set -- grab the lock if it is not set,
return True if it succeeded. | Atomic test-and-set -- grab the lock if it is not set,
return True if it succeeded. | [
"Atomic",
"test",
"-",
"and",
"-",
"set",
"--",
"grab",
"the",
"lock",
"if",
"it",
"is",
"not",
"set",
"return",
"True",
"if",
"it",
"succeeded",
"."
] | def testandset(self):
"""Atomic test-and-set -- grab the lock if it is not set,
return True if it succeeded."""
if not self.locked:
self.locked = 1
return True
else:
return False | [
"def",
"testandset",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"locked",
":",
"self",
".",
"locked",
"=",
"1",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mutex.py#L30-L37 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Text.tag_unbind | (self, tagName, sequence, funcid=None) | Unbind for all characters with TAGNAME for event SEQUENCE the
function identified with FUNCID. | Unbind for all characters with TAGNAME for event SEQUENCE the
function identified with FUNCID. | [
"Unbind",
"for",
"all",
"characters",
"with",
"TAGNAME",
"for",
"event",
"SEQUENCE",
"the",
"function",
"identified",
"with",
"FUNCID",
"."
] | def tag_unbind(self, tagName, sequence, funcid=None):
"""Unbind for all characters with TAGNAME for event SEQUENCE the
function identified with FUNCID."""
self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
if funcid:
self.deletecommand(funcid) | [
"def",
"tag_unbind",
"(",
"self",
",",
"tagName",
",",
"sequence",
",",
"funcid",
"=",
"None",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'tag'",
",",
"'bind'",
",",
"tagName",
",",
"sequence",
",",
"''",
")",
"if",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3105-L3110 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/jedi/jedi/api/classes.py | python | BaseDefinition.__init__ | (self, evaluator, name) | An instance of :class:`parso.reprsentation.Name` subclass. | An instance of :class:`parso.reprsentation.Name` subclass. | [
"An",
"instance",
"of",
":",
"class",
":",
"parso",
".",
"reprsentation",
".",
"Name",
"subclass",
"."
] | def __init__(self, evaluator, name):
self._evaluator = evaluator
self._name = name
"""
An instance of :class:`parso.reprsentation.Name` subclass.
"""
self.is_keyword = isinstance(self._name, KeywordName)
# generate a path to the definition
self._module = name.get_root_context()
if self.in_builtin_module():
self.module_path = None
else:
self.module_path = self._module.py__file__()
"""Shows the file path of a module. e.g. ``/usr/lib/python2.7/os.py``""" | [
"def",
"__init__",
"(",
"self",
",",
"evaluator",
",",
"name",
")",
":",
"self",
".",
"_evaluator",
"=",
"evaluator",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"is_keyword",
"=",
"isinstance",
"(",
"self",
".",
"_name",
",",
"KeywordName",
")",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/api/classes.py#L57-L71 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/memonger.py | python | _get_path | (pred_list, dist_list) | return list(reversed(ret)) | Get the path from nx.bellman_ford()'s output | Get the path from nx.bellman_ford()'s output | [
"Get",
"the",
"path",
"from",
"nx",
".",
"bellman_ford",
"()",
"s",
"output"
] | def _get_path(pred_list, dist_list):
''' Get the path from nx.bellman_ford()'s output '''
# distances are negative
assert all(dist_list[x] <= 0 for x in dist_list)
# node with longest distance to source is the target
target = min(dist_list, key=lambda x: dist_list[x])
ret = []
cur = target
while cur is not None:
ret.append(cur)
# Hack to get networkx 2.0 happy: it uses list in pred.
# TODO(tulloch): are there cases with multiple predecessors?
try:
cur = pred_list[cur][0] if pred_list[cur] else None
except TypeError:
cur = pred_list[cur]
return list(reversed(ret)) | [
"def",
"_get_path",
"(",
"pred_list",
",",
"dist_list",
")",
":",
"# distances are negative",
"assert",
"all",
"(",
"dist_list",
"[",
"x",
"]",
"<=",
"0",
"for",
"x",
"in",
"dist_list",
")",
"# node with longest distance to source is the target",
"target",
"=",
"m... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/memonger.py#L325-L345 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_gui/reduction/scripter.py | python | BaseScriptElement.to_xml | (self) | return "" | Return an XML representation of the data / state of the object | Return an XML representation of the data / state of the object | [
"Return",
"an",
"XML",
"representation",
"of",
"the",
"data",
"/",
"state",
"of",
"the",
"object"
] | def to_xml(self):
"""
Return an XML representation of the data / state of the object
"""
return "" | [
"def",
"to_xml",
"(",
"self",
")",
":",
"return",
"\"\""
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/scripter.py#L73-L77 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/api.py | python | close | () | Explicitly clears all contexts in the current thread, and destroys all
contexts if the current thread is the main thread. | Explicitly clears all contexts in the current thread, and destroys all
contexts if the current thread is the main thread. | [
"Explicitly",
"clears",
"all",
"contexts",
"in",
"the",
"current",
"thread",
"and",
"destroys",
"all",
"contexts",
"if",
"the",
"current",
"thread",
"is",
"the",
"main",
"thread",
"."
] | def close():
"""
Explicitly clears all contexts in the current thread, and destroys all
contexts if the current thread is the main thread.
"""
devices.reset() | [
"def",
"close",
"(",
")",
":",
"devices",
".",
"reset",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/api.py#L351-L356 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Task.py | python | compile_fun_noshell | (line) | return (funex(fun), dvars) | Create a compiled function to execute a process without the shell
WARNING: this method may disappear anytime, so use compile_fun instead | Create a compiled function to execute a process without the shell
WARNING: this method may disappear anytime, so use compile_fun instead | [
"Create",
"a",
"compiled",
"function",
"to",
"execute",
"a",
"process",
"without",
"the",
"shell",
"WARNING",
":",
"this",
"method",
"may",
"disappear",
"anytime",
"so",
"use",
"compile_fun",
"instead"
] | def compile_fun_noshell(line):
"""
Create a compiled function to execute a process without the shell
WARNING: this method may disappear anytime, so use compile_fun instead
"""
extr = []
def repl(match):
g = match.group
if g('dollar'): return "$"
elif g('subst'): extr.append((g('var'), g('code'))); return "<<|@|>>"
return None
line2 = reg_act.sub(repl, line)
params = line2.split('<<|@|>>')
assert(extr)
buf = []
dvars = []
app = buf.append
for x in range(len(extr)):
params[x] = params[x].strip()
if params[x]:
app("lst.extend(%r)" % params[x].split())
(var, meth) = extr[x]
if var == 'SRC':
if meth: app('lst.append(tsk.inputs%s)' % meth)
else: app("lst.extend([a.abspath() for a in tsk.inputs])")
elif var == 'TGT':
if meth: app('lst.append(tsk.outputs%s)' % meth)
else: app("lst.extend([a.abspath() for a in tsk.outputs])")
elif meth:
if meth.startswith(':'):
m = meth[1:]
if m == 'SRC':
m = '[a.abspath() for a in tsk.inputs]'
elif m == 'TGT':
m = '[a.abspath() for a in tsk.outputs]'
elif m[:3] not in ('tsk', 'gen', 'bld'):
dvars.extend([var, m])
m = '%r' % m
app('lst.extend(tsk.colon(%r, %s))' % (var, m))
else:
app('lst.extend(gen.to_list(%s%s))' % (var, meth))
else:
app('lst.extend(to_list(env[%r]))' % var)
if not var in dvars: dvars.append(var)
if extr:
if params[-1]:
app("lst.extend(%r)" % params[-1].split())
fun = COMPILE_TEMPLATE_NOSHELL % "\n\t".join(buf)
Logs.debug('action: %s' % fun.strip().splitlines())
return (funex(fun), dvars) | [
"def",
"compile_fun_noshell",
"(",
"line",
")",
":",
"extr",
"=",
"[",
"]",
"def",
"repl",
"(",
"match",
")",
":",
"g",
"=",
"match",
".",
"group",
"if",
"g",
"(",
"'dollar'",
")",
":",
"return",
"\"$\"",
"elif",
"g",
"(",
"'subst'",
")",
":",
"e... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Task.py#L1070-L1122 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/closure_linter/closure_linter/requireprovidesorter.py | python | RequireProvideSorter._GetTokensMap | (self, tokens) | return tokens_map | Gets a map from object name to tokens associated with that object.
Starting from the goog.provide/goog.require token, searches backwards in the
token stream for any lines that start with a comment. These lines are
associated with the goog.provide/goog.require token. Also associates any
tokens on the same line as the goog.provide/goog.require token with that
token.
Args:
tokens: A list of goog.provide or goog.require tokens.
Returns:
A dictionary that maps object names to the tokens associated with the
goog.provide or goog.require of that object name. For example:
{
'object.a': [JavaScriptToken, JavaScriptToken, ...],
'object.b': [...]
}
The list of tokens includes any comment lines above the goog.provide or
goog.require statement and everything after the statement on the same
line. For example, all of the following would be associated with
'object.a':
/** @suppress {extraRequire} */
goog.require('object.a'); // Some comment. | Gets a map from object name to tokens associated with that object. | [
"Gets",
"a",
"map",
"from",
"object",
"name",
"to",
"tokens",
"associated",
"with",
"that",
"object",
"."
] | def _GetTokensMap(self, tokens):
"""Gets a map from object name to tokens associated with that object.
Starting from the goog.provide/goog.require token, searches backwards in the
token stream for any lines that start with a comment. These lines are
associated with the goog.provide/goog.require token. Also associates any
tokens on the same line as the goog.provide/goog.require token with that
token.
Args:
tokens: A list of goog.provide or goog.require tokens.
Returns:
A dictionary that maps object names to the tokens associated with the
goog.provide or goog.require of that object name. For example:
{
'object.a': [JavaScriptToken, JavaScriptToken, ...],
'object.b': [...]
}
The list of tokens includes any comment lines above the goog.provide or
goog.require statement and everything after the statement on the same
line. For example, all of the following would be associated with
'object.a':
/** @suppress {extraRequire} */
goog.require('object.a'); // Some comment.
"""
tokens_map = {}
for token in tokens:
object_name = tokenutil.Search(token, Type.STRING_TEXT).string
# If the previous line starts with a comment, presume that the comment
# relates to the goog.require or goog.provide and keep them together when
# sorting.
first_token = token
previous_first_token = tokenutil.GetFirstTokenInPreviousLine(first_token)
while previous_first_token.IsAnyType(Type.COMMENT_TYPES):
first_token = previous_first_token
previous_first_token = tokenutil.GetFirstTokenInPreviousLine(
first_token)
# Find the last token on the line.
last_token = tokenutil.GetLastTokenInSameLine(token)
all_tokens = self._GetTokenList(first_token, last_token)
tokens_map[object_name] = all_tokens
return tokens_map | [
"def",
"_GetTokensMap",
"(",
"self",
",",
"tokens",
")",
":",
"tokens_map",
"=",
"{",
"}",
"for",
"token",
"in",
"tokens",
":",
"object_name",
"=",
"tokenutil",
".",
"Search",
"(",
"token",
",",
"Type",
".",
"STRING_TEXT",
")",
".",
"string",
"# If the p... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/requireprovidesorter.py#L200-L247 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/distributed_c10d.py | python | is_mpi_available | () | return _MPI_AVAILABLE | Checks if the MPI backend is available. | Checks if the MPI backend is available. | [
"Checks",
"if",
"the",
"MPI",
"backend",
"is",
"available",
"."
] | def is_mpi_available():
"""
Checks if the MPI backend is available.
"""
return _MPI_AVAILABLE | [
"def",
"is_mpi_available",
"(",
")",
":",
"return",
"_MPI_AVAILABLE"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/distributed_c10d.py#L384-L388 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewIconText.__init__ | (self, *args, **kwargs) | __init__(self, String text=wxEmptyString, Icon icon=wxNullIcon) -> DataViewIconText
DataViewIconText is used to hold the data for columns using the
`DataViewIconTextRenderer` | __init__(self, String text=wxEmptyString, Icon icon=wxNullIcon) -> DataViewIconText | [
"__init__",
"(",
"self",
"String",
"text",
"=",
"wxEmptyString",
"Icon",
"icon",
"=",
"wxNullIcon",
")",
"-",
">",
"DataViewIconText"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, String text=wxEmptyString, Icon icon=wxNullIcon) -> DataViewIconText
DataViewIconText is used to hold the data for columns using the
`DataViewIconTextRenderer`
"""
_dataview.DataViewIconText_swiginit(self,_dataview.new_DataViewIconText(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_dataview",
".",
"DataViewIconText_swiginit",
"(",
"self",
",",
"_dataview",
".",
"new_DataViewIconText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1293-L1300 | ||
hszhao/PSPNet | cf7e5a99ba37e46118026e96be5821a9bc63bde0 | scripts/cpp_lint.py | python | _NestingState.UpdatePreprocessor | (self, line) | Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check. | Update preprocessor stack. | [
"Update",
"preprocessor",
"stack",
"."
] | def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass | [
"def",
"UpdatePreprocessor",
"(",
"self",
",",
"line",
")",
":",
"if",
"Match",
"(",
"r'^\\s*#\\s*(if|ifdef|ifndef)\\b'",
",",
"line",
")",
":",
"# Beginning of #if block, save the nesting stack here. The saved",
"# stack will allow us to restore the parsing state in the #else cas... | https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L1948-L2002 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/command/frame_filters.py | python | SetFrameFilterPriority.complete | (self, text, word) | Completion function for both frame filter dictionary, and
frame filter name. | Completion function for both frame filter dictionary, and
frame filter name. | [
"Completion",
"function",
"for",
"both",
"frame",
"filter",
"dictionary",
"and",
"frame",
"filter",
"name",
"."
] | def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
frame filter name."""
if text.count(" ") == 0:
return _complete_frame_filter_list(text, word, False)
else:
printer_list = gdb.frames.return_list(text.split()[0].rstrip())
return _complete_frame_filter_name(word, printer_list) | [
"def",
"complete",
"(",
"self",
",",
"text",
",",
"word",
")",
":",
"if",
"text",
".",
"count",
"(",
"\" \"",
")",
"==",
"0",
":",
"return",
"_complete_frame_filter_list",
"(",
"text",
",",
"word",
",",
"False",
")",
"else",
":",
"printer_list",
"=",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/command/frame_filters.py#L355-L362 | ||
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/libs/metaparse/tools/benchmark/generate.py | python | out_filename | (template, n_val, mode) | return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier) | Determine the output filename | Determine the output filename | [
"Determine",
"the",
"output",
"filename"
] | def out_filename(template, n_val, mode):
"""Determine the output filename"""
return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier) | [
"def",
"out_filename",
"(",
"template",
",",
"n_val",
",",
"mode",
")",
":",
"return",
"'{0}_{1}_{2}.cpp'",
".",
"format",
"(",
"template",
".",
"name",
",",
"n_val",
",",
"mode",
".",
"identifier",
")"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/libs/metaparse/tools/benchmark/generate.py#L233-L235 | |
seladb/PcapPlusPlus | 6a9183ae9c156593fa18d6f78037f4ad236d91f9 | mk/setup_dpdk.py | python | display_devices | (title, dev_list, extra_params=None) | Displays to the user the details of a list of devices given in
"dev_list". The "extra_params" parameter, if given, should contain a string
with %()s fields in it for replacement by the named fields in each
device's dictionary. | Displays to the user the details of a list of devices given in
"dev_list". The "extra_params" parameter, if given, should contain a string
with %()s fields in it for replacement by the named fields in each
device's dictionary. | [
"Displays",
"to",
"the",
"user",
"the",
"details",
"of",
"a",
"list",
"of",
"devices",
"given",
"in",
"dev_list",
".",
"The",
"extra_params",
"parameter",
"if",
"given",
"should",
"contain",
"a",
"string",
"with",
"%",
"()",
"s",
"fields",
"in",
"it",
"f... | def display_devices(title, dev_list, extra_params=None):
"""Displays to the user the details of a list of devices given in
"dev_list". The "extra_params" parameter, if given, should contain a string
with %()s fields in it for replacement by the named fields in each
device's dictionary."""
strings = [] # this holds the strings to print. We sort before printing
print("\n%s" % title)
print("=" * len(title))
if len(dev_list) == 0:
strings.append("<none>")
else:
for dev in dev_list:
if extra_params is not None:
strings.append(
"%s '%s %s' %s"
% (
dev["Slot"],
dev["Device_str"],
dev["Device"],
extra_params % dev,
)
)
else:
strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
# sort before printing, so that the entries appear in PCI order
strings.sort()
print("\n".join(strings)) | [
"def",
"display_devices",
"(",
"title",
",",
"dev_list",
",",
"extra_params",
"=",
"None",
")",
":",
"strings",
"=",
"[",
"]",
"# this holds the strings to print. We sort before printing",
"print",
"(",
"\"\\n%s\"",
"%",
"title",
")",
"print",
"(",
"\"=\"",
"*",
... | https://github.com/seladb/PcapPlusPlus/blob/6a9183ae9c156593fa18d6f78037f4ad236d91f9/mk/setup_dpdk.py#L583-L609 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py | python | Random.choice | (self, seq) | return seq[int(self.random() * len(seq))] | Choose a random element from a non-empty sequence. | Choose a random element from a non-empty sequence. | [
"Choose",
"a",
"random",
"element",
"from",
"a",
"non",
"-",
"empty",
"sequence",
"."
] | def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
return seq[int(self.random() * len(seq))] | [
"def",
"choice",
"(",
"self",
",",
"seq",
")",
":",
"return",
"seq",
"[",
"int",
"(",
"self",
".",
"random",
"(",
")",
"*",
"len",
"(",
"seq",
")",
")",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py#L272-L274 | |
simsong/bulk_extractor | 738911df22b7066ca9e1662f4131fb44090a4196 | python/ttable.py | python | ttable.format_cell | (self,value,colNumber) | return (ret[0], self.col_alignment.get(colNumber,ret[1])) | Format a value that appears in a given colNumber. | Format a value that appears in a given colNumber. | [
"Format",
"a",
"value",
"that",
"appears",
"in",
"a",
"given",
"colNumber",
"."
] | def format_cell(self,value,colNumber):
""" Format a value that appears in a given colNumber."""
import decimal
ret = None
if value==None:
return ("",self.LEFT)
if value==0 and self.SUPPRESS_ZERO in self.options:
return ("",self.LEFT)
if isnumber(value):
try:
(prefix,fmt,suffix) = self.col_fmt[colNumber]
fmt = prefix + commas(value,fmt) + suffix
except KeyError:
fmt = commas(value,self.col_fmt_default)
ret = (fmt,self.RIGHT)
if not ret:
ret = (str(value),self.LEFT)
return (ret[0], self.col_alignment.get(colNumber,ret[1])) | [
"def",
"format_cell",
"(",
"self",
",",
"value",
",",
"colNumber",
")",
":",
"import",
"decimal",
"ret",
"=",
"None",
"if",
"value",
"==",
"None",
":",
"return",
"(",
"\"\"",
",",
"self",
".",
"LEFT",
")",
"if",
"value",
"==",
"0",
"and",
"self",
"... | https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/ttable.py#L188-L206 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ast.py | python | iter_fields | (node) | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*. | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*. | [
"Yield",
"a",
"tuple",
"of",
"(",
"fieldname",
"value",
")",
"for",
"each",
"field",
"in",
"node",
".",
"_fields",
"that",
"is",
"present",
"on",
"*",
"node",
"*",
"."
] | def iter_fields(node):
"""
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*.
"""
for field in node._fields:
try:
yield field, getattr(node, field)
except AttributeError:
pass | [
"def",
"iter_fields",
"(",
"node",
")",
":",
"for",
"field",
"in",
"node",
".",
"_fields",
":",
"try",
":",
"yield",
"field",
",",
"getattr",
"(",
"node",
",",
"field",
")",
"except",
"AttributeError",
":",
"pass"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ast.py#L161-L170 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/generator/analyzer.py | python | _WriteOutput | (params, **values) | Writes the output, either to stdout or a file is specified. | Writes the output, either to stdout or a file is specified. | [
"Writes",
"the",
"output",
"either",
"to",
"stdout",
"or",
"a",
"file",
"is",
"specified",
"."
] | def _WriteOutput(params, **values):
"""Writes the output, either to stdout or a file is specified."""
if 'error' in values:
print('Error:', values['error'])
if 'status' in values:
print(values['status'])
if 'targets' in values:
values['targets'].sort()
print('Supplied targets that depend on changed files:')
for target in values['targets']:
print('\t', target)
if 'invalid_targets' in values:
values['invalid_targets'].sort()
print('The following targets were not found:')
for target in values['invalid_targets']:
print('\t', target)
if 'build_targets' in values:
values['build_targets'].sort()
print('Targets that require a build:')
for target in values['build_targets']:
print('\t', target)
if 'compile_targets' in values:
values['compile_targets'].sort()
print('Targets that need to be built:')
for target in values['compile_targets']:
print('\t', target)
if 'test_targets' in values:
values['test_targets'].sort()
print('Test targets:')
for target in values['test_targets']:
print('\t', target)
output_path = params.get('generator_flags', {}).get(
'analyzer_output_path', None)
if not output_path:
print(json.dumps(values))
return
try:
f = open(output_path, 'w')
f.write(json.dumps(values) + '\n')
f.close()
except IOError as e:
print('Error writing to output file', output_path, str(e)) | [
"def",
"_WriteOutput",
"(",
"params",
",",
"*",
"*",
"values",
")",
":",
"if",
"'error'",
"in",
"values",
":",
"print",
"(",
"'Error:'",
",",
"values",
"[",
"'error'",
"]",
")",
"if",
"'status'",
"in",
"values",
":",
"print",
"(",
"values",
"[",
"'st... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/analyzer.py#L509-L551 | ||
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_data.py | python | Data.decode | (self, encoded: bytes) | return self._check(pn_data_decode(self._data, encoded)) | Decodes the first value from supplied AMQP data and returns the
number of bytes consumed.
:param encoded: AMQP encoded binary data
:raise: :exc:`DataException` if there is a Proton error. | Decodes the first value from supplied AMQP data and returns the
number of bytes consumed. | [
"Decodes",
"the",
"first",
"value",
"from",
"supplied",
"AMQP",
"data",
"and",
"returns",
"the",
"number",
"of",
"bytes",
"consumed",
"."
] | def decode(self, encoded: bytes) -> int:
"""
Decodes the first value from supplied AMQP data and returns the
number of bytes consumed.
:param encoded: AMQP encoded binary data
:raise: :exc:`DataException` if there is a Proton error.
"""
return self._check(pn_data_decode(self._data, encoded)) | [
"def",
"decode",
"(",
"self",
",",
"encoded",
":",
"bytes",
")",
"->",
"int",
":",
"return",
"self",
".",
"_check",
"(",
"pn_data_decode",
"(",
"self",
".",
"_data",
",",
"encoded",
")",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_data.py#L811-L819 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/pstats.py | python | add_callers | (target, source) | return new_callers | Combine two caller lists in a single list. | Combine two caller lists in a single list. | [
"Combine",
"two",
"caller",
"lists",
"in",
"a",
"single",
"list",
"."
] | def add_callers(target, source):
"""Combine two caller lists in a single list."""
new_callers = {}
for func, caller in target.iteritems():
new_callers[func] = caller
for func, caller in source.iteritems():
if func in new_callers:
new_callers[func] = tuple([i[0] + i[1] for i in
zip(caller, new_callers[func])])
else:
new_callers[func] = caller
return new_callers | [
"def",
"add_callers",
"(",
"target",
",",
"source",
")",
":",
"new_callers",
"=",
"{",
"}",
"for",
"func",
",",
"caller",
"in",
"target",
".",
"iteritems",
"(",
")",
":",
"new_callers",
"[",
"func",
"]",
"=",
"caller",
"for",
"func",
",",
"caller",
"... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pstats.py#L518-L529 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | delete | (arr, obj, axis=None) | Return a new array with sub-arrays along an axis deleted. For a one
dimensional array, this returns those entries not returned by
`arr[obj]`.
Parameters
----------
arr : _Symbol
Input array.
obj : slice, scaler or _Symbol of ints
Indicate indices of sub-arrays to remove along the specified axis.
axis : scaler, optional
The axis along which to delete the subarray defined by `obj`.
If `axis` is None, `obj` is applied to the flattened array.
Returns
-------
out : _Symbol
A copy of `arr` with the elements specified by `obj` removed. Note
that `delete` does not occur in-place. If `axis` is None, `out` is
a flattened array. | Return a new array with sub-arrays along an axis deleted. For a one
dimensional array, this returns those entries not returned by
`arr[obj]`. | [
"Return",
"a",
"new",
"array",
"with",
"sub",
"-",
"arrays",
"along",
"an",
"axis",
"deleted",
".",
"For",
"a",
"one",
"dimensional",
"array",
"this",
"returns",
"those",
"entries",
"not",
"returned",
"by",
"arr",
"[",
"obj",
"]",
"."
] | def delete(arr, obj, axis=None):
"""
Return a new array with sub-arrays along an axis deleted. For a one
dimensional array, this returns those entries not returned by
`arr[obj]`.
Parameters
----------
arr : _Symbol
Input array.
obj : slice, scaler or _Symbol of ints
Indicate indices of sub-arrays to remove along the specified axis.
axis : scaler, optional
The axis along which to delete the subarray defined by `obj`.
If `axis` is None, `obj` is applied to the flattened array.
Returns
-------
out : _Symbol
A copy of `arr` with the elements specified by `obj` removed. Note
that `delete` does not occur in-place. If `axis` is None, `out` is
a flattened array.
"""
if not isinstance(arr, Symbol):
raise TypeError("'arr' can not support type {}".format(str(type(arr))))
if isinstance(obj, slice):
start = obj.start
stop = obj.stop
step = 1 if obj.step is None else obj.step
return _npi.delete(arr, start=start, stop=stop, step=step, axis=axis)
elif isinstance(obj, integer_types):
return _npi.delete(arr, int_ind=obj, axis=axis)
elif isinstance(obj, Symbol):
return _npi.delete(arr, obj, axis=axis)
else:
raise TypeError("'obj' can not support type {}".format(str(type(obj)))) | [
"def",
"delete",
"(",
"arr",
",",
"obj",
",",
"axis",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"Symbol",
")",
":",
"raise",
"TypeError",
"(",
"\"'arr' can not support type {}\"",
".",
"format",
"(",
"str",
"(",
"type",
"(",
"a... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L3908-L3943 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/chrome_cache.py | python | PullBrowserCache | (device) | return save_target | Pulls the browser cache from the device and saves it locally.
Cache is saved with the same file structure as on the device. Timestamps are
important to preserve because indexing and eviction depends on them.
Returns:
Temporary directory containing all the browser cache. | Pulls the browser cache from the device and saves it locally. | [
"Pulls",
"the",
"browser",
"cache",
"from",
"the",
"device",
"and",
"saves",
"it",
"locally",
"."
] | def PullBrowserCache(device):
"""Pulls the browser cache from the device and saves it locally.
Cache is saved with the same file structure as on the device. Timestamps are
important to preserve because indexing and eviction depends on them.
Returns:
Temporary directory containing all the browser cache.
"""
_INDEX_DIRECTORY_NAME = 'index-dir'
_REAL_INDEX_FILE_NAME = 'the-real-index'
remote_cache_directory = _RemoteCacheDirectory()
save_target = tempfile.mkdtemp(suffix='.cache')
# Pull the cache recursively.
device.adb.Pull(remote_cache_directory, save_target)
# Update the modification time stamp on the local cache copy.
def _UpdateTimestampFromAdbStat(filename, stat):
assert os.path.exists(filename)
os.utime(filename, (stat.st_time, stat.st_time))
for filename, stat in device.adb.Ls(remote_cache_directory):
if filename == '..':
continue
if filename == '.':
cache_directory_stat = stat
continue
original_file = os.path.join(remote_cache_directory, filename)
saved_file = os.path.join(save_target, filename)
_UpdateTimestampFromAdbStat(saved_file, stat)
if filename == _INDEX_DIRECTORY_NAME:
# The directory containing the index was pulled recursively, update the
# timestamps for known files. They are ignored by cache backend, but may
# be useful for debugging.
index_dir_stat = stat
saved_index_dir = os.path.join(save_target, _INDEX_DIRECTORY_NAME)
saved_index_file = os.path.join(saved_index_dir, _REAL_INDEX_FILE_NAME)
for sub_file, sub_stat in device.adb.Ls(original_file):
if sub_file == _REAL_INDEX_FILE_NAME:
_UpdateTimestampFromAdbStat(saved_index_file, sub_stat)
break
_UpdateTimestampFromAdbStat(saved_index_dir, index_dir_stat)
# Store the cache directory modification time. It is important to update it
# after all files in it have been written. The timestamp is compared with
# the contents of the index file when freshness is determined.
_UpdateTimestampFromAdbStat(save_target, cache_directory_stat)
return save_target | [
"def",
"PullBrowserCache",
"(",
"device",
")",
":",
"_INDEX_DIRECTORY_NAME",
"=",
"'index-dir'",
"_REAL_INDEX_FILE_NAME",
"=",
"'the-real-index'",
"remote_cache_directory",
"=",
"_RemoteCacheDirectory",
"(",
")",
"save_target",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"suf... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/chrome_cache.py#L61-L110 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | BookCtrlBase.CalcSizeFromPage | (*args, **kwargs) | return _core_.BookCtrlBase_CalcSizeFromPage(*args, **kwargs) | CalcSizeFromPage(self, Size sizePage) -> Size | CalcSizeFromPage(self, Size sizePage) -> Size | [
"CalcSizeFromPage",
"(",
"self",
"Size",
"sizePage",
")",
"-",
">",
"Size"
] | def CalcSizeFromPage(*args, **kwargs):
"""CalcSizeFromPage(self, Size sizePage) -> Size"""
return _core_.BookCtrlBase_CalcSizeFromPage(*args, **kwargs) | [
"def",
"CalcSizeFromPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"BookCtrlBase_CalcSizeFromPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13574-L13576 | |
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | urllib3/__init__.py | python | add_stderr_logger | (level=logging.DEBUG) | return handler | Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it. | Helper for quickly adding a StreamHandler to the logger. Useful for
debugging. | [
"Helper",
"for",
"quickly",
"adding",
"a",
"StreamHandler",
"to",
"the",
"logger",
".",
"Useful",
"for",
"debugging",
"."
] | def add_stderr_logger(level=logging.DEBUG):
"""
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it.
"""
# This method needs to be in this __init__.py to get the __name__ correct
# even if urllib3 is vendored within another package.
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(handler)
logger.setLevel(level)
logger.debug('Added an stderr logging handler to logger: %s' % __name__)
return handler | [
"def",
"add_stderr_logger",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"# This method needs to be in this __init__.py to get the __name__ correct",
"# even if urllib3 is vendored within another package.",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
"... | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/__init__.py#L40-L55 | |
lmb-freiburg/ogn | 974f72ef4bf840d6f6693d22d1843a79223e77ce | scripts/cpp_lint.py | python | FindStartOfExpressionInLine | (line, endpos, depth, startchar, endchar) | return (-1, depth) | Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line) | Find position at the matching startchar. | [
"Find",
"position",
"at",
"the",
"matching",
"startchar",
"."
] | def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
"""Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line)
"""
for i in xrange(endpos, -1, -1):
if line[i] == endchar:
depth += 1
elif line[i] == startchar:
depth -= 1
if depth == 0:
return (i, 0)
return (-1, depth) | [
"def",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"endpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"endpos",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"endch... | https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L1300-L1324 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py | python | TypeRef.is_pointer | (self) | return ffi.lib.LLVMPY_TypeIsPointer(self) | Returns true is the type is a pointer type. | Returns true is the type is a pointer type. | [
"Returns",
"true",
"is",
"the",
"type",
"is",
"a",
"pointer",
"type",
"."
] | def is_pointer(self):
"""
Returns true is the type is a pointer type.
"""
return ffi.lib.LLVMPY_TypeIsPointer(self) | [
"def",
"is_pointer",
"(",
"self",
")",
":",
"return",
"ffi",
".",
"lib",
".",
"LLVMPY_TypeIsPointer",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py#L57-L61 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/mozjs-38/extract/js/src/builtin/make_intl_data.py | python | readRegistry | (registry) | return {"fileDate": fileDate,
"langTagMappings": langTagMappings,
"langSubtagMappings": langSubtagMappings,
"extlangMappings": extlangMappings} | Reads IANA Language Subtag Registry and extracts information for Intl.js.
Information extracted:
- langTagMappings: mappings from complete language tags to preferred
complete language tags
- langSubtagMappings: mappings from subtags to preferred subtags
- extlangMappings: mappings from extlang subtags to preferred subtags,
with prefix to be removed
Returns these three mappings as dictionaries, along with the registry's
file date.
We also check that mappings for language subtags don't affect extlang
subtags and vice versa, so that CanonicalizeLanguageTag doesn't have
to separate them for processing. Region codes are separated by case,
and script codes by length, so they're unproblematic. | Reads IANA Language Subtag Registry and extracts information for Intl.js. | [
"Reads",
"IANA",
"Language",
"Subtag",
"Registry",
"and",
"extracts",
"information",
"for",
"Intl",
".",
"js",
"."
] | def readRegistry(registry):
""" Reads IANA Language Subtag Registry and extracts information for Intl.js.
Information extracted:
- langTagMappings: mappings from complete language tags to preferred
complete language tags
- langSubtagMappings: mappings from subtags to preferred subtags
- extlangMappings: mappings from extlang subtags to preferred subtags,
with prefix to be removed
Returns these three mappings as dictionaries, along with the registry's
file date.
We also check that mappings for language subtags don't affect extlang
subtags and vice versa, so that CanonicalizeLanguageTag doesn't have
to separate them for processing. Region codes are separated by case,
and script codes by length, so they're unproblematic.
"""
langTagMappings = {}
langSubtagMappings = {}
extlangMappings = {}
languageSubtags = set()
extlangSubtags = set()
for record in readRegistryRecord(registry):
if "File-Date" in record:
fileDate = record["File-Date"]
continue
if record["Type"] == "grandfathered":
# Grandfathered tags don't use standard syntax, so
# CanonicalizeLanguageTag expects the mapping table to provide
# the final form for all.
# For langTagMappings, keys must be in lower case; values in
# the case used in the registry.
tag = record["Tag"]
if "Preferred-Value" in record:
langTagMappings[tag.lower()] = record["Preferred-Value"]
else:
langTagMappings[tag.lower()] = tag
elif record["Type"] == "redundant":
# For langTagMappings, keys must be in lower case; values in
# the case used in the registry.
if "Preferred-Value" in record:
langTagMappings[record["Tag"].lower()] = record["Preferred-Value"]
elif record["Type"] in ("language", "script", "region", "variant"):
# For langSubtagMappings, keys and values must be in the case used
# in the registry.
subtag = record["Subtag"]
if record["Type"] == "language":
languageSubtags.add(subtag)
if "Preferred-Value" in record:
if subtag == "heploc":
# The entry for heploc is unique in its complexity; handle
# it as special case below.
continue
if "Prefix" in record:
# This might indicate another heploc-like complex case.
raise Exception("Please evaluate: subtag mapping with prefix value.")
langSubtagMappings[subtag] = record["Preferred-Value"]
elif record["Type"] == "extlang":
# For extlangMappings, keys must be in the case used in the
# registry; values are records with the preferred value and the
# prefix to be removed.
subtag = record["Subtag"]
extlangSubtags.add(subtag)
if "Preferred-Value" in record:
preferred = record["Preferred-Value"]
prefix = record["Prefix"]
extlangMappings[subtag] = {"preferred": preferred, "prefix": prefix}
else:
# No other types are allowed by
# http://tools.ietf.org/html/rfc5646#section-3.1.3
assert False, "Unrecognized Type: {0}".format(record["Type"])
# Check that mappings for language subtags and extlang subtags don't affect
# each other.
for lang in languageSubtags:
if lang in extlangMappings and extlangMappings[lang]["preferred"] != lang:
raise Exception("Conflict: lang with extlang mapping: " + lang)
for extlang in extlangSubtags:
if extlang in langSubtagMappings:
raise Exception("Conflict: extlang with lang mapping: " + extlang)
# Special case for heploc.
langTagMappings["ja-latn-hepburn-heploc"] = "ja-Latn-alalc97"
return {"fileDate": fileDate,
"langTagMappings": langTagMappings,
"langSubtagMappings": langSubtagMappings,
"extlangMappings": extlangMappings} | [
"def",
"readRegistry",
"(",
"registry",
")",
":",
"langTagMappings",
"=",
"{",
"}",
"langSubtagMappings",
"=",
"{",
"}",
"extlangMappings",
"=",
"{",
"}",
"languageSubtags",
"=",
"set",
"(",
")",
"extlangSubtags",
"=",
"set",
"(",
")",
"for",
"record",
"in... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/mozjs-38/extract/js/src/builtin/make_intl_data.py#L44-L133 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/mws/connection.py | python | MWSConnection.get_product_categories_for_asin | (self, request, response, **kw) | return self._post_request(request, kw, response) | Returns the product categories that an ASIN belongs to. | Returns the product categories that an ASIN belongs to. | [
"Returns",
"the",
"product",
"categories",
"that",
"an",
"ASIN",
"belongs",
"to",
"."
] | def get_product_categories_for_asin(self, request, response, **kw):
"""Returns the product categories that an ASIN belongs to.
"""
return self._post_request(request, kw, response) | [
"def",
"get_product_categories_for_asin",
"(",
"self",
",",
"request",
",",
"response",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_post_request",
"(",
"request",
",",
"kw",
",",
"response",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/mws/connection.py#L845-L848 | |
codilime/veles | e65de5a7c268129acffcdb03034efd8d256d025c | python/veles/dis/core.py | python | Isa.parse | (self, data, base=None, pos=0) | return res | Runs the disassembler on given data, returning an IsaParseResult
instance. ``pos`` is the position in ``data`` to start disassembly
from. ``base`` is a symbol representing the beginning of the
code section passed as data, or None if pos is to be treated as
an absolute number (it affects disassembly of PC-relative arguments). | Runs the disassembler on given data, returning an IsaParseResult
instance. ``pos`` is the position in ``data`` to start disassembly
from. ``base`` is a symbol representing the beginning of the
code section passed as data, or None if pos is to be treated as
an absolute number (it affects disassembly of PC-relative arguments). | [
"Runs",
"the",
"disassembler",
"on",
"given",
"data",
"returning",
"an",
"IsaParseResult",
"instance",
".",
"pos",
"is",
"the",
"position",
"in",
"data",
"to",
"start",
"disassembly",
"from",
".",
"base",
"is",
"a",
"symbol",
"representing",
"the",
"beginning"... | def parse(self, data, base=None, pos=0):
"""
Runs the disassembler on given data, returning an IsaParseResult
instance. ``pos`` is the position in ``data`` to start disassembly
from. ``base`` is a symbol representing the beginning of the
code section passed as data, or None if pos is to be treated as
an absolute number (it affects disassembly of PC-relative arguments).
"""
# XXX: the whole thing should use BinData, and support extra offset
# to pos.
res = IsaParseResult(base, pos)
s = ParseState(res, data, pos)
for x in self.parser:
x.parse(s)
res.len = s.pos - pos
return res | [
"def",
"parse",
"(",
"self",
",",
"data",
",",
"base",
"=",
"None",
",",
"pos",
"=",
"0",
")",
":",
"# XXX: the whole thing should use BinData, and support extra offset",
"# to pos.",
"res",
"=",
"IsaParseResult",
"(",
"base",
",",
"pos",
")",
"s",
"=",
"Parse... | https://github.com/codilime/veles/blob/e65de5a7c268129acffcdb03034efd8d256d025c/python/veles/dis/core.py#L76-L91 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/base/distributed_strategy.py | python | DistributedStrategy.auto_search | (self) | return self.strategy.auto_search | Indicating whether we are using auto-search parallel function
For details, please reference the following code example
Default Value: False
Examples:
.. code-block:: python
import paddle
paddle.enable_static()
import paddle.distributed.fleet as fleet
strategy = fleet.DistributedStrategy()
strategy.auto_search = True | Indicating whether we are using auto-search parallel function
For details, please reference the following code example
Default Value: False
Examples:
.. code-block:: python
import paddle
paddle.enable_static()
import paddle.distributed.fleet as fleet
strategy = fleet.DistributedStrategy()
strategy.auto_search = True | [
"Indicating",
"whether",
"we",
"are",
"using",
"auto",
"-",
"search",
"parallel",
"function",
"For",
"details",
"please",
"reference",
"the",
"following",
"code",
"example",
"Default",
"Value",
":",
"False",
"Examples",
":",
"..",
"code",
"-",
"block",
"::",
... | def auto_search(self):
"""
Indicating whether we are using auto-search parallel function
For details, please reference the following code example
Default Value: False
Examples:
.. code-block:: python
import paddle
paddle.enable_static()
import paddle.distributed.fleet as fleet
strategy = fleet.DistributedStrategy()
strategy.auto_search = True
"""
return self.strategy.auto_search | [
"def",
"auto_search",
"(",
"self",
")",
":",
"return",
"self",
".",
"strategy",
".",
"auto_search"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/base/distributed_strategy.py#L1751-L1764 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | main/python/cmdLineUtils.py | python | tupleListSort | (tupleList) | Sort list of tuples by their first elements ignoring the case | Sort list of tuples by their first elements ignoring the case | [
"Sort",
"list",
"of",
"tuples",
"by",
"their",
"first",
"elements",
"ignoring",
"the",
"case"
] | def tupleListSort(tupleList):
"""
Sort list of tuples by their first elements ignoring the case
"""
tupleList.sort(key=lambda x: x[0].lower()) | [
"def",
"tupleListSort",
"(",
"tupleList",
")",
":",
"tupleList",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
".",
"lower",
"(",
")",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/main/python/cmdLineUtils.py#L246-L250 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/apply.py | python | FrameRowApply.wrap_results_for_axis | (self) | return result | return the results for the rows | return the results for the rows | [
"return",
"the",
"results",
"for",
"the",
"rows"
] | def wrap_results_for_axis(self):
""" return the results for the rows """
results = self.results
result = self.obj._constructor(data=results)
if not isinstance(results[0], ABCSeries):
try:
result.index = self.res_columns
except ValueError:
pass
try:
result.columns = self.res_index
except ValueError:
pass
return result | [
"def",
"wrap_results_for_axis",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"results",
"result",
"=",
"self",
".",
"obj",
".",
"_constructor",
"(",
"data",
"=",
"results",
")",
"if",
"not",
"isinstance",
"(",
"results",
"[",
"0",
"]",
",",
"ABC... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/apply.py#L336-L353 | |
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | projects/samples/robotbenchmark/visual_tracking/controllers/visual_tracking/visual_tracking.py | python | cleanup | () | Remove device image files. | Remove device image files. | [
"Remove",
"device",
"image",
"files",
"."
] | def cleanup():
"""Remove device image files."""
# Ignore errors if file doesn't exist.
try:
os.remove(deviceImagePath + '/display.jpg')
except OSError:
pass
try:
os.remove(deviceImagePath + '/camera.jpg')
except OSError:
pass | [
"def",
"cleanup",
"(",
")",
":",
"# Ignore errors if file doesn't exist.",
"try",
":",
"os",
".",
"remove",
"(",
"deviceImagePath",
"+",
"'/display.jpg'",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"os",
".",
"remove",
"(",
"deviceImagePath",
"+",
"'/c... | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/samples/robotbenchmark/visual_tracking/controllers/visual_tracking/visual_tracking.py#L21-L31 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/util.py | python | set_np_shape | (active) | return bool(prev.value) | Turns on/off NumPy shape semantics, in which `()` represents the shape of scalar tensors,
and tuples with `0` elements, for example, `(0,)`, `(1, 0, 2)`, represent the shapes
of zero-size tensors. This is turned off by default for keeping backward compatibility.
Please note that this is designed as an infrastructure for the incoming
MXNet-NumPy operators. Legacy operators registered in the modules
`mx.nd` and `mx.sym` are not guaranteed to behave like their counterparts
in NumPy within this semantics.
Parameters
----------
active : bool
Indicates whether to turn on/off NumPy shape semantics.
Returns
-------
A bool value indicating the previous state of NumPy shape semantics.
Example
-------
>>> import mxnet as mx
>>> prev_state = mx.set_np_shape(True)
>>> print(prev_state)
False
>>> print(mx.is_np_shape())
True | Turns on/off NumPy shape semantics, in which `()` represents the shape of scalar tensors,
and tuples with `0` elements, for example, `(0,)`, `(1, 0, 2)`, represent the shapes
of zero-size tensors. This is turned off by default for keeping backward compatibility. | [
"Turns",
"on",
"/",
"off",
"NumPy",
"shape",
"semantics",
"in",
"which",
"()",
"represents",
"the",
"shape",
"of",
"scalar",
"tensors",
"and",
"tuples",
"with",
"0",
"elements",
"for",
"example",
"(",
"0",
")",
"(",
"1",
"0",
"2",
")",
"represent",
"th... | def set_np_shape(active):
"""Turns on/off NumPy shape semantics, in which `()` represents the shape of scalar tensors,
and tuples with `0` elements, for example, `(0,)`, `(1, 0, 2)`, represent the shapes
of zero-size tensors. This is turned off by default for keeping backward compatibility.
Please note that this is designed as an infrastructure for the incoming
MXNet-NumPy operators. Legacy operators registered in the modules
`mx.nd` and `mx.sym` are not guaranteed to behave like their counterparts
in NumPy within this semantics.
Parameters
----------
active : bool
Indicates whether to turn on/off NumPy shape semantics.
Returns
-------
A bool value indicating the previous state of NumPy shape semantics.
Example
-------
>>> import mxnet as mx
>>> prev_state = mx.set_np_shape(True)
>>> print(prev_state)
False
>>> print(mx.is_np_shape())
True
"""
global _set_np_shape_logged
if active:
if not _set_np_shape_logged:
import logging
logging.info('NumPy-shape semantics has been activated in your code. '
'This is required for creating and manipulating scalar and zero-size '
'tensors, which were not supported in MXNet before, as in the official '
'NumPy library. Please DO NOT manually deactivate this semantics while '
'using `mxnet.numpy` and `mxnet.numpy_extension` modules.')
_set_np_shape_logged = True
elif is_np_array():
raise ValueError('Deactivating NumPy shape semantics while NumPy array semantics is still'
' active is not allowed. Please consider calling `npx.reset_np()` to'
' deactivate both of them.')
prev = ctypes.c_int()
check_call(_LIB.MXSetIsNumpyShape(ctypes.c_int(active), ctypes.byref(prev)))
return bool(prev.value) | [
"def",
"set_np_shape",
"(",
"active",
")",
":",
"global",
"_set_np_shape_logged",
"if",
"active",
":",
"if",
"not",
"_set_np_shape_logged",
":",
"import",
"logging",
"logging",
".",
"info",
"(",
"'NumPy-shape semantics has been activated in your code. '",
"'This is requir... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/util.py#L58-L102 | |
rdiankov/openrave | d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7 | sandbox/mobilemanipulation.py | python | MobileManipulationPlanning.moveToNeutral | (self,neutraljointvalues,bounds=None,manipnames=None,ikcollisionbody=None) | moves the robot to a neutral position defined by several manipulators and neutraljointvalues. Can also specify a special collision body to constraint choosing the goals. | moves the robot to a neutral position defined by several manipulators and neutraljointvalues. Can also specify a special collision body to constraint choosing the goals. | [
"moves",
"the",
"robot",
"to",
"a",
"neutral",
"position",
"defined",
"by",
"several",
"manipulators",
"and",
"neutraljointvalues",
".",
"Can",
"also",
"specify",
"a",
"special",
"collision",
"body",
"to",
"constraint",
"choosing",
"the",
"goals",
"."
] | def moveToNeutral(self,neutraljointvalues,bounds=None,manipnames=None,ikcollisionbody=None):
"""moves the robot to a neutral position defined by several manipulators and neutraljointvalues. Can also specify a special collision body to constraint choosing the goals."""
if manipnames is None:
manipnames = ['leftarm','rightarm']
manips = [self.robot.GetManipulator(name) for name in manipnames]
ikmodels = []
for manip in manips:
self.robot.SetActiveManipulator(manip)
ikmodel = inversekinematics.InverseKinematicsModel(robot=self.robot,iktype=IkParameterization.Type.Transform6D)
if not ikmodel.load():
ikmodel.autogenerate()
ikmodels.append(ikmodel)
goaljointvalues = None
alltrajdata = None
with self.robot:
origjointvalues=self.robot.GetDOFValues()
self.robot.SetDOFValues(neutraljointvalues)
if ikcollisionbody is not None:
ikcollisionbody.Enable(True)
nocollision = not self.env.CheckCollision(self.robot) and not self.robot.CheckSelfCollision()
if ikcollisionbody is not None:
ikcollisionbody.Enable(False)
if nocollision:
goaljointvalues = neutraljointvalues
try:
alltrajdata = []
self.robot.SetDOFValues(origjointvalues)
for manip in manips:
self.robot.SetActiveDOFs(manip.GetArmIndices())
alltrajdata.append(self.basemanip.MoveActiveJoints(goal=goaljointvalues[manip.GetArmIndices()],execute=False,outputtraj=True))
self.robot.SetDOFValues(goaljointvalues[manip.GetArmIndices()],manip.GetArmIndices())
except planning_error:
alltrajdata = None
if alltrajdata is None:
self.robot.SetDOFValues(neutraljointvalues)
Tmanips = [dot(linalg.inv(manip.GetBase().GetTransform()),manip.GetEndEffectorTransform()) for manip in manips]
for niter in range(500):
self.robot.SetDOFValues(origjointvalues)
if bounds is None:
r = random.rand(3)*0.4-0.2
else:
r = bounds[0,:]+random.rand(3)*(bounds[1,:]-bounds[0,:])
success = True
startjointvalues=[]
for manip,Tmanip in izip(manips,Tmanips):
T = dot(manip.GetBase().GetTransform(),Tmanip)
if niter > 0:
T[0:3,3] += r
if niter > 200:
T[0:3,0:3] = dot(T[0:3,0:3],rotationMatrixFromAxisAngle(random.rand(3)*0.5))
s=None
try:
if ikcollisionbody is not None:
ikcollisionbody.Enable(True)
for link in manip.GetIndependentLinks():
link.Enable(False)
s = manip.FindIKSolution(T,filteroptions=IkFilterOptions.CheckEnvCollisions)
finally:
if ikcollisionbody is not None:
ikcollisionbody.Enable(False)
for link in manip.GetIndependentLinks():
link.Enable(True)
if s is None:
success = False
break
else:
if ikcollisionbody is not None:
# have to check self collision
with self.robot:
self.robot.SetDOFValues(s,manip.GetArmIndices())
if self.robot.CheckSelfCollision():
success = False
break
startjointvalues.append(self.robot.GetDOFValues())
self.robot.SetDOFValues(s,manip.GetArmIndices())
if not success:
continue
try:
print 'attempting to plan...'
goaljointvalues = self.robot.GetDOFValues()
alltrajdata = []
for jointvalues,manip in izip(startjointvalues,manips):
self.robot.SetDOFValues(jointvalues)
self.robot.SetActiveDOFs(manip.GetArmIndices())
alltrajdata.append(self.basemanip.MoveActiveJoints(goal=goaljointvalues[manip.GetArmIndices()],execute=False,outputtraj=True))
break
except planning_error:
alltrajdata = None
if alltrajdata is None:
raise planning_error('failed to find collision free position')
for trajdata in alltrajdata:
self.basemanip.TrajFromData(trajdata)
self.waitrobot() | [
"def",
"moveToNeutral",
"(",
"self",
",",
"neutraljointvalues",
",",
"bounds",
"=",
"None",
",",
"manipnames",
"=",
"None",
",",
"ikcollisionbody",
"=",
"None",
")",
":",
"if",
"manipnames",
"is",
"None",
":",
"manipnames",
"=",
"[",
"'leftarm'",
",",
"'ri... | https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/sandbox/mobilemanipulation.py#L455-L547 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/__init__.py | python | PackageFinder._find_packages_iter | (cls, where, exclude, include) | All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter. | All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter. | [
"All",
"the",
"packages",
"found",
"in",
"where",
"that",
"pass",
"the",
"include",
"filter",
"but",
"not",
"the",
"exclude",
"filter",
"."
] | def _find_packages_iter(cls, where, exclude, include):
"""
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
"""
for root, dirs, files in os.walk(where, followlinks=True):
# Copy dirs to iterate over it, then empty dirs.
all_dirs = dirs[:]
dirs[:] = []
for dir in all_dirs:
full_path = os.path.join(root, dir)
rel_path = os.path.relpath(full_path, where)
package = rel_path.replace(os.path.sep, '.')
# Skip directory trees that are not valid packages
if ('.' in dir or not cls._looks_like_package(full_path)):
continue
# Should this package be included?
if include(package) and not exclude(package):
yield package
# Keep searching subdirectories, as there may be more packages
# down there, even if the parent was excluded.
dirs.append(dir) | [
"def",
"_find_packages_iter",
"(",
"cls",
",",
"where",
",",
"exclude",
",",
"include",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"where",
",",
"followlinks",
"=",
"True",
")",
":",
"# Copy dirs to iterate over it, t... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/__init__.py#L76-L101 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | llvm/utils/lit/lit/worker.py | python | execute | (test) | return test | Run one test in a multiprocessing.Pool
Side effects in this function and functions it calls are not visible in the
main lit process.
Arguments and results of this function are pickled, so they should be cheap
to copy. | Run one test in a multiprocessing.Pool | [
"Run",
"one",
"test",
"in",
"a",
"multiprocessing",
".",
"Pool"
] | def execute(test):
"""Run one test in a multiprocessing.Pool
Side effects in this function and functions it calls are not visible in the
main lit process.
Arguments and results of this function are pickled, so they should be cheap
to copy.
"""
with _get_parallelism_semaphore(test):
result = _execute(test, _lit_config)
test.setResult(result)
return test | [
"def",
"execute",
"(",
"test",
")",
":",
"with",
"_get_parallelism_semaphore",
"(",
"test",
")",
":",
"result",
"=",
"_execute",
"(",
"test",
",",
"_lit_config",
")",
"test",
".",
"setResult",
"(",
"result",
")",
"return",
"test"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/llvm/utils/lit/lit/worker.py#L35-L48 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/cond_v2.py | python | _create_none_optionals | (func_graph, n) | Creates `n` `None` optionals in func_graph.
Args:
func_graph: FuncGraph.
n: `int` the number of `None` optionals to make.
Returns:
A list of tensors in func_graph. | Creates `n` `None` optionals in func_graph. | [
"Creates",
"n",
"None",
"optionals",
"in",
"func_graph",
"."
] | def _create_none_optionals(func_graph, n):
"""Creates `n` `None` optionals in func_graph.
Args:
func_graph: FuncGraph.
n: `int` the number of `None` optionals to make.
Returns:
A list of tensors in func_graph.
"""
with func_graph.as_default():
return [gen_dataset_ops.optional_none() for _ in range(n)] | [
"def",
"_create_none_optionals",
"(",
"func_graph",
",",
"n",
")",
":",
"with",
"func_graph",
".",
"as_default",
"(",
")",
":",
"return",
"[",
"gen_dataset_ops",
".",
"optional_none",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/cond_v2.py#L778-L789 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/backprop.py | python | _get_arg_spec | (f, params, param_args) | The positions of the parameters of f to be differentiated in param_args. | The positions of the parameters of f to be differentiated in param_args. | [
"The",
"positions",
"of",
"the",
"parameters",
"of",
"f",
"to",
"be",
"differentiated",
"in",
"param_args",
"."
] | def _get_arg_spec(f, params, param_args):
"""The positions of the parameters of f to be differentiated in param_args."""
try:
args = tf_inspect.getfullargspec(f).args
except TypeError as e:
# TypeError can happen when f is a callable object.
if params is None:
return range(len(param_args))
elif all(isinstance(x, int) for x in params):
return params
raise ValueError("Either callable provided is not a function or could not "
"inspect its arguments by name: %s. Original error: %s"
% (f, e))
if params is None:
if not args:
return range(len(param_args))
return range(len(args))
elif all(isinstance(x, six.string_types) for x in params):
return [args.index(n) for n in params]
elif all(isinstance(x, int) for x in params):
return params
else:
raise ValueError(
"params must be all strings or all integers; got %s." % params) | [
"def",
"_get_arg_spec",
"(",
"f",
",",
"params",
",",
"param_args",
")",
":",
"try",
":",
"args",
"=",
"tf_inspect",
".",
"getfullargspec",
"(",
"f",
")",
".",
"args",
"except",
"TypeError",
"as",
"e",
":",
"# TypeError can happen when f is a callable object.",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/backprop.py#L275-L298 | ||
LARG/HFO | b8b2a1d462823c6732f4d5581aa7fe2e371d55cb | bin/Trainer.py | python | Trainer.checkLive | (self, necProcesses) | return True | Returns true if each of the necessary processes is still alive and
running. | Returns true if each of the necessary processes is still alive and
running. | [
"Returns",
"true",
"if",
"each",
"of",
"the",
"necessary",
"processes",
"is",
"still",
"alive",
"and",
"running",
"."
] | def checkLive(self, necProcesses):
"""Returns true if each of the necessary processes is still alive and
running.
"""
for p,name in necProcesses:
if p is not None and p.poll() is not None:
print('Something necessary closed (%s), exiting' % name)
return False
return True | [
"def",
"checkLive",
"(",
"self",
",",
"necProcesses",
")",
":",
"for",
"p",
",",
"name",
"in",
"necProcesses",
":",
"if",
"p",
"is",
"not",
"None",
"and",
"p",
".",
"poll",
"(",
")",
"is",
"not",
"None",
":",
"print",
"(",
"'Something necessary closed ... | https://github.com/LARG/HFO/blob/b8b2a1d462823c6732f4d5581aa7fe2e371d55cb/bin/Trainer.py#L370-L379 | |
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/recognizers.py | python | Lexer.emit | (self, token=None) | return token | The standard method called to automatically emit a token at the
outermost lexical rule. The token object should point into the
char buffer start..stop. If there is a text override in 'text',
use that to set the token's text. Override this method to emit
custom Token objects.
If you are building trees, then you should also override
Parser or TreeParser.getMissingSymbol(). | The standard method called to automatically emit a token at the
outermost lexical rule. The token object should point into the
char buffer start..stop. If there is a text override in 'text',
use that to set the token's text. Override this method to emit
custom Token objects. | [
"The",
"standard",
"method",
"called",
"to",
"automatically",
"emit",
"a",
"token",
"at",
"the",
"outermost",
"lexical",
"rule",
".",
"The",
"token",
"object",
"should",
"point",
"into",
"the",
"char",
"buffer",
"start",
"..",
"stop",
".",
"If",
"there",
"... | def emit(self, token=None):
"""
The standard method called to automatically emit a token at the
outermost lexical rule. The token object should point into the
char buffer start..stop. If there is a text override in 'text',
use that to set the token's text. Override this method to emit
custom Token objects.
If you are building trees, then you should also override
Parser or TreeParser.getMissingSymbol().
"""
if token is None:
token = CommonToken(
input=self.input,
type=self._state.type,
channel=self._state.channel,
start=self._state.tokenStartCharIndex,
stop=self.getCharIndex()-1
)
token.line = self._state.tokenStartLine
token.text = self._state.text
token.charPositionInLine = self._state.tokenStartCharPositionInLine
self._state.token = token
return token | [
"def",
"emit",
"(",
"self",
",",
"token",
"=",
"None",
")",
":",
"if",
"token",
"is",
"None",
":",
"token",
"=",
"CommonToken",
"(",
"input",
"=",
"self",
".",
"input",
",",
"type",
"=",
"self",
".",
"_state",
".",
"type",
",",
"channel",
"=",
"s... | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/recognizers.py#L1192-L1218 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/utils/spirv/gen_spirv_dialect.py | python | update_td_op_definitions | (path, instructions, docs, filter_list,
inst_category, capability_mapping, settings) | Updates SPIRVOps.td with newly generated op definition.
Arguments:
- path: path to SPIRVOps.td
- instructions: SPIR-V JSON grammar for all instructions
- docs: SPIR-V HTML doc for all instructions
- filter_list: a list containing new opnames to include
- capability_mapping: mapping from duplicated capability symbols to the
canonicalized symbol chosen for SPIRVBase.td.
Returns:
- A string containing all the TableGen op definitions | Updates SPIRVOps.td with newly generated op definition. | [
"Updates",
"SPIRVOps",
".",
"td",
"with",
"newly",
"generated",
"op",
"definition",
"."
] | def update_td_op_definitions(path, instructions, docs, filter_list,
inst_category, capability_mapping, settings):
"""Updates SPIRVOps.td with newly generated op definition.
Arguments:
- path: path to SPIRVOps.td
- instructions: SPIR-V JSON grammar for all instructions
- docs: SPIR-V HTML doc for all instructions
- filter_list: a list containing new opnames to include
- capability_mapping: mapping from duplicated capability symbols to the
canonicalized symbol chosen for SPIRVBase.td.
Returns:
- A string containing all the TableGen op definitions
"""
with open(path, 'r') as f:
content = f.read()
# Split the file into chunks, each containing one op.
ops = content.split(AUTOGEN_OP_DEF_SEPARATOR)
header = ops[0]
footer = ops[-1]
ops = ops[1:-1]
# For each existing op, extract the manually-written sections out to retain
# them when re-generating the ops. Also append the existing ops to filter
# list.
name_op_map = {} # Map from opname to its existing ODS definition
op_info_dict = {}
for op in ops:
info_dict = extract_td_op_info(op)
opname = info_dict['opname']
name_op_map[opname] = op
op_info_dict[opname] = info_dict
filter_list.append(opname)
filter_list = sorted(list(set(filter_list)))
op_defs = []
if settings.gen_ocl_ops:
fix_opname = lambda src: src.replace('OCL','').lower()
else:
fix_opname = lambda src: src
for opname in filter_list:
# Find the grammar spec for this op
try:
fixed_opname = fix_opname(opname)
instruction = next(
inst for inst in instructions if inst['opname'] == fixed_opname)
op_defs.append(
get_op_definition(
instruction, opname, docs[fixed_opname],
op_info_dict.get(opname, {'inst_category': inst_category}),
capability_mapping, settings))
except StopIteration:
# This is an op added by us; use the existing ODS definition.
op_defs.append(name_op_map[opname])
# Substitute the old op definitions
op_defs = [header] + op_defs + [footer]
content = AUTOGEN_OP_DEF_SEPARATOR.join(op_defs)
with open(path, 'w') as f:
f.write(content) | [
"def",
"update_td_op_definitions",
"(",
"path",
",",
"instructions",
",",
"docs",
",",
"filter_list",
",",
"inst_category",
",",
"capability_mapping",
",",
"settings",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"content",
"=",
... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/utils/spirv/gen_spirv_dialect.py#L923-L988 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/site_compare/scrapers/chrome/chrome011010.py | python | Scrape | (urls, outdir, size, pos, timeout=20, **kwargs) | return chromebase.Scrape(urls, outdir, size, pos, timeout, kwargs) | Invoke a browser, send it to a series of URLs, and save its output.
Args:
urls: list of URLs to scrape
outdir: directory to place output
size: size of browser window to use
pos: position of browser window
timeout: amount of time to wait for page to load
kwargs: miscellaneous keyword args
Returns:
None if succeeded, else an error code | Invoke a browser, send it to a series of URLs, and save its output. | [
"Invoke",
"a",
"browser",
"send",
"it",
"to",
"a",
"series",
"of",
"URLs",
"and",
"save",
"its",
"output",
"."
] | def Scrape(urls, outdir, size, pos, timeout=20, **kwargs):
"""Invoke a browser, send it to a series of URLs, and save its output.
Args:
urls: list of URLs to scrape
outdir: directory to place output
size: size of browser window to use
pos: position of browser window
timeout: amount of time to wait for page to load
kwargs: miscellaneous keyword args
Returns:
None if succeeded, else an error code
"""
chromebase.GetChromeRenderPane = GetChromeRenderPane
return chromebase.Scrape(urls, outdir, size, pos, timeout, kwargs) | [
"def",
"Scrape",
"(",
"urls",
",",
"outdir",
",",
"size",
",",
"pos",
",",
"timeout",
"=",
"20",
",",
"*",
"*",
"kwargs",
")",
":",
"chromebase",
".",
"GetChromeRenderPane",
"=",
"GetChromeRenderPane",
"return",
"chromebase",
".",
"Scrape",
"(",
"urls",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/site_compare/scrapers/chrome/chrome011010.py#L19-L35 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/Draw/SimilarityMaps.py | python | GetMorganFingerprint | (mol, atomId=-1, radius=2, fpType='bv', nBits=2048, useFeatures=False,
**kwargs) | return molFp | Calculates the Morgan fingerprint with the environments of atomId removed.
Parameters:
mol -- the molecule of interest
radius -- the maximum radius
fpType -- the type of Morgan fingerprint: 'count' or 'bv'
atomId -- the atom to remove the environments for (if -1, no environments is removed)
nBits -- the size of the bit vector (only for fpType = 'bv')
useFeatures -- if false: ConnectivityMorgan, if true: FeatureMorgan
any additional keyword arguments will be passed to the fingerprinting function. | Calculates the Morgan fingerprint with the environments of atomId removed. | [
"Calculates",
"the",
"Morgan",
"fingerprint",
"with",
"the",
"environments",
"of",
"atomId",
"removed",
"."
] | def GetMorganFingerprint(mol, atomId=-1, radius=2, fpType='bv', nBits=2048, useFeatures=False,
**kwargs):
"""
Calculates the Morgan fingerprint with the environments of atomId removed.
Parameters:
mol -- the molecule of interest
radius -- the maximum radius
fpType -- the type of Morgan fingerprint: 'count' or 'bv'
atomId -- the atom to remove the environments for (if -1, no environments is removed)
nBits -- the size of the bit vector (only for fpType = 'bv')
useFeatures -- if false: ConnectivityMorgan, if true: FeatureMorgan
any additional keyword arguments will be passed to the fingerprinting function.
"""
if fpType not in ['bv', 'count']:
raise ValueError("Unknown Morgan fingerprint type")
isBitVect = fpType == 'bv'
if not hasattr(mol, '_fpInfo'):
info = {}
# get the fingerprint & construct the bitmap template
if isBitVect:
molFp = rdMD.GetMorganFingerprintAsBitVect(mol, radius, nBits=nBits, useFeatures=useFeatures,
bitInfo=info, **kwargs)
bitmap = [DataStructs.ExplicitBitVect(nBits) for _ in range(mol.GetNumAtoms())]
else:
molFp = rdMD.GetMorganFingerprint(mol, radius, useFeatures=useFeatures, bitInfo=info,
**kwargs)
bitmap = [[] for _ in range(mol.GetNumAtoms())]
# construct the bit map
for bit, es in info.items():
for at1, rad in es:
if rad == 0: # for radius 0
if isBitVect:
bitmap[at1][bit] = 1
else:
bitmap[at1].append(bit)
else: # for radii > 0
env = Chem.FindAtomEnvironmentOfRadiusN(mol, rad, at1)
amap = {}
Chem.PathToSubmol(mol, env, atomMap=amap)
for at2 in amap.keys():
if isBitVect:
bitmap[at2][bit] = 1
else:
bitmap[at2].append(bit)
mol._fpInfo = (molFp, bitmap)
if atomId < 0:
return mol._fpInfo[0]
# remove the bits of atomId
if atomId >= mol.GetNumAtoms():
raise ValueError("atom index greater than number of atoms")
if len(mol._fpInfo) != 2:
raise ValueError("_fpInfo not set")
if isBitVect:
molFp = mol._fpInfo[0] ^ mol._fpInfo[1][atomId] # xor
else: # count
molFp = copy.deepcopy(mol._fpInfo[0])
# delete the bits with atomId
for bit in mol._fpInfo[1][atomId]:
molFp[bit] -= 1
return molFp | [
"def",
"GetMorganFingerprint",
"(",
"mol",
",",
"atomId",
"=",
"-",
"1",
",",
"radius",
"=",
"2",
",",
"fpType",
"=",
"'bv'",
",",
"nBits",
"=",
"2048",
",",
"useFeatures",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"fpType",
"not",
"in... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/Draw/SimilarityMaps.py#L346-L411 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/groupby/groupby.py | python | GroupBy.sum | (self) | return self.agg("sum") | Compute the column-wise sum of the values in each group. | Compute the column-wise sum of the values in each group. | [
"Compute",
"the",
"column",
"-",
"wise",
"sum",
"of",
"the",
"values",
"in",
"each",
"group",
"."
] | def sum(self):
"""Compute the column-wise sum of the values in each group."""
return self.agg("sum") | [
"def",
"sum",
"(",
"self",
")",
":",
"return",
"self",
".",
"agg",
"(",
"\"sum\"",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/groupby/groupby.py#L814-L816 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/trace.py | python | CoverageResults.update | (self, other) | Merge in the data from another CoverageResults | Merge in the data from another CoverageResults | [
"Merge",
"in",
"the",
"data",
"from",
"another",
"CoverageResults"
] | def update(self, other):
"""Merge in the data from another CoverageResults"""
counts = self.counts
calledfuncs = self.calledfuncs
callers = self.callers
other_counts = other.counts
other_calledfuncs = other.calledfuncs
other_callers = other.callers
for key in other_counts:
counts[key] = counts.get(key, 0) + other_counts[key]
for key in other_calledfuncs:
calledfuncs[key] = 1
for key in other_callers:
callers[key] = 1 | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"counts",
"=",
"self",
".",
"counts",
"calledfuncs",
"=",
"self",
".",
"calledfuncs",
"callers",
"=",
"self",
".",
"callers",
"other_counts",
"=",
"other",
".",
"counts",
"other_calledfuncs",
"=",
"othe... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/trace.py#L187-L203 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/nonlin.py | python | LowRankMatrix.rmatvec | (self, v) | return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs) | Evaluate w = M^H v | Evaluate w = M^H v | [
"Evaluate",
"w",
"=",
"M^H",
"v"
] | def rmatvec(self, v):
"""Evaluate w = M^H v"""
if self.collapsed is not None:
return np.dot(self.collapsed.T.conj(), v)
return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs) | [
"def",
"rmatvec",
"(",
"self",
",",
"v",
")",
":",
"if",
"self",
".",
"collapsed",
"is",
"not",
"None",
":",
"return",
"np",
".",
"dot",
"(",
"self",
".",
"collapsed",
".",
"T",
".",
"conj",
"(",
")",
",",
"v",
")",
"return",
"LowRankMatrix",
"."... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/nonlin.py#L754-L758 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | FileHistory.RemoveFileFromHistory | (*args, **kwargs) | return _misc_.FileHistory_RemoveFileFromHistory(*args, **kwargs) | RemoveFileFromHistory(self, int i) | RemoveFileFromHistory(self, int i) | [
"RemoveFileFromHistory",
"(",
"self",
"int",
"i",
")"
] | def RemoveFileFromHistory(*args, **kwargs):
"""RemoveFileFromHistory(self, int i)"""
return _misc_.FileHistory_RemoveFileFromHistory(*args, **kwargs) | [
"def",
"RemoveFileFromHistory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"FileHistory_RemoveFileFromHistory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L918-L920 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/train/train_thor/convert_utils.py | python | ConvertNetUtils.convert_to_thor_net | (self, net) | This interface is used to convert a network to thor layer network, in order to calculate and store the
second-order information matrix.
Note:
This interface is automatically called by the second-order optimizer thor.
Args:
net (Cell): Network to be trained by the second-order optimizer thor.
Supported Platforms:
``Ascend`` ``GPU``
Examples:
>>> ConvertNetUtils().convert_to_thor_net(net) | This interface is used to convert a network to thor layer network, in order to calculate and store the
second-order information matrix. | [
"This",
"interface",
"is",
"used",
"to",
"convert",
"a",
"network",
"to",
"thor",
"layer",
"network",
"in",
"order",
"to",
"calculate",
"and",
"store",
"the",
"second",
"-",
"order",
"information",
"matrix",
"."
] | def convert_to_thor_net(self, net):
"""
This interface is used to convert a network to thor layer network, in order to calculate and store the
second-order information matrix.
Note:
This interface is automatically called by the second-order optimizer thor.
Args:
net (Cell): Network to be trained by the second-order optimizer thor.
Supported Platforms:
``Ascend`` ``GPU``
Examples:
>>> ConvertNetUtils().convert_to_thor_net(net)
"""
net.update_cell_prefix()
self._convert_to_thor_net(net)
net.update_cell_type("second-order") | [
"def",
"convert_to_thor_net",
"(",
"self",
",",
"net",
")",
":",
"net",
".",
"update_cell_prefix",
"(",
")",
"self",
".",
"_convert_to_thor_net",
"(",
"net",
")",
"net",
".",
"update_cell_type",
"(",
"\"second-order\"",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/train_thor/convert_utils.py#L152-L173 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/doctools.py | python | DocPositionMgr.__init__ | (self) | Creates the position manager object | Creates the position manager object | [
"Creates",
"the",
"position",
"manager",
"object"
] | def __init__(self):
"""Creates the position manager object"""
super(DocPositionMgr, self).__init__()
# Attributes
self._init = False
self._book = None
self._records = dict() | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"DocPositionMgr",
",",
"self",
")",
".",
"__init__",
"(",
")",
"# Attributes",
"self",
".",
"_init",
"=",
"False",
"self",
".",
"_book",
"=",
"None",
"self",
".",
"_records",
"=",
"dict",
"(",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/doctools.py#L40-L47 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/tools/miniterm.py | python | Miniterm.set_rx_encoding | (self, encoding, errors='replace') | set encoding for received data | set encoding for received data | [
"set",
"encoding",
"for",
"received",
"data"
] | def set_rx_encoding(self, encoding, errors='replace'):
"""set encoding for received data"""
self.input_encoding = encoding
self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors) | [
"def",
"set_rx_encoding",
"(",
"self",
",",
"encoding",
",",
"errors",
"=",
"'replace'",
")",
":",
"self",
".",
"input_encoding",
"=",
"encoding",
"self",
".",
"rx_decoder",
"=",
"codecs",
".",
"getincrementaldecoder",
"(",
"encoding",
")",
"(",
"errors",
")... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/tools/miniterm.py#L405-L408 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/tools/graphviz.py | python | LoadEdges | (filename, targets) | return target_edges | Load the edges map from the dump file, and filter it to only
show targets in |targets| and their depedendents. | Load the edges map from the dump file, and filter it to only
show targets in |targets| and their depedendents. | [
"Load",
"the",
"edges",
"map",
"from",
"the",
"dump",
"file",
"and",
"filter",
"it",
"to",
"only",
"show",
"targets",
"in",
"|targets|",
"and",
"their",
"depedendents",
"."
] | def LoadEdges(filename, targets):
"""Load the edges map from the dump file, and filter it to only
show targets in |targets| and their depedendents."""
file = open('dump.json')
edges = json.load(file)
file.close()
# Copy out only the edges we're interested in from the full edge list.
target_edges = {}
to_visit = targets[:]
while to_visit:
src = to_visit.pop()
if src in target_edges:
continue
target_edges[src] = edges[src]
to_visit.extend(edges[src])
return target_edges | [
"def",
"LoadEdges",
"(",
"filename",
",",
"targets",
")",
":",
"file",
"=",
"open",
"(",
"'dump.json'",
")",
"edges",
"=",
"json",
".",
"load",
"(",
"file",
")",
"file",
".",
"close",
"(",
")",
"# Copy out only the edges we're interested in from the full edge li... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/tools/graphviz.py#L22-L40 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/edfplugin.py | python | EDFPlugin.get_runflags | (self, mode, interactive, scripted) | return (waitmode,newconsole) | Return the following boolean flags:
newconsole - the plugin should execute in a new console
waitmode - Execution should wait for the plugin to finish
executing | Return the following boolean flags: | [
"Return",
"the",
"following",
"boolean",
"flags",
":"
] | def get_runflags(self, mode, interactive, scripted):
"""
Return the following boolean flags:
newconsole - the plugin should execute in a new console
waitmode - Execution should wait for the plugin to finish
executing
"""
if interactive:
if not mode:
# Use the plugin's settings
mode = self.getConsoleMode()
else:
# Non-interactive mode must reuse the console
mode = util.CONSOLE_REUSE
if mode == util.CONSOLE_REUSE:
# Reusing implies no new console
newconsole = False
else:
newconsole = True
waitmode = True
# If non-scripted, interactive sessions that launch new consoles don't
# need to wait for plugins to finish. All other permutations do.
if interactive and not scripted and newconsole:
waitmode = False
return (waitmode,newconsole) | [
"def",
"get_runflags",
"(",
"self",
",",
"mode",
",",
"interactive",
",",
"scripted",
")",
":",
"if",
"interactive",
":",
"if",
"not",
"mode",
":",
"# Use the plugin's settings",
"mode",
"=",
"self",
".",
"getConsoleMode",
"(",
")",
"else",
":",
"# Non-inter... | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/edfplugin.py#L283-L311 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/animate.py | python | AnimationCtrl.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, Animation anim=NullAnimation,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=AC_DEFAULT_STYLE, String name=AnimationCtrlNameStr) -> AnimationCtrl | __init__(self, Window parent, int id=-1, Animation anim=NullAnimation,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=AC_DEFAULT_STYLE, String name=AnimationCtrlNameStr) -> AnimationCtrl | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Animation",
"anim",
"=",
"NullAnimation",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"AC_DEFAULT_STYLE",
"String",
"name",
"=",
"... | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Animation anim=NullAnimation,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=AC_DEFAULT_STYLE, String name=AnimationCtrlNameStr) -> AnimationCtrl
"""
_animate.AnimationCtrl_swiginit(self,_animate.new_AnimationCtrl(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_animate",
".",
"AnimationCtrl_swiginit",
"(",
"self",
",",
"_animate",
".",
"new_AnimationCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/animate.py#L193-L200 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/tracking/resource.py | python | CapturableResource.resource_handle | (self) | return self._resource_handle | Returns the resource handle associated with this Resource. | Returns the resource handle associated with this Resource. | [
"Returns",
"the",
"resource",
"handle",
"associated",
"with",
"this",
"Resource",
"."
] | def resource_handle(self):
"""Returns the resource handle associated with this Resource."""
if self._resource_handle is None:
with ops.device(self._resource_device):
self._resource_handle = self._create_resource()
return self._resource_handle | [
"def",
"resource_handle",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resource_handle",
"is",
"None",
":",
"with",
"ops",
".",
"device",
"(",
"self",
".",
"_resource_device",
")",
":",
"self",
".",
"_resource_handle",
"=",
"self",
".",
"_create_resource",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/tracking/resource.py#L171-L176 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/stcspellcheck.py | python | STCSpellCheck.setDefaultLanguage | (cls, lang) | Set the default language for spelling check.
The string should be in language locale format, e.g. en_US, ru, ru_RU,
eo, es_ES, etc. See L{getAvailableLanguages}.
@param lang: text string indicating the language | Set the default language for spelling check.
The string should be in language locale format, e.g. en_US, ru, ru_RU,
eo, es_ES, etc. See L{getAvailableLanguages}. | [
"Set",
"the",
"default",
"language",
"for",
"spelling",
"check",
".",
"The",
"string",
"should",
"be",
"in",
"language",
"locale",
"format",
"e",
".",
"g",
".",
"en_US",
"ru",
"ru_RU",
"eo",
"es_ES",
"etc",
".",
"See",
"L",
"{",
"getAvailableLanguages",
... | def setDefaultLanguage(cls, lang):
"""Set the default language for spelling check.
The string should be in language locale format, e.g. en_US, ru, ru_RU,
eo, es_ES, etc. See L{getAvailableLanguages}.
@param lang: text string indicating the language
"""
cls._spelling_lang = lang
cls._spelling_dict = cls._getDict(lang) | [
"def",
"setDefaultLanguage",
"(",
"cls",
",",
"lang",
")",
":",
"cls",
".",
"_spelling_lang",
"=",
"lang",
"cls",
".",
"_spelling_dict",
"=",
"cls",
".",
"_getDict",
"(",
"lang",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/stcspellcheck.py#L216-L225 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | PyTextDataObject.__init__ | (self, *args, **kwargs) | __init__(self, String text=EmptyString) -> PyTextDataObject
wx.PyTextDataObject is a version of `wx.TextDataObject` that is
Python-aware and knows how to reflect calls to its C++ virtual methods
to methods in the Python derived class. You should derive from this
class and overload `GetTextLength`, `GetText`, and `SetText` when you
want to be able to provide text on demand instead of preloading it
into the data object. | __init__(self, String text=EmptyString) -> PyTextDataObject | [
"__init__",
"(",
"self",
"String",
"text",
"=",
"EmptyString",
")",
"-",
">",
"PyTextDataObject"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, String text=EmptyString) -> PyTextDataObject
wx.PyTextDataObject is a version of `wx.TextDataObject` that is
Python-aware and knows how to reflect calls to its C++ virtual methods
to methods in the Python derived class. You should derive from this
class and overload `GetTextLength`, `GetText`, and `SetText` when you
want to be able to provide text on demand instead of preloading it
into the data object.
"""
_misc_.PyTextDataObject_swiginit(self,_misc_.new_PyTextDataObject(*args, **kwargs))
PyTextDataObject._setCallbackInfo(self, self, PyTextDataObject) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"PyTextDataObject_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_PyTextDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"PyTextDataObje... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5236-L5248 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | tools/coverage/gcda_clean.py | python | clean | (pull_id) | Clean.
Args:
pull_id (int): Pull id.
Returns:
None. | Clean. | [
"Clean",
"."
] | def clean(pull_id):
"""Clean.
Args:
pull_id (int): Pull id.
Returns:
None.
"""
changed = []
for file in get_files(pull_id):
changed.append('/paddle/build/{}.gcda'.format(file))
for parent, dirs, files in os.walk('/paddle/build/'):
for gcda in files:
if gcda.endswith('.gcda'):
trimmed = parent
# convert paddle/fluid/imperative/CMakeFiles/layer.dir/layer.cc.gcda
# to paddle/fluid/imperative/layer.cc.gcda
if trimmed.endswith('.dir'):
trimmed = os.path.dirname(trimmed)
if trimmed.endswith('CMakeFiles'):
trimmed = os.path.dirname(trimmed)
# remove no changed gcda
if os.path.join(trimmed, gcda) not in changed:
gcda = os.path.join(parent, gcda)
os.remove(gcda) | [
"def",
"clean",
"(",
"pull_id",
")",
":",
"changed",
"=",
"[",
"]",
"for",
"file",
"in",
"get_files",
"(",
"pull_id",
")",
":",
"changed",
".",
"append",
"(",
"'/paddle/build/{}.gcda'",
".",
"format",
"(",
"file",
")",
")",
"for",
"parent",
",",
"dirs"... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/coverage/gcda_clean.py#L69-L101 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/failure_handling/failure_handling.py | python | CoordinatedCheckpointManager.total_runs | (self) | return self._run_counter | Returns the number of times `CoordinatedCheckpointManager.run` is called.
This value tracks the number of all calls to
`CoordinatedCheckpointManager.run` including those before the program is
restarted and the training is restored. The user can compute their total
number of iterations by:
`coordinated_checkpoint_manager.run * number_of_steps_in_train_function`,
while for tf.distribute.MultiWorkerMirroredStrategy users,
`number_of_steps_in_train_function` should be one. | Returns the number of times `CoordinatedCheckpointManager.run` is called. | [
"Returns",
"the",
"number",
"of",
"times",
"CoordinatedCheckpointManager",
".",
"run",
"is",
"called",
"."
] | def total_runs(self):
"""Returns the number of times `CoordinatedCheckpointManager.run` is called.
This value tracks the number of all calls to
`CoordinatedCheckpointManager.run` including those before the program is
restarted and the training is restored. The user can compute their total
number of iterations by:
`coordinated_checkpoint_manager.run * number_of_steps_in_train_function`,
while for tf.distribute.MultiWorkerMirroredStrategy users,
`number_of_steps_in_train_function` should be one.
"""
return self._run_counter | [
"def",
"total_runs",
"(",
"self",
")",
":",
"return",
"self",
".",
"_run_counter"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/failure_handling/failure_handling.py#L184-L195 | |
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | plugins/maya/afanasy/meCheckTexturePaths.py | python | meCheckTexturePaths.getTextureName | (self, fileNodeName) | return fileTextureName, attrName | Missing DocString | Missing DocString | [
"Missing",
"DocString"
] | def getTextureName(self, fileNodeName):
"""Missing DocString
"""
fileTextureName = None
attrName = None
fileNodeType = cmds.objectType(fileNodeName)
if fileNodeType == 'file' \
or fileNodeType == 'mentalrayTexture' \
or fileNodeType == 'psdFileTex':
attrName = "fileTextureName"
elif fileNodeType == 'mentalrayIblShape':
attrName = "texture"
elif fileNodeType == 'aiImage':
attrName = "filename"
elif fileNodeType == 'imagePlane':
attrName = "imageName"
if attrName is not None:
fileTextureName = cmds.getAttr(fileNodeName + "." + attrName)
return fileTextureName, attrName | [
"def",
"getTextureName",
"(",
"self",
",",
"fileNodeName",
")",
":",
"fileTextureName",
"=",
"None",
"attrName",
"=",
"None",
"fileNodeType",
"=",
"cmds",
".",
"objectType",
"(",
"fileNodeName",
")",
"if",
"fileNodeType",
"==",
"'file'",
"or",
"fileNodeType",
... | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/plugins/maya/afanasy/meCheckTexturePaths.py#L336-L356 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | v8_5_1/tools/grokdump.py | python | InspectionShell.do_do_map | (self, address) | Print a descriptor array in a readable format. | Print a descriptor array in a readable format. | [
"Print",
"a",
"descriptor",
"array",
"in",
"a",
"readable",
"format",
"."
] | def do_do_map(self, address):
"""
Print a descriptor array in a readable format.
"""
start = int(address, 16)
if ((start & 1) == 1): start = start - 1
Map(self.heap, None, start).Print(Printer()) | [
"def",
"do_do_map",
"(",
"self",
",",
"address",
")",
":",
"start",
"=",
"int",
"(",
"address",
",",
"16",
")",
"if",
"(",
"(",
"start",
"&",
"1",
")",
"==",
"1",
")",
":",
"start",
"=",
"start",
"-",
"1",
"Map",
"(",
"self",
".",
"heap",
","... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_5_1/tools/grokdump.py#L2964-L2970 | ||
facebookresearch/ELF | 1f790173095cd910976d9f651b80beb872ec5d12 | vendor/pybind11/tools/clang/cindex.py | python | CursorKind.is_statement | (self) | return conf.lib.clang_isStatement(self) | Test if this is a statement kind. | Test if this is a statement kind. | [
"Test",
"if",
"this",
"is",
"a",
"statement",
"kind",
"."
] | def is_statement(self):
"""Test if this is a statement kind."""
return conf.lib.clang_isStatement(self) | [
"def",
"is_statement",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isStatement",
"(",
"self",
")"
] | https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L588-L590 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/popen2.py | python | Popen3.poll | (self, _deadstate=None) | return self.sts | Return the exit status of the child process if it has finished,
or -1 if it hasn't finished yet. | Return the exit status of the child process if it has finished,
or -1 if it hasn't finished yet. | [
"Return",
"the",
"exit",
"status",
"of",
"the",
"child",
"process",
"if",
"it",
"has",
"finished",
"or",
"-",
"1",
"if",
"it",
"hasn",
"t",
"finished",
"yet",
"."
] | def poll(self, _deadstate=None):
"""Return the exit status of the child process if it has finished,
or -1 if it hasn't finished yet."""
if self.sts < 0:
try:
pid, sts = os.waitpid(self.pid, os.WNOHANG)
# pid will be 0 if self.pid hasn't terminated
if pid == self.pid:
self.sts = sts
except os.error:
if _deadstate is not None:
self.sts = _deadstate
return self.sts | [
"def",
"poll",
"(",
"self",
",",
"_deadstate",
"=",
"None",
")",
":",
"if",
"self",
".",
"sts",
"<",
"0",
":",
"try",
":",
"pid",
",",
"sts",
"=",
"os",
".",
"waitpid",
"(",
"self",
".",
"pid",
",",
"os",
".",
"WNOHANG",
")",
"# pid will be 0 if ... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/popen2.py#L91-L103 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/services_api/send.py | python | Send.__init__ | (self, host, port=6544) | INPUT:
======
host: Must be set and is the hostname or IP address of the backend
or frontend.
port: Only needed if the backend is using a different port
(unlikely) or set to the frontend port, which is usually
6547. Defaults to 6544. | INPUT:
====== | [
"INPUT",
":",
"======"
] | def __init__(self, host, port=6544):
"""
INPUT:
======
host: Must be set and is the hostname or IP address of the backend
or frontend.
port: Only needed if the backend is using a different port
(unlikely) or set to the frontend port, which is usually
6547. Defaults to 6544.
"""
if not host:
raise RuntimeError('Missing host argument')
self.host = host
self.port = port
self.endpoint = None
self.postdata = None
self.rest = None
self.opts = None
self.session = None
self.server_version = 'Set to MythTV version after calls to send()'
self.logger = logging.getLogger(__name__)
logging.getLogger(__name__).addHandler(logging.NullHandler()) | [
"def",
"__init__",
"(",
"self",
",",
"host",
",",
"port",
"=",
"6544",
")",
":",
"if",
"not",
"host",
":",
"raise",
"RuntimeError",
"(",
"'Missing host argument'",
")",
"self",
".",
"host",
"=",
"host",
"self",
".",
"port",
"=",
"port",
"self",
".",
... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/services_api/send.py#L35-L61 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | openmp/runtime/tools/summarizeStats.py | python | uselessValues | (l) | return [not p for p in usefulValues(l)] | I.e. values which are null or zero | I.e. values which are null or zero | [
"I",
".",
"e",
".",
"values",
"which",
"are",
"null",
"or",
"zero"
] | def uselessValues(l):
"""I.e. values which are null or zero"""
return [not p for p in usefulValues(l)] | [
"def",
"uselessValues",
"(",
"l",
")",
":",
"return",
"[",
"not",
"p",
"for",
"p",
"in",
"usefulValues",
"(",
"l",
")",
"]"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/openmp/runtime/tools/summarizeStats.py#L153-L155 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/skia/tools/skp/webpages_playback.py | python | SkPicturePlayback.__init__ | (self, parse_options) | Constructs a SkPicturePlayback BuildStep instance. | Constructs a SkPicturePlayback BuildStep instance. | [
"Constructs",
"a",
"SkPicturePlayback",
"BuildStep",
"instance",
"."
] | def __init__(self, parse_options):
"""Constructs a SkPicturePlayback BuildStep instance."""
assert parse_options.browser_executable, 'Must specify --browser_executable'
self._browser_executable = parse_options.browser_executable
self._browser_args = '--disable-setuid-sandbox'
if parse_options.browser_extra_args:
self._browser_args = '%s %s' % (
self._browser_args, parse_options.browser_extra_args)
self._chrome_page_sets_path = os.path.join(parse_options.chrome_src_path,
CHROMIUM_PAGE_SETS_PATH)
self._all_page_sets_specified = parse_options.page_sets == 'all'
self._page_sets = self._ParsePageSets(parse_options.page_sets)
self._record = parse_options.record
self._skia_tools = parse_options.skia_tools
self._non_interactive = parse_options.non_interactive
self._upload = parse_options.upload
self._skp_prefix = parse_options.skp_prefix
data_store_location = parse_options.data_store
if data_store_location.startswith(gs_utils.GS_PREFIX):
self.gs = GoogleStorageDataStore(data_store_location)
else:
self.gs = LocalFileSystemDataStore(data_store_location)
self._alternate_upload_dir = parse_options.alternate_upload_dir
self._telemetry_binaries_dir = os.path.join(parse_options.chrome_src_path,
'tools', 'perf')
self._local_skp_dir = os.path.join(
parse_options.output_dir, ROOT_PLAYBACK_DIR_NAME, SKPICTURES_DIR_NAME)
self._local_record_webpages_archive_dir = os.path.join(
parse_options.output_dir, ROOT_PLAYBACK_DIR_NAME, 'webpages_archive')
# List of SKP files generated by this script.
self._skp_files = [] | [
"def",
"__init__",
"(",
"self",
",",
"parse_options",
")",
":",
"assert",
"parse_options",
".",
"browser_executable",
",",
"'Must specify --browser_executable'",
"self",
".",
"_browser_executable",
"=",
"parse_options",
".",
"browser_executable",
"self",
".",
"_browser_... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/tools/skp/webpages_playback.py#L137-L171 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-blocks/python/blocks/stream_to_vector_decimator.py | python | stream_to_vector_decimator.set_sample_rate | (self, sample_rate) | Set the new sampling rate and update the decimator.
Args:
sample_rate: the new rate | Set the new sampling rate and update the decimator. | [
"Set",
"the",
"new",
"sampling",
"rate",
"and",
"update",
"the",
"decimator",
"."
] | def set_sample_rate(self, sample_rate):
"""
Set the new sampling rate and update the decimator.
Args:
sample_rate: the new rate
"""
self._sample_rate = sample_rate
self._update_decimator() | [
"def",
"set_sample_rate",
"(",
"self",
",",
"sample_rate",
")",
":",
"self",
".",
"_sample_rate",
"=",
"sample_rate",
"self",
".",
"_update_decimator",
"(",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-blocks/python/blocks/stream_to_vector_decimator.py#L44-L52 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBProcess.ReadUnsignedFromMemory | (self, *args) | return _lldb.SBProcess_ReadUnsignedFromMemory(self, *args) | Reads an unsigned integer from memory given a byte size and an address.
Returns the unsigned integer that was read. Example:
# Read a 4 byte unsigned integer from address 0x1000
error = lldb.SBError()
uint = ReadUnsignedFromMemory(0x1000, 4, error)
if error.Success():
print('integer: %u' % uint)
else
print('error: ', error) | Reads an unsigned integer from memory given a byte size and an address.
Returns the unsigned integer that was read. Example: | [
"Reads",
"an",
"unsigned",
"integer",
"from",
"memory",
"given",
"a",
"byte",
"size",
"and",
"an",
"address",
".",
"Returns",
"the",
"unsigned",
"integer",
"that",
"was",
"read",
".",
"Example",
":"
] | def ReadUnsignedFromMemory(self, *args):
"""
Reads an unsigned integer from memory given a byte size and an address.
Returns the unsigned integer that was read. Example:
# Read a 4 byte unsigned integer from address 0x1000
error = lldb.SBError()
uint = ReadUnsignedFromMemory(0x1000, 4, error)
if error.Success():
print('integer: %u' % uint)
else
print('error: ', error)
"""
return _lldb.SBProcess_ReadUnsignedFromMemory(self, *args) | [
"def",
"ReadUnsignedFromMemory",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBProcess_ReadUnsignedFromMemory",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7215-L7229 | |
cocos-creator/engine-native | 984c4c9f5838253313b44ccd429bd8fac4ec8a6a | tools/bindings-generator/clang/cindex.py | python | TranslationUnit.get_tokens | (self, locations=None, extent=None) | return TokenGroup.get_tokens(self, extent) | Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined. | Obtain tokens in this translation unit. | [
"Obtain",
"tokens",
"in",
"this",
"translation",
"unit",
"."
] | def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
"""
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent) | [
"def",
"get_tokens",
"(",
"self",
",",
"locations",
"=",
"None",
",",
"extent",
"=",
"None",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"extent",
"=",
"SourceRange",
"(",
"start",
"=",
"locations",
"[",
"0",
"]",
",",
"end",
"=",
"locatio... | https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L3076-L3087 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/drivers/lidar/velodyne/parser/scripts/gen_calibration.py | python | addLaserCalibration | (laser_num, key, val) | Define key and corresponding value for laser_num | Define key and corresponding value for laser_num | [
"Define",
"key",
"and",
"corresponding",
"value",
"for",
"laser_num"
] | def addLaserCalibration(laser_num, key, val):
"""Define key and corresponding value for laser_num"""
global calibration
if laser_num < len(calibration['lasers']):
calibration['lasers'][laser_num][key] = val
else:
calibration['lasers'].append({key: val}) | [
"def",
"addLaserCalibration",
"(",
"laser_num",
",",
"key",
",",
"val",
")",
":",
"global",
"calibration",
"if",
"laser_num",
"<",
"len",
"(",
"calibration",
"[",
"'lasers'",
"]",
")",
":",
"calibration",
"[",
"'lasers'",
"]",
"[",
"laser_num",
"]",
"[",
... | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/drivers/lidar/velodyne/parser/scripts/gen_calibration.py#L119-L126 | ||
CaoWGG/TensorRT-CenterNet | f949252e37b51e60f873808f46d3683f15735e79 | onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py | python | TranslationUnit.save | (self, filename) | Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to. | Saves the TranslationUnit to a file. | [
"Saves",
"the",
"TranslationUnit",
"to",
"a",
"file",
"."
] | def save(self, filename):
"""Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to.
"""
options = conf.lib.clang_defaultSaveOptions(self)
result = int(conf.lib.clang_saveTranslationUnit(self, filename,
options))
if result != 0:
raise TranslationUnitSaveError(result,
'Error saving TranslationUnit.') | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"options",
"=",
"conf",
".",
"lib",
".",
"clang_defaultSaveOptions",
"(",
"self",
")",
"result",
"=",
"int",
"(",
"conf",
".",
"lib",
".",
"clang_saveTranslationUnit",
"(",
"self",
",",
"filename",
"... | https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L2715-L2735 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/saved_model/main_op_impl.py | python | main_op | () | return control_flow_ops.group(init, init_local, init_tables) | Returns a main op to init variables and tables.
Returns the main op including the group of ops that initializes all
variables, initializes local variables and initialize all tables.
Returns:
The set of ops to be run as part of the main op upon the load operation. | Returns a main op to init variables and tables. | [
"Returns",
"a",
"main",
"op",
"to",
"init",
"variables",
"and",
"tables",
"."
] | def main_op():
"""Returns a main op to init variables and tables.
Returns the main op including the group of ops that initializes all
variables, initializes local variables and initialize all tables.
Returns:
The set of ops to be run as part of the main op upon the load operation.
"""
init = variables.global_variables_initializer()
init_local = variables.local_variables_initializer()
init_tables = lookup_ops.tables_initializer()
return control_flow_ops.group(init, init_local, init_tables) | [
"def",
"main_op",
"(",
")",
":",
"init",
"=",
"variables",
".",
"global_variables_initializer",
"(",
")",
"init_local",
"=",
"variables",
".",
"local_variables_initializer",
"(",
")",
"init_tables",
"=",
"lookup_ops",
".",
"tables_initializer",
"(",
")",
"return",... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/saved_model/main_op_impl.py#L27-L39 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/monitored_session.py | python | _HookedSession.__init__ | (self, sess, hooks) | Initializes a _HookedSession object.
Args:
sess: A `tf.compat.v1.Session` or a `_WrappedSession` object.
hooks: An iterable of `SessionRunHook' objects. | Initializes a _HookedSession object. | [
"Initializes",
"a",
"_HookedSession",
"object",
"."
] | def __init__(self, sess, hooks):
"""Initializes a _HookedSession object.
Args:
sess: A `tf.compat.v1.Session` or a `_WrappedSession` object.
hooks: An iterable of `SessionRunHook' objects.
"""
_WrappedSession.__init__(self, sess)
self._hooks = hooks
self._should_stop = False | [
"def",
"__init__",
"(",
"self",
",",
"sess",
",",
"hooks",
")",
":",
"_WrappedSession",
".",
"__init__",
"(",
"self",
",",
"sess",
")",
"self",
".",
"_hooks",
"=",
"hooks",
"self",
".",
"_should_stop",
"=",
"False"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/monitored_session.py#L1380-L1390 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/ccompiler.py | python | CCompiler.set_library_dirs | (self, dirs) | Set the list of library search directories to 'dirs' (a list of
strings). This does not affect any standard library search path
that the linker may search by default. | Set the list of library search directories to 'dirs' (a list of
strings). This does not affect any standard library search path
that the linker may search by default. | [
"Set",
"the",
"list",
"of",
"library",
"search",
"directories",
"to",
"dirs",
"(",
"a",
"list",
"of",
"strings",
")",
".",
"This",
"does",
"not",
"affect",
"any",
"standard",
"library",
"search",
"path",
"that",
"the",
"linker",
"may",
"search",
"by",
"d... | def set_library_dirs(self, dirs):
"""Set the list of library search directories to 'dirs' (a list of
strings). This does not affect any standard library search path
that the linker may search by default.
"""
self.library_dirs = dirs[:] | [
"def",
"set_library_dirs",
"(",
"self",
",",
"dirs",
")",
":",
"self",
".",
"library_dirs",
"=",
"dirs",
"[",
":",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/ccompiler.py#L280-L285 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/app.py | python | CApp.LoadMainFrame | (self) | Create the main applications frame | Create the main applications frame | [
"Create",
"the",
"main",
"applications",
"frame"
] | def LoadMainFrame(self):
" Create the main applications frame "
self.frame = self.CreateMainFrame()
self.SetMainFrame(self.frame)
self.frame.LoadFrame(win32ui.IDR_MAINFRAME, win32con.WS_OVERLAPPEDWINDOW)
self.frame.DragAcceptFiles() # we can accept these.
self.frame.ShowWindow(win32ui.GetInitialStateRequest())
self.frame.UpdateWindow()
self.HookCommands() | [
"def",
"LoadMainFrame",
"(",
"self",
")",
":",
"self",
".",
"frame",
"=",
"self",
".",
"CreateMainFrame",
"(",
")",
"self",
".",
"SetMainFrame",
"(",
"self",
".",
"frame",
")",
"self",
".",
"frame",
".",
"LoadFrame",
"(",
"win32ui",
".",
"IDR_MAINFRAME",... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/app.py#L190-L198 | ||
Kitt-AI/snowboy | c9ff036e2ef3f9c422a3b8c9a01361dbad7a9bd4 | examples/Python3/snowboydecoder.py | python | HotwordDetector.start | (self, detected_callback=play_audio_file,
interrupt_check=lambda: False,
sleep_time=0.03,
audio_recorder_callback=None,
silent_count_threshold=15,
recording_timeout=100) | Start the voice detector. For every `sleep_time` second it checks the
audio buffer for triggering keywords. If detected, then call
corresponding function in `detected_callback`, which can be a single
function (single model) or a list of callback functions (multiple
models). Every loop it also calls `interrupt_check` -- if it returns
True, then breaks from the loop and return.
:param detected_callback: a function or list of functions. The number of
items must match the number of models in
`decoder_model`.
:param interrupt_check: a function that returns True if the main loop
needs to stop.
:param float sleep_time: how much time in second every loop waits.
:param audio_recorder_callback: if specified, this will be called after
a keyword has been spoken and after the
phrase immediately after the keyword has
been recorded. The function will be
passed the name of the file where the
phrase was recorded.
:param silent_count_threshold: indicates how long silence must be heard
to mark the end of a phrase that is
being recorded.
:param recording_timeout: limits the maximum length of a recording.
:return: None | Start the voice detector. For every `sleep_time` second it checks the
audio buffer for triggering keywords. If detected, then call
corresponding function in `detected_callback`, which can be a single
function (single model) or a list of callback functions (multiple
models). Every loop it also calls `interrupt_check` -- if it returns
True, then breaks from the loop and return. | [
"Start",
"the",
"voice",
"detector",
".",
"For",
"every",
"sleep_time",
"second",
"it",
"checks",
"the",
"audio",
"buffer",
"for",
"triggering",
"keywords",
".",
"If",
"detected",
"then",
"call",
"corresponding",
"function",
"in",
"detected_callback",
"which",
"... | def start(self, detected_callback=play_audio_file,
interrupt_check=lambda: False,
sleep_time=0.03,
audio_recorder_callback=None,
silent_count_threshold=15,
recording_timeout=100):
"""
Start the voice detector. For every `sleep_time` second it checks the
audio buffer for triggering keywords. If detected, then call
corresponding function in `detected_callback`, which can be a single
function (single model) or a list of callback functions (multiple
models). Every loop it also calls `interrupt_check` -- if it returns
True, then breaks from the loop and return.
:param detected_callback: a function or list of functions. The number of
items must match the number of models in
`decoder_model`.
:param interrupt_check: a function that returns True if the main loop
needs to stop.
:param float sleep_time: how much time in second every loop waits.
:param audio_recorder_callback: if specified, this will be called after
a keyword has been spoken and after the
phrase immediately after the keyword has
been recorded. The function will be
passed the name of the file where the
phrase was recorded.
:param silent_count_threshold: indicates how long silence must be heard
to mark the end of a phrase that is
being recorded.
:param recording_timeout: limits the maximum length of a recording.
:return: None
"""
self._running = True
def audio_callback(in_data, frame_count, time_info, status):
self.ring_buffer.extend(in_data)
play_data = chr(0) * len(in_data)
return play_data, pyaudio.paContinue
with no_alsa_error():
self.audio = pyaudio.PyAudio()
self.stream_in = self.audio.open(
input=True, output=False,
format=self.audio.get_format_from_width(
self.detector.BitsPerSample() / 8),
channels=self.detector.NumChannels(),
rate=self.detector.SampleRate(),
frames_per_buffer=2048,
stream_callback=audio_callback)
if interrupt_check():
logger.debug("detect voice return")
return
tc = type(detected_callback)
if tc is not list:
detected_callback = [detected_callback]
if len(detected_callback) == 1 and self.num_hotwords > 1:
detected_callback *= self.num_hotwords
assert self.num_hotwords == len(detected_callback), \
"Error: hotwords in your models (%d) do not match the number of " \
"callbacks (%d)" % (self.num_hotwords, len(detected_callback))
logger.debug("detecting...")
state = "PASSIVE"
while self._running is True:
if interrupt_check():
logger.debug("detect voice break")
break
data = self.ring_buffer.get()
if len(data) == 0:
time.sleep(sleep_time)
continue
status = self.detector.RunDetection(data)
if status == -1:
logger.warning("Error initializing streams or reading audio data")
#small state machine to handle recording of phrase after keyword
if state == "PASSIVE":
if status > 0: #key word found
self.recordedData = []
self.recordedData.append(data)
silentCount = 0
recordingCount = 0
message = "Keyword " + str(status) + " detected at time: "
message += time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(time.time()))
logger.info(message)
callback = detected_callback[status-1]
if callback is not None:
callback()
if audio_recorder_callback is not None:
state = "ACTIVE"
continue
elif state == "ACTIVE":
stopRecording = False
if recordingCount > recording_timeout:
stopRecording = True
elif status == -2: #silence found
if silentCount > silent_count_threshold:
stopRecording = True
else:
silentCount = silentCount + 1
elif status == 0: #voice found
silentCount = 0
if stopRecording == True:
fname = self.saveMessage()
audio_recorder_callback(fname)
state = "PASSIVE"
continue
recordingCount = recordingCount + 1
self.recordedData.append(data)
logger.debug("finished.") | [
"def",
"start",
"(",
"self",
",",
"detected_callback",
"=",
"play_audio_file",
",",
"interrupt_check",
"=",
"lambda",
":",
"False",
",",
"sleep_time",
"=",
"0.03",
",",
"audio_recorder_callback",
"=",
"None",
",",
"silent_count_threshold",
"=",
"15",
",",
"recor... | https://github.com/Kitt-AI/snowboy/blob/c9ff036e2ef3f9c422a3b8c9a01361dbad7a9bd4/examples/Python3/snowboydecoder.py#L128-L248 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/logging/handlers.py | python | WatchedFileHandler.emit | (self, record) | Emit a record.
If underlying file has changed, reopen the file before emitting the
record to it. | Emit a record. | [
"Emit",
"a",
"record",
"."
] | def emit(self, record):
"""
Emit a record.
If underlying file has changed, reopen the file before emitting the
record to it.
"""
self.reopenIfNeeded()
logging.FileHandler.emit(self, record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"reopenIfNeeded",
"(",
")",
"logging",
".",
"FileHandler",
".",
"emit",
"(",
"self",
",",
"record",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/handlers.py#L509-L517 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/urllib/request.py | python | URLopener.open_local_file | (self, url) | Use local file. | Use local file. | [
"Use",
"local",
"file",
"."
] | def open_local_file(self, url):
"""Use local file."""
import email.utils
import mimetypes
host, file = splithost(url)
localname = url2pathname(file)
try:
stats = os.stat(localname)
except OSError as e:
raise URLError(e.strerror, e.filename)
size = stats.st_size
modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
mtype = mimetypes.guess_type(url)[0]
headers = email.message_from_string(
'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
(mtype or 'text/plain', size, modified))
if not host:
urlfile = file
if file[:1] == '/':
urlfile = 'file://' + file
return addinfourl(open(localname, 'rb'), headers, urlfile)
host, port = splitport(host)
if (not port
and socket.gethostbyname(host) in ((localhost(),) + thishost())):
urlfile = file
if file[:1] == '/':
urlfile = 'file://' + file
elif file[:2] == './':
raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
return addinfourl(open(localname, 'rb'), headers, urlfile)
raise URLError('local file error: not on local host') | [
"def",
"open_local_file",
"(",
"self",
",",
"url",
")",
":",
"import",
"email",
".",
"utils",
"import",
"mimetypes",
"host",
",",
"file",
"=",
"splithost",
"(",
"url",
")",
"localname",
"=",
"url2pathname",
"(",
"file",
")",
"try",
":",
"stats",
"=",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/urllib/request.py#L2009-L2039 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/core/pipe.py | python | LoggerPipe.run | (self) | Read the output from 'pipe_out' and logs each line to 'logger'. | Read the output from 'pipe_out' and logs each line to 'logger'. | [
"Read",
"the",
"output",
"from",
"pipe_out",
"and",
"logs",
"each",
"line",
"to",
"logger",
"."
] | def run(self):
"""Read the output from 'pipe_out' and logs each line to 'logger'."""
with self.__lock:
self.__started = True
self.__condition.notify_all()
# Close the pipe when finished reading all of the output.
with self.__pipe_out:
# Avoid buffering the output from the pipe.
for line in iter(self.__pipe_out.readline, b""):
# Replace null bytes in the output of the subprocess with a literal backslash ('\')
# followed by a literal zero ('0') so tools like grep don't treat resmoke.py's
# output as binary data.
line = line.replace(b"\0", b"\\0")
# Convert the output of the process from a bytestring to a UTF-8 string, and replace
# any characters that cannot be decoded with the official Unicode replacement
# character, U+FFFD. The log messages of MongoDB processes are not always valid
# UTF-8 sequences. See SERVER-7506.
line = line.decode("utf-8", "replace")
self.__logger.log(self.__level, line.rstrip())
with self.__lock:
self.__finished = True
self.__condition.notify_all() | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"self",
".",
"__lock",
":",
"self",
".",
"__started",
"=",
"True",
"self",
".",
"__condition",
".",
"notify_all",
"(",
")",
"# Close the pipe when finished reading all of the output.",
"with",
"self",
".",
"__pipe_out... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/core/pipe.py#L42-L67 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py | python | ensure_str | (s, encoding="utf-8", errors="strict") | return s | Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str` | Coerce *s* to `str`. | [
"Coerce",
"*",
"s",
"*",
"to",
"str",
"."
] | def ensure_str(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s | [
"def",
"ensure_str",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"text_type",
",",
"binary_type",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%... | 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/urllib3/packages/six.py#L939-L956 | |
Illumina/strelka | d7377443b62319f7c7bd70c241c4b2df3459e29a | scratch/util/mergeScoringModels.py | python | update | (d, u) | return d | recursive merge of u into d | recursive merge of u into d | [
"recursive",
"merge",
"of",
"u",
"into",
"d"
] | def update(d, u):
"""
recursive merge of u into d
"""
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
assert(k not in d)
d[k] = u[k]
return d | [
"def",
"update",
"(",
"d",
",",
"u",
")",
":",
"for",
"k",
",",
"v",
"in",
"u",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"Mapping",
")",
":",
"r",
"=",
"update",
"(",
"d",
".",
"get",
"(",
"k",
... | https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/scratch/util/mergeScoringModels.py#L26-L37 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/bindings/python/llvm/common.py | python | LLVMObject.take_ownership | (self, obj) | Take ownership of another object.
When you take ownership of another object, you are responsible for
destroying that object. In addition, a reference to that object is
placed inside this object so the Python garbage collector will not
collect the object while it is still alive in libLLVM.
This method should likely only be called from within modules inside
this package. | Take ownership of another object. | [
"Take",
"ownership",
"of",
"another",
"object",
"."
] | def take_ownership(self, obj):
"""Take ownership of another object.
When you take ownership of another object, you are responsible for
destroying that object. In addition, a reference to that object is
placed inside this object so the Python garbage collector will not
collect the object while it is still alive in libLLVM.
This method should likely only be called from within modules inside
this package.
"""
assert isinstance(obj, LLVMObject)
self._owned_objects.append(obj)
obj._self_owned = False | [
"def",
"take_ownership",
"(",
"self",
",",
"obj",
")",
":",
"assert",
"isinstance",
"(",
"obj",
",",
"LLVMObject",
")",
"self",
".",
"_owned_objects",
".",
"append",
"(",
"obj",
")",
"obj",
".",
"_self_owned",
"=",
"False"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/bindings/python/llvm/common.py#L44-L58 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/printing.py | python | PrintHandler.on_print_status_changed | (self, operation) | Print Operation Status Changed | Print Operation Status Changed | [
"Print",
"Operation",
"Status",
"Changed"
] | def on_print_status_changed(self, operation):
"""Print Operation Status Changed"""
if operation.is_finished(): active_prints.remove(operation) | [
"def",
"on_print_status_changed",
"(",
"self",
",",
"operation",
")",
":",
"if",
"operation",
".",
"is_finished",
"(",
")",
":",
"active_prints",
".",
"remove",
"(",
"operation",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/printing.py#L75-L77 | ||
lyxok1/Tiny-DSOD | 94d15450699bea0dd3720e75e2d273e476174fba | scripts/cpp_lint.py | python | CheckForNewlineAtEOF | (filename, lines, error) | Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error if there is no newline char at the end of the file. | [
"Logs",
"an",
"error",
"if",
"there",
"is",
"no",
"newline",
"char",
"at",
"the",
"end",
"of",
"the",
"file",
"."
] | def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.') | [
"def",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# The array lines() was created by adding two newlines to the",
"# original file (go figure), then splitting on \\n.",
"# To verify that the file ends in \\n, we just have to make sure the",
"# last-but-... | https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/scripts/cpp_lint.py#L1508-L1523 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/libmintspointgrp.py | python | SymmetryOperation.__str__ | (self, out=None) | print the matrix | print the matrix | [
"print",
"the",
"matrix"
] | def __str__(self, out=None):
"""print the matrix"""
text = " 1 2 3\n"
text += " 1 "
text += "%10.7f " % (self.d[0][0])
text += "%10.7f " % (self.d[0][1])
text += "%10.7f \n" % (self.d[0][2])
text += " 2 "
text += "%10.7f " % (self.d[1][0])
text += "%10.7f " % (self.d[1][1])
text += "%10.7f \n" % (self.d[1][2])
text += " 3 "
text += "%10.7f " % (self.d[2][0])
text += "%10.7f " % (self.d[2][1])
text += "%10.7f \n" % (self.d[2][2])
text += "bits_ = %d\n" % (self.bits)
if out is None:
return text
else:
with open(out, mode='w') as handle:
handle.write(text) | [
"def",
"__str__",
"(",
"self",
",",
"out",
"=",
"None",
")",
":",
"text",
"=",
"\" 1 2 3\\n\"",
"text",
"+=",
"\" 1 \"",
"text",
"+=",
"\"%10.7f \"",
"%",
"(",
"self",
".",
"d",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"text",
"+="... | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintspointgrp.py#L358-L380 | ||
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/ultisnips/plugin/UltiSnips/_vim.py | python | VimBuffer.current_line_splitted | (self) | return before, after | Returns the text before and after the cursor as a tuple. | Returns the text before and after the cursor as a tuple. | [
"Returns",
"the",
"text",
"before",
"and",
"after",
"the",
"cursor",
"as",
"a",
"tuple",
"."
] | def current_line_splitted(self):
"""Returns the text before and after the cursor as a tuple."""
# Note: we want byte position here
lineno, col = vim.current.window.cursor
line = vim.current.line
before, after = as_unicode(line[:col]), as_unicode(line[col:])
return before, after | [
"def",
"current_line_splitted",
"(",
"self",
")",
":",
"# Note: we want byte position here",
"lineno",
",",
"col",
"=",
"vim",
".",
"current",
".",
"window",
".",
"cursor",
"line",
"=",
"vim",
".",
"current",
".",
"line",
"before",
",",
"after",
"=",
"as_uni... | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/ultisnips/plugin/UltiSnips/_vim.py#L37-L44 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | HandWrittenHandler.WriteImmediateFormatTest | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteImmediateFormatTest(self, func, file):
"""Overrriden from TypeHandler."""
file.Write("// TODO(gman): Write test for %s\n" % func.name) | [
"def",
"WriteImmediateFormatTest",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"file",
".",
"Write",
"(",
"\"// TODO(gman): Write test for %s\\n\"",
"%",
"func",
".",
"name",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3581-L3583 | ||
apache/trafficserver | 92d238a8fad483c58bc787f784b2ceae73aed532 | plugins/experimental/traffic_dump/post_process.py | python | parse_json | (replay_file) | return parsed_json | Open and parse the replay_file.
Args:
replay_file (string) The file with JSON content to parse.
Return:
The json package parsed JSON file or None if there was a problem
parsing the file. | Open and parse the replay_file. | [
"Open",
"and",
"parse",
"the",
"replay_file",
"."
] | def parse_json(replay_file):
""" Open and parse the replay_file.
Args:
replay_file (string) The file with JSON content to parse.
Return:
The json package parsed JSON file or None if there was a problem
parsing the file.
"""
try:
fd = open(replay_file, 'r')
except Exception as e:
logging.exception("Failed to open %s.", replay_file)
raise ParseJSONError(e)
try:
parsed_json = json.load(fd)
except Exception as e:
message = e.msg.split(':')[0]
logging.error("Failed to load %s as a JSON object: %s", replay_file, e)
raise ParseJSONError(message)
return parsed_json | [
"def",
"parse_json",
"(",
"replay_file",
")",
":",
"try",
":",
"fd",
"=",
"open",
"(",
"replay_file",
",",
"'r'",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"exception",
"(",
"\"Failed to open %s.\"",
",",
"replay_file",
")",
"raise",
"Par... | https://github.com/apache/trafficserver/blob/92d238a8fad483c58bc787f784b2ceae73aed532/plugins/experimental/traffic_dump/post_process.py#L201-L224 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/image_tool.py | python | ImageTool.random_crop_resize | (self, patch, inplace=True) | Crop of the image at a random size between 0.08 to 1 of input image
and random aspect ratio between 3/4 to 4/3.
This crop is then resized to the given patch size.
Args:
patch(tuple): width and height of the patch
inplace(Boolean): replace the internal images list with the patches
if True; otherwise, return the patches. | Crop of the image at a random size between 0.08 to 1 of input image
and random aspect ratio between 3/4 to 4/3.
This crop is then resized to the given patch size. | [
"Crop",
"of",
"the",
"image",
"at",
"a",
"random",
"size",
"between",
"0",
".",
"08",
"to",
"1",
"of",
"input",
"image",
"and",
"random",
"aspect",
"ratio",
"between",
"3",
"/",
"4",
"to",
"4",
"/",
"3",
".",
"This",
"crop",
"is",
"then",
"resized"... | def random_crop_resize(self, patch, inplace=True):
''' Crop of the image at a random size between 0.08 to 1 of input image
and random aspect ratio between 3/4 to 4/3.
This crop is then resized to the given patch size.
Args:
patch(tuple): width and height of the patch
inplace(Boolean): replace the internal images list with the patches
if True; otherwise, return the patches.
'''
new_imgs = []
for img in self.imgs:
area = img.size[0] * img.size[1]
img_resized = None
for attempt in range(10):
target_area = random.uniform(0.08, 1.0) * area
aspect_ratio = random.uniform(3. / 4, 4. / 3)
crop_x = int(round(math.sqrt(target_area * aspect_ratio)))
crop_y = int(round(math.sqrt(target_area / aspect_ratio)))
if img.size[0] > crop_x and img.size[1] > crop_y:
left_offset = random.randint(0, img.size[0] - crop_x)
top_offset = random.randint(0, img.size[1] - crop_y)
box = (left_offset, top_offset, left_offset + crop_x,
top_offset + crop_y)
img_croped = img.crop(box)
img_resized = img_croped.resize(patch, Image.BILINEAR)
break
if img_resized is None:
img_resized = img.resize(patch, Image.BILINEAR)
new_imgs.append(img_resized)
if inplace:
self.imgs = new_imgs
return self
else:
return new_imgs | [
"def",
"random_crop_resize",
"(",
"self",
",",
"patch",
",",
"inplace",
"=",
"True",
")",
":",
"new_imgs",
"=",
"[",
"]",
"for",
"img",
"in",
"self",
".",
"imgs",
":",
"area",
"=",
"img",
".",
"size",
"[",
"0",
"]",
"*",
"img",
".",
"size",
"[",
... | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/image_tool.py#L504-L539 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/header.py | python | Header.encode | (self, splitchars=';, \t', maxlinelen=None, linesep='\n') | return value | r"""Encode a message header into an RFC-compliant format.
There are many issues involved in converting a given string for use in
an email header. Only certain character sets are readable in most
email clients, and as header strings can only contain a subset of
7-bit ASCII, care must be taken to properly convert and encode (with
Base64 or quoted-printable) header strings. In addition, there is a
75-character length limit on any given encoded header field, so
line-wrapping must be performed, even with double-byte character sets.
Optional maxlinelen specifies the maximum length of each generated
line, exclusive of the linesep string. Individual lines may be longer
than maxlinelen if a folding point cannot be found. The first line
will be shorter by the length of the header name plus ": " if a header
name was specified at Header construction time. The default value for
maxlinelen is determined at header construction time.
Optional splitchars is a string containing characters which should be
given extra weight by the splitting algorithm during normal header
wrapping. This is in very rough support of RFC 2822's `higher level
syntactic breaks': split points preceded by a splitchar are preferred
during line splitting, with the characters preferred in the order in
which they appear in the string. Space and tab may be included in the
string to indicate whether preference should be given to one over the
other as a split point when other split chars do not appear in the line
being split. Splitchars does not affect RFC 2047 encoded lines.
Optional linesep is a string to be used to separate the lines of
the value. The default value is the most useful for typical
Python applications, but it can be set to \r\n to produce RFC-compliant
line separators when needed. | r"""Encode a message header into an RFC-compliant format. | [
"r",
"Encode",
"a",
"message",
"header",
"into",
"an",
"RFC",
"-",
"compliant",
"format",
"."
] | def encode(self, splitchars=';, \t', maxlinelen=None, linesep='\n'):
r"""Encode a message header into an RFC-compliant format.
There are many issues involved in converting a given string for use in
an email header. Only certain character sets are readable in most
email clients, and as header strings can only contain a subset of
7-bit ASCII, care must be taken to properly convert and encode (with
Base64 or quoted-printable) header strings. In addition, there is a
75-character length limit on any given encoded header field, so
line-wrapping must be performed, even with double-byte character sets.
Optional maxlinelen specifies the maximum length of each generated
line, exclusive of the linesep string. Individual lines may be longer
than maxlinelen if a folding point cannot be found. The first line
will be shorter by the length of the header name plus ": " if a header
name was specified at Header construction time. The default value for
maxlinelen is determined at header construction time.
Optional splitchars is a string containing characters which should be
given extra weight by the splitting algorithm during normal header
wrapping. This is in very rough support of RFC 2822's `higher level
syntactic breaks': split points preceded by a splitchar are preferred
during line splitting, with the characters preferred in the order in
which they appear in the string. Space and tab may be included in the
string to indicate whether preference should be given to one over the
other as a split point when other split chars do not appear in the line
being split. Splitchars does not affect RFC 2047 encoded lines.
Optional linesep is a string to be used to separate the lines of
the value. The default value is the most useful for typical
Python applications, but it can be set to \r\n to produce RFC-compliant
line separators when needed.
"""
self._normalize()
if maxlinelen is None:
maxlinelen = self._maxlinelen
# A maxlinelen of 0 means don't wrap. For all practical purposes,
# choosing a huge number here accomplishes that and makes the
# _ValueFormatter algorithm much simpler.
if maxlinelen == 0:
maxlinelen = 1000000
formatter = _ValueFormatter(self._headerlen, maxlinelen,
self._continuation_ws, splitchars)
lastcs = None
hasspace = lastspace = None
for string, charset in self._chunks:
if hasspace is not None:
hasspace = string and self._nonctext(string[0])
if lastcs not in (None, 'us-ascii'):
if not hasspace or charset not in (None, 'us-ascii'):
formatter.add_transition()
elif charset not in (None, 'us-ascii') and not lastspace:
formatter.add_transition()
lastspace = string and self._nonctext(string[-1])
lastcs = charset
hasspace = False
lines = string.splitlines()
if lines:
formatter.feed('', lines[0], charset)
else:
formatter.feed('', '', charset)
for line in lines[1:]:
formatter.newline()
if charset.header_encoding is not None:
formatter.feed(self._continuation_ws, ' ' + line.lstrip(),
charset)
else:
sline = line.lstrip()
fws = line[:len(line)-len(sline)]
formatter.feed(fws, sline, charset)
if len(lines) > 1:
formatter.newline()
if self._chunks:
formatter.add_transition()
value = formatter._str(linesep)
if _embedded_header.search(value):
raise HeaderParseError("header value appears to contain "
"an embedded header: {!r}".format(value))
return value | [
"def",
"encode",
"(",
"self",
",",
"splitchars",
"=",
"';, \\t'",
",",
"maxlinelen",
"=",
"None",
",",
"linesep",
"=",
"'\\n'",
")",
":",
"self",
".",
"_normalize",
"(",
")",
"if",
"maxlinelen",
"is",
"None",
":",
"maxlinelen",
"=",
"self",
".",
"_maxl... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/header.py#L313-L391 | |
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert/tokenization.py | python | convert_to_unicode | (text) | Converts `text` to Unicode (if it's not already), assuming utf-8 input. | Converts `text` to Unicode (if it's not already), assuming utf-8 input. | [
"Converts",
"text",
"to",
"Unicode",
"(",
"if",
"it",
"s",
"not",
"already",
")",
"assuming",
"utf",
"-",
"8",
"input",
"."
] | def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?") | [
"def",
"convert_to_unicode",
"(",
"text",
")",
":",
"if",
"six",
".",
"PY3",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"text",
"elif",
"isinstance",
"(",
"text",
",",
"bytes",
")",
":",
"return",
"text",
".",
"decode",
"("... | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert/tokenization.py#L78-L95 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | ppapi/generators/idl_parser.py | python | IDLParser.p_interface_block | (self, p) | interface_block : modifiers INTERFACE SYMBOL '{' interface_list '}' '; | interface_block : modifiers INTERFACE SYMBOL '{' interface_list '}' '; | [
"interface_block",
":",
"modifiers",
"INTERFACE",
"SYMBOL",
"{",
"interface_list",
"}",
";"
] | def p_interface_block(self, p):
"""interface_block : modifiers INTERFACE SYMBOL '{' interface_list '}' ';'"""
p[0] = self.BuildNamed('Interface', p, 3, ListFromConcat(p[1], p[5]))
if self.parse_debug: DumpReduction('interface_block', p) | [
"def",
"p_interface_block",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"BuildNamed",
"(",
"'Interface'",
",",
"p",
",",
"3",
",",
"ListFromConcat",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"5",
"]",
")",
")",
"if",
... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/ppapi/generators/idl_parser.py#L709-L712 | ||
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/gtk/GtkGLExtVTKRenderWindow.py | python | GtkGLExtVTKRenderWindowBase.OnLeave | (self, wid, event) | return gtk.TRUE | Leaving the vtkRenderWindow. | Leaving the vtkRenderWindow. | [
"Leaving",
"the",
"vtkRenderWindow",
"."
] | def OnLeave(self, wid, event):
"""Leaving the vtkRenderWindow."""
return gtk.TRUE | [
"def",
"OnLeave",
"(",
"self",
",",
"wid",
",",
"event",
")",
":",
"return",
"gtk",
".",
"TRUE"
] | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/gtk/GtkGLExtVTKRenderWindow.py#L161-L163 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/apitools/scripts/oauth2l.py | python | _ValidateToken | (access_token) | return bool(_GetTokenScopes(access_token)) | Return True iff the provided access token is valid. | Return True iff the provided access token is valid. | [
"Return",
"True",
"iff",
"the",
"provided",
"access",
"token",
"is",
"valid",
"."
] | def _ValidateToken(access_token):
"""Return True iff the provided access token is valid."""
return bool(_GetTokenScopes(access_token)) | [
"def",
"_ValidateToken",
"(",
"access_token",
")",
":",
"return",
"bool",
"(",
"_GetTokenScopes",
"(",
"access_token",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/scripts/oauth2l.py#L156-L158 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/autocomplete.py | python | AutoComplete._delayed_open_completions | (self, args) | Call open_completions if index unchanged. | Call open_completions if index unchanged. | [
"Call",
"open_completions",
"if",
"index",
"unchanged",
"."
] | def _delayed_open_completions(self, args):
"Call open_completions if index unchanged."
self._delayed_completion_id = None
if self.text.index("insert") == self._delayed_completion_index:
self.open_completions(args) | [
"def",
"_delayed_open_completions",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"_delayed_completion_id",
"=",
"None",
"if",
"self",
".",
"text",
".",
"index",
"(",
"\"insert\"",
")",
"==",
"self",
".",
"_delayed_completion_index",
":",
"self",
".",
"op... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/autocomplete.py#L87-L91 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/thumbnailctrl.py | python | ScrolledThumbnail.DeleteFiles | (self) | Deletes the selected thumbnails and their associated files.
.. warning:: This method deletes the original files too. | Deletes the selected thumbnails and their associated files. | [
"Deletes",
"the",
"selected",
"thumbnails",
"and",
"their",
"associated",
"files",
"."
] | def DeleteFiles(self):
"""
Deletes the selected thumbnails and their associated files.
.. warning:: This method deletes the original files too.
"""
dlg = wx.MessageDialog(self, 'Are you sure you want to delete the files?',
'Confirmation',
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
if dlg.ShowModal() == wx.ID_YES:
errordelete = []
count = 0
dlg.Destroy()
wx.BeginBusyCursor()
for ii in xrange(len(self._items)):
if self.IsSelected(ii):
thumb = self._items[ii]
files = self._items[ii].GetFullFileName()
filename = opj(files)
try:
os.remove(filename)
count = count + 1
except:
errordelete.append(files)
wx.EndBusyCursor()
if errordelete:
strs = "Unable to remove the following files:\n\n"
for fil in errordelete:
strs = strs + fil + "\n"
strs = strs + "\n"
strs = strs + "Please check your privileges and file permissions."
dlg = wx.MessageDialog(self, strs,
'Error in removing files',
wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
if count:
self.UpdateShow() | [
"def",
"DeleteFiles",
"(",
"self",
")",
":",
"dlg",
"=",
"wx",
".",
"MessageDialog",
"(",
"self",
",",
"'Are you sure you want to delete the files?'",
",",
"'Confirmation'",
",",
"wx",
".",
"YES_NO",
"|",
"wx",
".",
"NO_DEFAULT",
"|",
"wx",
".",
"ICON_QUESTION... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L2488-L2533 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.