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
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/boost/tools/build/src/util/regex.py
python
replace_list
(items, match, replacement)
return [replace(item, match, replacement) for item in items]
Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match string can be a regex expression. Args: items (list): the list of strings to modify. match (str): the search expression. replacement (str): the string to replace with.
Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match string can be a regex expression.
[ "Replaces", "occurrences", "of", "a", "match", "string", "in", "a", "given", "list", "of", "strings", "and", "returns", "a", "list", "of", "new", "strings", ".", "The", "match", "string", "can", "be", "a", "regex", "expression", "." ]
def replace_list(items, match, replacement): """Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match string can be a regex expression. Args: items (list): the list of strings to modify. match (str): the search expression. replacement (str): the string to replace with. """ return [replace(item, match, replacement) for item in items]
[ "def", "replace_list", "(", "items", ",", "match", ",", "replacement", ")", ":", "return", "[", "replace", "(", "item", ",", "match", ",", "replacement", ")", "for", "item", "in", "items", "]" ]
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/util/regex.py#L54-L63
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Button.__init__
(self, master=None, cnf={}, **kw)
Construct a button widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, repeatdelay, repeatinterval, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS command, compound, default, height, overrelief, state, width
Construct a button widget with the parent MASTER.
[ "Construct", "a", "button", "widget", "with", "the", "parent", "MASTER", "." ]
def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, repeatdelay, repeatinterval, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS command, compound, default, height, overrelief, state, width """ Widget.__init__(self, master, 'button', cnf, kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "'button'", ",", "cnf", ",", "kw", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2087-L2106
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/views/rest/gp_hyper_opt.py
python
GpHyperOptView.pretty_view
(self)
return self.pretty_response()
A pretty, browser interactive view for the interface. Includes form request and response. .. http:get:: /gp/hyper_opt/pretty
A pretty, browser interactive view for the interface. Includes form request and response.
[ "A", "pretty", "browser", "interactive", "view", "for", "the", "interface", ".", "Includes", "form", "request", "and", "response", "." ]
def pretty_view(self): """A pretty, browser interactive view for the interface. Includes form request and response. .. http:get:: /gp/hyper_opt/pretty """ return self.pretty_response()
[ "def", "pretty_view", "(", "self", ")", ":", "return", "self", ".", "pretty_response", "(", ")" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/views/rest/gp_hyper_opt.py#L84-L90
taichi-dev/taichi
973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6
python/taichi/lang/matrix.py
python
Matrix.norm
(self, eps=0)
return ops_mod.sqrt(self.norm_sqr() + eps)
Return the square root of the sum of the absolute squares of its elements. Args: eps (Number): a safe-guard value for sqrt, usually 0. Examples:: a = ti.Vector([3, 4]) a.norm() # sqrt(3*3 + 4*4 + 0) = 5 # `a.norm(eps)` is equivalent to `ti.sqrt(a.dot(a) + eps).` Return: The square root of the sum of the absolute squares of its elements.
Return the square root of the sum of the absolute squares of its elements.
[ "Return", "the", "square", "root", "of", "the", "sum", "of", "the", "absolute", "squares", "of", "its", "elements", "." ]
def norm(self, eps=0): """Return the square root of the sum of the absolute squares of its elements. Args: eps (Number): a safe-guard value for sqrt, usually 0. Examples:: a = ti.Vector([3, 4]) a.norm() # sqrt(3*3 + 4*4 + 0) = 5 # `a.norm(eps)` is equivalent to `ti.sqrt(a.dot(a) + eps).` Return: The square root of the sum of the absolute squares of its elements. """ return ops_mod.sqrt(self.norm_sqr() + eps)
[ "def", "norm", "(", "self", ",", "eps", "=", "0", ")", ":", "return", "ops_mod", ".", "sqrt", "(", "self", ".", "norm_sqr", "(", ")", "+", "eps", ")" ]
https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/matrix.py#L581-L597
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/string_arrow.py
python
ArrowStringArray.isna
(self)
return self._data.is_null().to_pandas().values
Boolean NumPy array indicating if each value is missing. This should return a 1-D array the same length as 'self'.
Boolean NumPy array indicating if each value is missing.
[ "Boolean", "NumPy", "array", "indicating", "if", "each", "value", "is", "missing", "." ]
def isna(self) -> np.ndarray: """ Boolean NumPy array indicating if each value is missing. This should return a 1-D array the same length as 'self'. """ # TODO: Implement .to_numpy for ChunkedArray return self._data.is_null().to_pandas().values
[ "def", "isna", "(", "self", ")", "->", "np", ".", "ndarray", ":", "# TODO: Implement .to_numpy for ChunkedArray", "return", "self", ".", "_data", ".", "is_null", "(", ")", ".", "to_pandas", "(", ")", ".", "values" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/string_arrow.py#L390-L397
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/Chem/FeatMaps/FeatMapPoint.py
python
FeatMapPoint.initFromFeat
(self, feat)
>>> from rdkit import Geometry >>> sfeat = ChemicalFeatures.FreeChemicalFeature('Aromatic','Foo',Geometry.Point3D(0,0,0)) >>> fmp = FeatMapPoint() >>> fmp.initFromFeat(sfeat) >>> fmp.GetFamily()==sfeat.GetFamily() True >>> fmp.GetType()==sfeat.GetType() True >>> list(fmp.GetPos()) [0.0, 0.0, 0.0] >>> fmp.featDirs == [] True >>> sfeat.featDirs = [Geometry.Point3D(1.0,0,0)] >>> fmp.initFromFeat(sfeat) >>> len(fmp.featDirs) 1
>>> from rdkit import Geometry >>> sfeat = ChemicalFeatures.FreeChemicalFeature('Aromatic','Foo',Geometry.Point3D(0,0,0)) >>> fmp = FeatMapPoint() >>> fmp.initFromFeat(sfeat) >>> fmp.GetFamily()==sfeat.GetFamily() True >>> fmp.GetType()==sfeat.GetType() True >>> list(fmp.GetPos()) [0.0, 0.0, 0.0] >>> fmp.featDirs == [] True
[ ">>>", "from", "rdkit", "import", "Geometry", ">>>", "sfeat", "=", "ChemicalFeatures", ".", "FreeChemicalFeature", "(", "Aromatic", "Foo", "Geometry", ".", "Point3D", "(", "0", "0", "0", "))", ">>>", "fmp", "=", "FeatMapPoint", "()", ">>>", "fmp", ".", "initFromFeat", "(", "sfeat", ")", ">>>", "fmp", ".", "GetFamily", "()", "==", "sfeat", ".", "GetFamily", "()", "True", ">>>", "fmp", ".", "GetType", "()", "==", "sfeat", ".", "GetType", "()", "True", ">>>", "list", "(", "fmp", ".", "GetPos", "()", ")", "[", "0", ".", "0", "0", ".", "0", "0", ".", "0", "]", ">>>", "fmp", ".", "featDirs", "==", "[]", "True" ]
def initFromFeat(self, feat): """ >>> from rdkit import Geometry >>> sfeat = ChemicalFeatures.FreeChemicalFeature('Aromatic','Foo',Geometry.Point3D(0,0,0)) >>> fmp = FeatMapPoint() >>> fmp.initFromFeat(sfeat) >>> fmp.GetFamily()==sfeat.GetFamily() True >>> fmp.GetType()==sfeat.GetType() True >>> list(fmp.GetPos()) [0.0, 0.0, 0.0] >>> fmp.featDirs == [] True >>> sfeat.featDirs = [Geometry.Point3D(1.0,0,0)] >>> fmp.initFromFeat(sfeat) >>> len(fmp.featDirs) 1 """ self.SetFamily(feat.GetFamily()) self.SetType(feat.GetType()) self.SetPos(feat.GetPos()) if hasattr(feat, 'featDirs'): self.featDirs = feat.featDirs[:]
[ "def", "initFromFeat", "(", "self", ",", "feat", ")", ":", "self", ".", "SetFamily", "(", "feat", ".", "GetFamily", "(", ")", ")", "self", ".", "SetType", "(", "feat", ".", "GetType", "(", ")", ")", "self", ".", "SetPos", "(", "feat", ".", "GetPos", "(", ")", ")", "if", "hasattr", "(", "feat", ",", "'featDirs'", ")", ":", "self", ".", "featDirs", "=", "feat", ".", "featDirs", "[", ":", "]" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/FeatMaps/FeatMapPoint.py#L22-L47
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/tz.py
python
tzfile.is_ambiguous
(self, dt, idx=None)
return timestamp < tt + od
Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0
Whether or not the "wall time" of a given datetime is ambiguous in this zone.
[ "Whether", "or", "not", "the", "wall", "time", "of", "a", "given", "datetime", "is", "ambiguous", "in", "this", "zone", "." ]
def is_ambiguous(self, dt, idx=None): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. .. versionadded:: 2.6.0 """ if idx is None: idx = self._find_last_transition(dt) # Calculate the difference in offsets from current to previous timestamp = _datetime_to_timestamp(dt) tti = self._get_ttinfo(idx) if idx is None or idx <= 0: return False od = self._get_ttinfo(idx - 1).offset - tti.offset tt = self._trans_list[idx] # Transition time return timestamp < tt + od
[ "def", "is_ambiguous", "(", "self", ",", "dt", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "None", ":", "idx", "=", "self", ".", "_find_last_transition", "(", "dt", ")", "# Calculate the difference in offsets from current to previous", "timestamp", "=", "_datetime_to_timestamp", "(", "dt", ")", "tti", "=", "self", ".", "_get_ttinfo", "(", "idx", ")", "if", "idx", "is", "None", "or", "idx", "<=", "0", ":", "return", "False", "od", "=", "self", ".", "_get_ttinfo", "(", "idx", "-", "1", ")", ".", "offset", "-", "tti", ".", "offset", "tt", "=", "self", ".", "_trans_list", "[", "idx", "]", "# Transition time", "return", "timestamp", "<", "tt", "+", "od" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/tz.py#L673-L700
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/pymock/mock.py
python
_patch_dict.__exit__
(self, *args)
return False
Unpatch the dict.
Unpatch the dict.
[ "Unpatch", "the", "dict", "." ]
def __exit__(self, *args): """Unpatch the dict.""" self._unpatch_dict() return False
[ "def", "__exit__", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_unpatch_dict", "(", ")", "return", "False" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pymock/mock.py#L1680-L1683
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/portable_server.py
python
CompositeDbRootHandler.get
(self, layer_id)
Handle GET request for the dbroot.
Handle GET request for the dbroot.
[ "Handle", "GET", "request", "for", "the", "dbroot", "." ]
def get(self, layer_id): """Handle GET request for the dbroot.""" self.set_header("Content-Type", "application/octet-stream") if not tornado.web.globe_.Is3d(): print "Bad request: dbRoot from non-3D globe." elif not tornado.web.globe_.IsComposite(): print "Bad request: composite request for glb." else: tornado.web.local_server_.LocalDbRootHandler(self, int(layer_id)) self.finish()
[ "def", "get", "(", "self", ",", "layer_id", ")", ":", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"application/octet-stream\"", ")", "if", "not", "tornado", ".", "web", ".", "globe_", ".", "Is3d", "(", ")", ":", "print", "\"Bad request: dbRoot from non-3D globe.\"", "elif", "not", "tornado", ".", "web", ".", "globe_", ".", "IsComposite", "(", ")", ":", "print", "\"Bad request: composite request for glb.\"", "else", ":", "tornado", ".", "web", ".", "local_server_", ".", "LocalDbRootHandler", "(", "self", ",", "int", "(", "layer_id", ")", ")", "self", ".", "finish", "(", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/portable_server.py#L99-L108
D-X-Y/caffe-faster-rcnn
eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb
python/caffe/pycaffe.py
python
_Net_backward
(self, diffs=None, start=None, end=None, **kwargs)
return {out: self.blobs[out].diff for out in outputs}
Backward pass: prepare diffs and run the net backward. Parameters ---------- diffs : list of diffs to return in addition to bottom diffs. kwargs : Keys are output blob names and values are diff ndarrays. If None, top diffs are taken from forward loss. start : optional name of layer at which to begin the backward pass end : optional name of layer at which to finish the backward pass (inclusive) Returns ------- outs: {blob name: diff ndarray} dict.
Backward pass: prepare diffs and run the net backward.
[ "Backward", "pass", ":", "prepare", "diffs", "and", "run", "the", "net", "backward", "." ]
def _Net_backward(self, diffs=None, start=None, end=None, **kwargs): """ Backward pass: prepare diffs and run the net backward. Parameters ---------- diffs : list of diffs to return in addition to bottom diffs. kwargs : Keys are output blob names and values are diff ndarrays. If None, top diffs are taken from forward loss. start : optional name of layer at which to begin the backward pass end : optional name of layer at which to finish the backward pass (inclusive) Returns ------- outs: {blob name: diff ndarray} dict. """ if diffs is None: diffs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = len(self.layers) - 1 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set(self.bottom_names[end] + diffs) else: end_ind = 0 outputs = set(self.inputs + diffs) if kwargs: if set(kwargs.keys()) != set(self.outputs): raise Exception('Top diff arguments do not match net outputs.') # Set top diffs according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for top, diff in six.iteritems(kwargs): if diff.shape[0] != self.blobs[top].shape[0]: raise Exception('Diff is not batch sized') self.blobs[top].diff[...] = diff self._backward(start_ind, end_ind) # Unpack diffs to extract return {out: self.blobs[out].diff for out in outputs}
[ "def", "_Net_backward", "(", "self", ",", "diffs", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "diffs", "is", "None", ":", "diffs", "=", "[", "]", "if", "start", "is", "not", "None", ":", "start_ind", "=", "list", "(", "self", ".", "_layer_names", ")", ".", "index", "(", "start", ")", "else", ":", "start_ind", "=", "len", "(", "self", ".", "layers", ")", "-", "1", "if", "end", "is", "not", "None", ":", "end_ind", "=", "list", "(", "self", ".", "_layer_names", ")", ".", "index", "(", "end", ")", "outputs", "=", "set", "(", "self", ".", "bottom_names", "[", "end", "]", "+", "diffs", ")", "else", ":", "end_ind", "=", "0", "outputs", "=", "set", "(", "self", ".", "inputs", "+", "diffs", ")", "if", "kwargs", ":", "if", "set", "(", "kwargs", ".", "keys", "(", ")", ")", "!=", "set", "(", "self", ".", "outputs", ")", ":", "raise", "Exception", "(", "'Top diff arguments do not match net outputs.'", ")", "# Set top diffs according to defined shapes and make arrays single and", "# C-contiguous as Caffe expects.", "for", "top", ",", "diff", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "if", "diff", ".", "shape", "[", "0", "]", "!=", "self", ".", "blobs", "[", "top", "]", ".", "shape", "[", "0", "]", ":", "raise", "Exception", "(", "'Diff is not batch sized'", ")", "self", ".", "blobs", "[", "top", "]", ".", "diff", "[", "...", "]", "=", "diff", "self", ".", "_backward", "(", "start_ind", ",", "end_ind", ")", "# Unpack diffs to extract", "return", "{", "out", ":", "self", ".", "blobs", "[", "out", "]", ".", "diff", "for", "out", "in", "outputs", "}" ]
https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/python/caffe/pycaffe.py#L137-L182
bilibili/biliobs
573613dc3b2b63fe7c1506cc94717609a2c52c0c
base/android/jni_generator/jni_generator.py
python
InlHeaderFileGenerator.SubstituteNativeMethods
(self, template)
return '\n' + '\n'.join(ret)
Substitutes JAVA_CLASS and KMETHODS in the provided template.
Substitutes JAVA_CLASS and KMETHODS in the provided template.
[ "Substitutes", "JAVA_CLASS", "and", "KMETHODS", "in", "the", "provided", "template", "." ]
def SubstituteNativeMethods(self, template): """Substitutes JAVA_CLASS and KMETHODS in the provided template.""" ret = [] all_classes = self.GetUniqueClasses(self.natives) all_classes[self.class_name] = self.fully_qualified_class for clazz in all_classes: kmethods = self.GetKMethodsString(clazz) if kmethods: values = {'JAVA_CLASS': clazz, 'KMETHODS': kmethods} ret += [template.substitute(values)] if not ret: return '' return '\n' + '\n'.join(ret)
[ "def", "SubstituteNativeMethods", "(", "self", ",", "template", ")", ":", "ret", "=", "[", "]", "all_classes", "=", "self", ".", "GetUniqueClasses", "(", "self", ".", "natives", ")", "all_classes", "[", "self", ".", "class_name", "]", "=", "self", ".", "fully_qualified_class", "for", "clazz", "in", "all_classes", ":", "kmethods", "=", "self", ".", "GetKMethodsString", "(", "clazz", ")", "if", "kmethods", ":", "values", "=", "{", "'JAVA_CLASS'", ":", "clazz", ",", "'KMETHODS'", ":", "kmethods", "}", "ret", "+=", "[", "template", ".", "substitute", "(", "values", ")", "]", "if", "not", "ret", ":", "return", "''", "return", "'\\n'", "+", "'\\n'", ".", "join", "(", "ret", ")" ]
https://github.com/bilibili/biliobs/blob/573613dc3b2b63fe7c1506cc94717609a2c52c0c/base/android/jni_generator/jni_generator.py#L881-L893
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
python
AppleScript_Suite_Events._2d_
(self, _object, _attributes={}, **_arguments)
-: Subtraction Required argument: an AE object reference Keyword argument _attributes: AppleEvent attribute dictionary Returns: anything
-: Subtraction Required argument: an AE object reference Keyword argument _attributes: AppleEvent attribute dictionary Returns: anything
[ "-", ":", "Subtraction", "Required", "argument", ":", "an", "AE", "object", "reference", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "anything" ]
def _2d_(self, _object, _attributes={}, **_arguments): """-: Subtraction Required argument: an AE object reference Keyword argument _attributes: AppleEvent attribute dictionary Returns: anything """ _code = 'ascr' _subcode = '- ' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "_2d_", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'ascr'", "_subcode", "=", "'- '", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py#L78-L97
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/control_flow_ops.py
python
IsLoopExit
(op)
return op.type == "Exit" or op.type == "RefExit"
Return true if `op` is an Exit.
Return true if `op` is an Exit.
[ "Return", "true", "if", "op", "is", "an", "Exit", "." ]
def IsLoopExit(op): """Return true if `op` is an Exit.""" return op.type == "Exit" or op.type == "RefExit"
[ "def", "IsLoopExit", "(", "op", ")", ":", "return", "op", ".", "type", "==", "\"Exit\"", "or", "op", ".", "type", "==", "\"RefExit\"" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/control_flow_ops.py#L1322-L1324
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/PyChop2.py
python
PyChop2.getChopper
(self)
return self.object.getChopper()
! Returns the currently set chopper rotor or instrument configuration
! Returns the currently set chopper rotor or instrument configuration
[ "!", "Returns", "the", "currently", "set", "chopper", "rotor", "or", "instrument", "configuration" ]
def getChopper(self): """ ! Returns the currently set chopper rotor or instrument configuration """ return self.object.getChopper()
[ "def", "getChopper", "(", "self", ")", ":", "return", "self", ".", "object", ".", "getChopper", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/PyChop2.py#L74-L78
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_carbon/gizmos.py
python
TreeListCtrl.GetImageList
(*args, **kwargs)
return _gizmos.TreeListCtrl_GetImageList(*args, **kwargs)
GetImageList(self) -> ImageList
GetImageList(self) -> ImageList
[ "GetImageList", "(", "self", ")", "-", ">", "ImageList" ]
def GetImageList(*args, **kwargs): """GetImageList(self) -> ImageList""" return _gizmos.TreeListCtrl_GetImageList(*args, **kwargs)
[ "def", "GetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_GetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L519-L521
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/datasets/_twenty_newsgroups.py
python
fetch_20newsgroups_vectorized
(subset="train", remove=(), data_home=None, download_if_missing=True, return_X_y=False, normalize=True)
return Bunch(data=data, target=target, target_names=target_names, DESCR=fdescr)
Load the 20 newsgroups dataset and vectorize it into token counts \ (classification). Download it if necessary. This is a convenience function; the transformation is done using the default settings for :class:`sklearn.feature_extraction.text.CountVectorizer`. For more advanced usage (stopword filtering, n-gram extraction, etc.), combine fetch_20newsgroups with a custom :class:`sklearn.feature_extraction.text.CountVectorizer`, :class:`sklearn.feature_extraction.text.HashingVectorizer`, :class:`sklearn.feature_extraction.text.TfidfTransformer` or :class:`sklearn.feature_extraction.text.TfidfVectorizer`. The resulting counts are normalized using :func:`sklearn.preprocessing.normalize` unless normalize is set to False. ================= ========== Classes 20 Samples total 18846 Dimensionality 130107 Features real ================= ========== Read more in the :ref:`User Guide <20newsgroups_dataset>`. Parameters ---------- subset : 'train' or 'test', 'all', optional Select the dataset to load: 'train' for the training set, 'test' for the test set, 'all' for both, with shuffled ordering. remove : tuple May contain any subset of ('headers', 'footers', 'quotes'). Each of these are kinds of text that will be detected and removed from the newsgroup posts, preventing classifiers from overfitting on metadata. 'headers' removes newsgroup headers, 'footers' removes blocks at the ends of posts that look like signatures, and 'quotes' removes lines that appear to be quoting another post. data_home : optional, default: None Specify an download and cache folder for the datasets. If None, all scikit-learn data is stored in '~/scikit_learn_data' subfolders. download_if_missing : optional, True by default If False, raise an IOError if the data is not locally available instead of trying to download the data from the source site. return_X_y : bool, default=False If True, returns ``(data.data, data.target)`` instead of a Bunch object. .. versionadded:: 0.20 normalize : bool, default=True If True, normalizes each document's feature vector to unit norm using :func:`sklearn.preprocessing.normalize`. .. versionadded:: 0.22 Returns ------- bunch : Bunch object with the following attribute: - bunch.data: sparse matrix, shape [n_samples, n_features] - bunch.target: array, shape [n_samples] - bunch.target_names: a list of categories of the returned data, length [n_classes]. - bunch.DESCR: a description of the dataset. (data, target) : tuple if ``return_X_y`` is True .. versionadded:: 0.20
Load the 20 newsgroups dataset and vectorize it into token counts \ (classification).
[ "Load", "the", "20", "newsgroups", "dataset", "and", "vectorize", "it", "into", "token", "counts", "\\", "(", "classification", ")", "." ]
def fetch_20newsgroups_vectorized(subset="train", remove=(), data_home=None, download_if_missing=True, return_X_y=False, normalize=True): """Load the 20 newsgroups dataset and vectorize it into token counts \ (classification). Download it if necessary. This is a convenience function; the transformation is done using the default settings for :class:`sklearn.feature_extraction.text.CountVectorizer`. For more advanced usage (stopword filtering, n-gram extraction, etc.), combine fetch_20newsgroups with a custom :class:`sklearn.feature_extraction.text.CountVectorizer`, :class:`sklearn.feature_extraction.text.HashingVectorizer`, :class:`sklearn.feature_extraction.text.TfidfTransformer` or :class:`sklearn.feature_extraction.text.TfidfVectorizer`. The resulting counts are normalized using :func:`sklearn.preprocessing.normalize` unless normalize is set to False. ================= ========== Classes 20 Samples total 18846 Dimensionality 130107 Features real ================= ========== Read more in the :ref:`User Guide <20newsgroups_dataset>`. Parameters ---------- subset : 'train' or 'test', 'all', optional Select the dataset to load: 'train' for the training set, 'test' for the test set, 'all' for both, with shuffled ordering. remove : tuple May contain any subset of ('headers', 'footers', 'quotes'). Each of these are kinds of text that will be detected and removed from the newsgroup posts, preventing classifiers from overfitting on metadata. 'headers' removes newsgroup headers, 'footers' removes blocks at the ends of posts that look like signatures, and 'quotes' removes lines that appear to be quoting another post. data_home : optional, default: None Specify an download and cache folder for the datasets. If None, all scikit-learn data is stored in '~/scikit_learn_data' subfolders. download_if_missing : optional, True by default If False, raise an IOError if the data is not locally available instead of trying to download the data from the source site. return_X_y : bool, default=False If True, returns ``(data.data, data.target)`` instead of a Bunch object. .. versionadded:: 0.20 normalize : bool, default=True If True, normalizes each document's feature vector to unit norm using :func:`sklearn.preprocessing.normalize`. .. versionadded:: 0.22 Returns ------- bunch : Bunch object with the following attribute: - bunch.data: sparse matrix, shape [n_samples, n_features] - bunch.target: array, shape [n_samples] - bunch.target_names: a list of categories of the returned data, length [n_classes]. - bunch.DESCR: a description of the dataset. (data, target) : tuple if ``return_X_y`` is True .. versionadded:: 0.20 """ data_home = get_data_home(data_home=data_home) filebase = '20newsgroup_vectorized' if remove: filebase += 'remove-' + ('-'.join(remove)) target_file = _pkl_filepath(data_home, filebase + ".pkl") # we shuffle but use a fixed seed for the memoization data_train = fetch_20newsgroups(data_home=data_home, subset='train', categories=None, shuffle=True, random_state=12, remove=remove, download_if_missing=download_if_missing) data_test = fetch_20newsgroups(data_home=data_home, subset='test', categories=None, shuffle=True, random_state=12, remove=remove, download_if_missing=download_if_missing) if os.path.exists(target_file): X_train, X_test = joblib.load(target_file) else: vectorizer = CountVectorizer(dtype=np.int16) X_train = vectorizer.fit_transform(data_train.data).tocsr() X_test = vectorizer.transform(data_test.data).tocsr() joblib.dump((X_train, X_test), target_file, compress=9) # the data is stored as int16 for compactness # but normalize needs floats if normalize: X_train = X_train.astype(np.float64) X_test = X_test.astype(np.float64) preprocessing.normalize(X_train, copy=False) preprocessing.normalize(X_test, copy=False) target_names = data_train.target_names if subset == "train": data = X_train target = data_train.target elif subset == "test": data = X_test target = data_test.target elif subset == "all": data = sp.vstack((X_train, X_test)).tocsr() target = np.concatenate((data_train.target, data_test.target)) else: raise ValueError("%r is not a valid subset: should be one of " "['train', 'test', 'all']" % subset) module_path = dirname(__file__) with open(join(module_path, 'descr', 'twenty_newsgroups.rst')) as rst_file: fdescr = rst_file.read() if return_X_y: return data, target return Bunch(data=data, target=target, target_names=target_names, DESCR=fdescr)
[ "def", "fetch_20newsgroups_vectorized", "(", "subset", "=", "\"train\"", ",", "remove", "=", "(", ")", ",", "data_home", "=", "None", ",", "download_if_missing", "=", "True", ",", "return_X_y", "=", "False", ",", "normalize", "=", "True", ")", ":", "data_home", "=", "get_data_home", "(", "data_home", "=", "data_home", ")", "filebase", "=", "'20newsgroup_vectorized'", "if", "remove", ":", "filebase", "+=", "'remove-'", "+", "(", "'-'", ".", "join", "(", "remove", ")", ")", "target_file", "=", "_pkl_filepath", "(", "data_home", ",", "filebase", "+", "\".pkl\"", ")", "# we shuffle but use a fixed seed for the memoization", "data_train", "=", "fetch_20newsgroups", "(", "data_home", "=", "data_home", ",", "subset", "=", "'train'", ",", "categories", "=", "None", ",", "shuffle", "=", "True", ",", "random_state", "=", "12", ",", "remove", "=", "remove", ",", "download_if_missing", "=", "download_if_missing", ")", "data_test", "=", "fetch_20newsgroups", "(", "data_home", "=", "data_home", ",", "subset", "=", "'test'", ",", "categories", "=", "None", ",", "shuffle", "=", "True", ",", "random_state", "=", "12", ",", "remove", "=", "remove", ",", "download_if_missing", "=", "download_if_missing", ")", "if", "os", ".", "path", ".", "exists", "(", "target_file", ")", ":", "X_train", ",", "X_test", "=", "joblib", ".", "load", "(", "target_file", ")", "else", ":", "vectorizer", "=", "CountVectorizer", "(", "dtype", "=", "np", ".", "int16", ")", "X_train", "=", "vectorizer", ".", "fit_transform", "(", "data_train", ".", "data", ")", ".", "tocsr", "(", ")", "X_test", "=", "vectorizer", ".", "transform", "(", "data_test", ".", "data", ")", ".", "tocsr", "(", ")", "joblib", ".", "dump", "(", "(", "X_train", ",", "X_test", ")", ",", "target_file", ",", "compress", "=", "9", ")", "# the data is stored as int16 for compactness", "# but normalize needs floats", "if", "normalize", ":", "X_train", "=", "X_train", ".", "astype", "(", "np", ".", "float64", ")", "X_test", "=", "X_test", ".", "astype", "(", "np", ".", "float64", ")", "preprocessing", ".", "normalize", "(", "X_train", ",", "copy", "=", "False", ")", "preprocessing", ".", "normalize", "(", "X_test", ",", "copy", "=", "False", ")", "target_names", "=", "data_train", ".", "target_names", "if", "subset", "==", "\"train\"", ":", "data", "=", "X_train", "target", "=", "data_train", ".", "target", "elif", "subset", "==", "\"test\"", ":", "data", "=", "X_test", "target", "=", "data_test", ".", "target", "elif", "subset", "==", "\"all\"", ":", "data", "=", "sp", ".", "vstack", "(", "(", "X_train", ",", "X_test", ")", ")", ".", "tocsr", "(", ")", "target", "=", "np", ".", "concatenate", "(", "(", "data_train", ".", "target", ",", "data_test", ".", "target", ")", ")", "else", ":", "raise", "ValueError", "(", "\"%r is not a valid subset: should be one of \"", "\"['train', 'test', 'all']\"", "%", "subset", ")", "module_path", "=", "dirname", "(", "__file__", ")", "with", "open", "(", "join", "(", "module_path", ",", "'descr'", ",", "'twenty_newsgroups.rst'", ")", ")", "as", "rst_file", ":", "fdescr", "=", "rst_file", ".", "read", "(", ")", "if", "return_X_y", ":", "return", "data", ",", "target", "return", "Bunch", "(", "data", "=", "data", ",", "target", "=", "target", ",", "target_names", "=", "target_names", ",", "DESCR", "=", "fdescr", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/datasets/_twenty_newsgroups.py#L319-L462
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/gem5/components/processors/random_generator.py
python
RandomGenerator.start_traffic
(self)
This function will start the assigned traffic to this generator.
This function will start the assigned traffic to this generator.
[ "This", "function", "will", "start", "the", "assigned", "traffic", "to", "this", "generator", "." ]
def start_traffic(self) -> None: """ This function will start the assigned traffic to this generator. """ for core in self.cores: core.start_traffic()
[ "def", "start_traffic", "(", "self", ")", "->", "None", ":", "for", "core", "in", "self", ".", "cores", ":", "core", ".", "start_traffic", "(", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/gem5/components/processors/random_generator.py#L114-L119
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pdb.py
python
Pdb.user_call
(self, frame, argument_list)
This method is called when there is the remote possibility that we ever need to stop in this function.
This method is called when there is the remote possibility that we ever need to stop in this function.
[ "This", "method", "is", "called", "when", "there", "is", "the", "remote", "possibility", "that", "we", "ever", "need", "to", "stop", "in", "this", "function", "." ]
def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" if self._wait_for_mainpyfile: return if self.stop_here(frame): print >>self.stdout, '--Call--' self.interaction(frame, None)
[ "def", "user_call", "(", "self", ",", "frame", ",", "argument_list", ")", ":", "if", "self", ".", "_wait_for_mainpyfile", ":", "return", "if", "self", ".", "stop_here", "(", "frame", ")", ":", "print", ">>", "self", ".", "stdout", ",", "'--Call--'", "self", ".", "interaction", "(", "frame", ",", "None", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pdb.py#L141-L148
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/parser.py
python
ByteParser.child_parsers
(self)
return (ByteParser(self.text, code=c) for c in children)
Iterate over all the code objects nested within this one. The iteration includes `self` as its first value.
Iterate over all the code objects nested within this one.
[ "Iterate", "over", "all", "the", "code", "objects", "nested", "within", "this", "one", "." ]
def child_parsers(self): """Iterate over all the code objects nested within this one. The iteration includes `self` as its first value. """ children = CodeObjects(self.code) return (ByteParser(self.text, code=c) for c in children)
[ "def", "child_parsers", "(", "self", ")", ":", "children", "=", "CodeObjects", "(", "self", ".", "code", ")", "return", "(", "ByteParser", "(", "self", ".", "text", ",", "code", "=", "c", ")", "for", "c", "in", "children", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/parser.py#L355-L362
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/core/util.py
python
GetUnreservedAvailableLocalPort
()
return port
Returns an available port on the system. WARNING: This method does not reserve the port it returns, so it may be used by something else before you get to use it. This can lead to flake.
Returns an available port on the system.
[ "Returns", "an", "available", "port", "on", "the", "system", "." ]
def GetUnreservedAvailableLocalPort(): """Returns an available port on the system. WARNING: This method does not reserve the port it returns, so it may be used by something else before you get to use it. This can lead to flake. """ tmp = socket.socket() tmp.bind(('', 0)) port = tmp.getsockname()[1] tmp.close() return port
[ "def", "GetUnreservedAvailableLocalPort", "(", ")", ":", "tmp", "=", "socket", ".", "socket", "(", ")", "tmp", ".", "bind", "(", "(", "''", ",", "0", ")", ")", "port", "=", "tmp", ".", "getsockname", "(", ")", "[", "1", "]", "tmp", ".", "close", "(", ")", "return", "port" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/util.py#L126-L137
facebook/redex
fac189a289bca2647061f9e364016afc1096500d
tools/python/dex.py
python
File.demangle_class_name
(self, cls_mangled)
return None
Given a mangled type name as it would appear in a DEX file like "LX/JxK;", return the demangled version if we have a proguard file, otherwise return the original class typename
Given a mangled type name as it would appear in a DEX file like "LX/JxK;", return the demangled version if we have a proguard file, otherwise return the original class typename
[ "Given", "a", "mangled", "type", "name", "as", "it", "would", "appear", "in", "a", "DEX", "file", "like", "LX", "/", "JxK", ";", "return", "the", "demangled", "version", "if", "we", "have", "a", "proguard", "file", "otherwise", "return", "the", "original", "class", "typename" ]
def demangle_class_name(self, cls_mangled): """Given a mangled type name as it would appear in a DEX file like "LX/JxK;", return the demangled version if we have a proguard file, otherwise return the original class typename""" if self.proguard: cls_demangled = demangle_classname(cls_mangled) if cls_demangled: return self.proguard.lookup_class(cls_demangled) return None
[ "def", "demangle_class_name", "(", "self", ",", "cls_mangled", ")", ":", "if", "self", ".", "proguard", ":", "cls_demangled", "=", "demangle_classname", "(", "cls_mangled", ")", "if", "cls_demangled", ":", "return", "self", ".", "proguard", ".", "lookup_class", "(", "cls_demangled", ")", "return", "None" ]
https://github.com/facebook/redex/blob/fac189a289bca2647061f9e364016afc1096500d/tools/python/dex.py#L1759-L1767
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.SetTabWidth
(*args, **kwargs)
return _stc.StyledTextCtrl_SetTabWidth(*args, **kwargs)
SetTabWidth(self, int tabWidth) Change the visible size of a tab to be a multiple of the width of a space character.
SetTabWidth(self, int tabWidth)
[ "SetTabWidth", "(", "self", "int", "tabWidth", ")" ]
def SetTabWidth(*args, **kwargs): """ SetTabWidth(self, int tabWidth) Change the visible size of a tab to be a multiple of the width of a space character. """ return _stc.StyledTextCtrl_SetTabWidth(*args, **kwargs)
[ "def", "SetTabWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetTabWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L2304-L2310
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py
python
_trie
(tags, index)
return (trie_node(char, subtags) for char, subtags in char_subtags)
Make a trie from list of tags, starting at index. Resulting trie is partly space-optimized (semi-radix tree): once have only one string left, compact the entire branch to one leaf node. However, does not compact branch nodes with a single child. (FIXME) Returns: (char, subtrie, tag, conditions): (char, trie, str, list) code generation differs between branch nodes and leaf nodes, hence need different data for each. Arguments: tags: sorted list (sorted needed by groupby, list needed by len) index: index at which to branch (assumes prior to this index strings have a common prefix)
Make a trie from list of tags, starting at index.
[ "Make", "a", "trie", "from", "list", "of", "tags", "starting", "at", "index", "." ]
def _trie(tags, index): """Make a trie from list of tags, starting at index. Resulting trie is partly space-optimized (semi-radix tree): once have only one string left, compact the entire branch to one leaf node. However, does not compact branch nodes with a single child. (FIXME) Returns: (char, subtrie, tag, conditions): (char, trie, str, list) code generation differs between branch nodes and leaf nodes, hence need different data for each. Arguments: tags: sorted list (sorted needed by groupby, list needed by len) index: index at which to branch (assumes prior to this index strings have a common prefix) """ def trie_node(char, subtags_iter): # Pass in |char| so we can include in same tuple without unpacking subtags = list(subtags_iter) # need list for len if len(subtags) == 1: # terminal node, no subtrie subtrie = None tag = subtags[0] conditions = _conditions(tag, index + 1) else: subtrie = _trie(subtags, index + 1) tag = None conditions = None return char, subtrie, tag, conditions # Group by char at index def char_at_index(tag): return tag[index].lower() char_subtags = ((k, g) for k, g in groupby(tags, char_at_index)) # FIXME: if all subtags have a common prefix, merge with child # and skip the switch in the generated code return (trie_node(char, subtags) for char, subtags in char_subtags)
[ "def", "_trie", "(", "tags", ",", "index", ")", ":", "def", "trie_node", "(", "char", ",", "subtags_iter", ")", ":", "# Pass in |char| so we can include in same tuple without unpacking", "subtags", "=", "list", "(", "subtags_iter", ")", "# need list for len", "if", "len", "(", "subtags", ")", "==", "1", ":", "# terminal node, no subtrie", "subtrie", "=", "None", "tag", "=", "subtags", "[", "0", "]", "conditions", "=", "_conditions", "(", "tag", ",", "index", "+", "1", ")", "else", ":", "subtrie", "=", "_trie", "(", "subtags", ",", "index", "+", "1", ")", "tag", "=", "None", "conditions", "=", "None", "return", "char", ",", "subtrie", ",", "tag", ",", "conditions", "# Group by char at index", "def", "char_at_index", "(", "tag", ")", ":", "return", "tag", "[", "index", "]", ".", "lower", "(", ")", "char_subtags", "=", "(", "(", "k", ",", "g", ")", "for", "k", ",", "g", "in", "groupby", "(", "tags", ",", "char_at_index", ")", ")", "# FIXME: if all subtags have a common prefix, merge with child", "# and skip the switch in the generated code", "return", "(", "trie_node", "(", "char", ",", "subtags", ")", "for", "char", ",", "subtags", "in", "char_subtags", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py#L39-L79
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/pexpect/pexpect.py
python
spawn.setecho
(self, state)
This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') # Echo is on by default. p.sendline('1234') # We expect see this twice from the child... p.expect(['1234']) # ... once from the tty echo... p.expect(['1234']) # ... and again from cat itself. p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['abcd']) p.expect(['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline('1234') p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['1234']) p.expect(['1234']) p.expect(['abcd']) p.expect(['wxyz'])
This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected::
[ "This", "sets", "the", "terminal", "echo", "mode", "on", "or", "off", ".", "Note", "that", "anything", "the", "child", "sent", "before", "the", "echo", "will", "be", "lost", "so", "you", "should", "be", "sure", "that", "your", "input", "buffer", "is", "empty", "before", "you", "call", "setecho", "()", ".", "For", "example", "the", "following", "will", "work", "as", "expected", "::" ]
def setecho(self, state): """This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn('cat') # Echo is on by default. p.sendline('1234') # We expect see this twice from the child... p.expect(['1234']) # ... once from the tty echo... p.expect(['1234']) # ... and again from cat itself. p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['abcd']) p.expect(['wxyz']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn('cat') p.sendline('1234') p.setecho(False) # Turn off tty echo p.sendline('abcd') # We will set this only once (echoed by cat). p.sendline('wxyz') # We will set this only once (echoed by cat) p.expect(['1234']) p.expect(['1234']) p.expect(['abcd']) p.expect(['wxyz']) """ self.child_fd attr = termios.tcgetattr(self.child_fd) if state: attr[3] = attr[3] | termios.ECHO else: attr[3] = attr[3] & ~termios.ECHO # I tried TCSADRAIN and TCSAFLUSH, but # these were inconsistent and blocked on some platforms. # TCSADRAIN would probably be ideal if it worked. termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
[ "def", "setecho", "(", "self", ",", "state", ")", ":", "self", ".", "child_fd", "attr", "=", "termios", ".", "tcgetattr", "(", "self", ".", "child_fd", ")", "if", "state", ":", "attr", "[", "3", "]", "=", "attr", "[", "3", "]", "|", "termios", ".", "ECHO", "else", ":", "attr", "[", "3", "]", "=", "attr", "[", "3", "]", "&", "~", "termios", ".", "ECHO", "# I tried TCSADRAIN and TCSAFLUSH, but", "# these were inconsistent and blocked on some platforms.", "# TCSADRAIN would probably be ideal if it worked.", "termios", ".", "tcsetattr", "(", "self", ".", "child_fd", ",", "termios", ".", "TCSANOW", ",", "attr", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pexpect/pexpect.py#L771-L811
NASA-SW-VnV/ikos
71325dfb94737332542caa708d7537752021522d
analyzer/python/ikos/view.py
python
Formatter._build_checks
(self, statement_reports)
return checks
Return the list of check for a source line
Return the list of check for a source line
[ "Return", "the", "list", "of", "check", "for", "a", "source", "line" ]
def _build_checks(self, statement_reports): ''' Return the list of check for a source line ''' checks = [] for statement_report in statement_reports: statement = statement_report.statement() checks.append({ 'kind': statement_report.kind, 'status': statement_report.status, 'column': statement.column_or('?'), 'message': report.generate_message(statement_report, 4), 'function_id': statement.function_id, 'call_context_ids': statement_report.call_context_ids, }) self._build_function(statement.function()) self._build_call_contexts(statement_report.call_contexts()) # Sort by status (error > warning > ok) checks.sort(key=operator.itemgetter('status'), reverse=True) return checks
[ "def", "_build_checks", "(", "self", ",", "statement_reports", ")", ":", "checks", "=", "[", "]", "for", "statement_report", "in", "statement_reports", ":", "statement", "=", "statement_report", ".", "statement", "(", ")", "checks", ".", "append", "(", "{", "'kind'", ":", "statement_report", ".", "kind", ",", "'status'", ":", "statement_report", ".", "status", ",", "'column'", ":", "statement", ".", "column_or", "(", "'?'", ")", ",", "'message'", ":", "report", ".", "generate_message", "(", "statement_report", ",", "4", ")", ",", "'function_id'", ":", "statement", ".", "function_id", ",", "'call_context_ids'", ":", "statement_report", ".", "call_context_ids", ",", "}", ")", "self", ".", "_build_function", "(", "statement", ".", "function", "(", ")", ")", "self", ".", "_build_call_contexts", "(", "statement_report", ".", "call_contexts", "(", ")", ")", "# Sort by status (error > warning > ok)", "checks", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "'status'", ")", ",", "reverse", "=", "True", ")", "return", "checks" ]
https://github.com/NASA-SW-VnV/ikos/blob/71325dfb94737332542caa708d7537752021522d/analyzer/python/ikos/view.py#L485-L505
AojunZhou/Incremental-Network-Quantization
c7f6a609d5817d8424ce224209cf4c50f1e4de50
python/caffe/io.py
python
Transformer.set_channel_swap
(self, in_, order)
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example.
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose.
[ "Set", "the", "input", "channel", "order", "for", "e", ".", "g", ".", "RGB", "to", "BGR", "conversion", "as", "needed", "for", "the", "reference", "ImageNet", "model", ".", "N", ".", "B", ".", "this", "assumes", "the", "channels", "are", "the", "first", "dimension", "AFTER", "transpose", "." ]
def set_channel_swap(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example. """ self.__check_input(in_) if len(order) != self.inputs[in_][1]: raise Exception('Channel swap needs to have the same number of ' 'dimensions as the input channels.') self.channel_swap[in_] = order
[ "def", "set_channel_swap", "(", "self", ",", "in_", ",", "order", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "if", "len", "(", "order", ")", "!=", "self", ".", "inputs", "[", "in_", "]", "[", "1", "]", ":", "raise", "Exception", "(", "'Channel swap needs to have the same number of '", "'dimensions as the input channels.'", ")", "self", ".", "channel_swap", "[", "in_", "]", "=", "order" ]
https://github.com/AojunZhou/Incremental-Network-Quantization/blob/c7f6a609d5817d8424ce224209cf4c50f1e4de50/python/caffe/io.py#L203-L219
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.py
python
_IncludeState.ResetSection
(self, directive)
Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else").
Reset section checking for preprocessor directive.
[ "Reset", "section", "checking", "for", "preprocessor", "directive", "." ]
def ResetSection(self, directive): """Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else"). """ # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' # Update list of includes. Note that we never pop from the # include list. if directive in ('if', 'ifdef', 'ifndef'): self.include_list.append([]) elif directive in ('else', 'elif'): self.include_list[-1] = []
[ "def", "ResetSection", "(", "self", ",", "directive", ")", ":", "# The name of the current section.", "self", ".", "_section", "=", "self", ".", "_INITIAL_SECTION", "# The path of last found header.", "self", ".", "_last_header", "=", "''", "# Update list of includes. Note that we never pop from the", "# include list.", "if", "directive", "in", "(", "'if'", ",", "'ifdef'", ",", "'ifndef'", ")", ":", "self", ".", "include_list", ".", "append", "(", "[", "]", ")", "elif", "directive", "in", "(", "'else'", ",", "'elif'", ")", ":", "self", ".", "include_list", "[", "-", "1", "]", "=", "[", "]" ]
https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L739-L755
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py
python
LinuxDistribution.linux_distribution
(self, full_distribution_name=True)
return ( self.name() if full_distribution_name else self.id(), self.version(), self.codename() )
Return information about the OS distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters. For details, see :func:`distro.linux_distribution`.
[]
def linux_distribution(self, full_distribution_name=True): """ Return information about the OS distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters. For details, see :func:`distro.linux_distribution`. """ return ( self.name() if full_distribution_name else self.id(), self.version(), self.codename() )
[ "def", "linux_distribution", "(", "self", ",", "full_distribution_name", "=", "True", ")", ":", "return", "(", "self", ".", "name", "(", ")", "if", "full_distribution_name", "else", "self", ".", "id", "(", ")", ",", "self", ".", "version", "(", ")", ",", "self", ".", "codename", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py#L1341-L1365
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/tensor_array_ops.py
python
TensorArray.scatter
(self, indices, value, name=None)
Scatter the values of a `Tensor` in specific indices of a `TensorArray`. Args: indices: A `1-D` `Tensor` taking values in `[0, max_value)`. If the `TensorArray` is not dynamic, `max_value=size()`. value: (N+1)-D. Tensor of type `dtype`. The Tensor to unpack. name: A name for the operation (optional). Returns: A new TensorArray object with flow that ensures the scatter occurs. Use this object all for subsequent operations. Raises: ValueError: if the shape inference fails.
Scatter the values of a `Tensor` in specific indices of a `TensorArray`.
[ "Scatter", "the", "values", "of", "a", "Tensor", "in", "specific", "indices", "of", "a", "TensorArray", "." ]
def scatter(self, indices, value, name=None): """Scatter the values of a `Tensor` in specific indices of a `TensorArray`. Args: indices: A `1-D` `Tensor` taking values in `[0, max_value)`. If the `TensorArray` is not dynamic, `max_value=size()`. value: (N+1)-D. Tensor of type `dtype`. The Tensor to unpack. name: A name for the operation (optional). Returns: A new TensorArray object with flow that ensures the scatter occurs. Use this object all for subsequent operations. Raises: ValueError: if the shape inference fails. """ with ops.name_scope(name, "TensorArrayScatter", [self._handle, value, indices]): value = ops.convert_to_tensor(value, name="value") with self._maybe_colocate_with(value): flow_out = gen_data_flow_ops._tensor_array_scatter_v3( handle=self._handle, indices=indices, value=value, flow_in=self._flow, name=name) ta = TensorArray( dtype=self._dtype, handle=self._handle, flow=flow_out, colocate_with_first_write_call=self._colocate_with_first_write_call) ta._infer_shape = self._infer_shape ta._element_shape = self._element_shape ta._colocate_with = self._colocate_with if ta._infer_shape: val_shape = flow_out.op.inputs[2].get_shape() element_shape = tensor_shape.unknown_shape() if val_shape.dims is not None: element_shape = tensor_shape.TensorShape(val_shape.dims[1:]) ta._merge_element_shape(element_shape) return ta
[ "def", "scatter", "(", "self", ",", "indices", ",", "value", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"TensorArrayScatter\"", ",", "[", "self", ".", "_handle", ",", "value", ",", "indices", "]", ")", ":", "value", "=", "ops", ".", "convert_to_tensor", "(", "value", ",", "name", "=", "\"value\"", ")", "with", "self", ".", "_maybe_colocate_with", "(", "value", ")", ":", "flow_out", "=", "gen_data_flow_ops", ".", "_tensor_array_scatter_v3", "(", "handle", "=", "self", ".", "_handle", ",", "indices", "=", "indices", ",", "value", "=", "value", ",", "flow_in", "=", "self", ".", "_flow", ",", "name", "=", "name", ")", "ta", "=", "TensorArray", "(", "dtype", "=", "self", ".", "_dtype", ",", "handle", "=", "self", ".", "_handle", ",", "flow", "=", "flow_out", ",", "colocate_with_first_write_call", "=", "self", ".", "_colocate_with_first_write_call", ")", "ta", ".", "_infer_shape", "=", "self", ".", "_infer_shape", "ta", ".", "_element_shape", "=", "self", ".", "_element_shape", "ta", ".", "_colocate_with", "=", "self", ".", "_colocate_with", "if", "ta", ".", "_infer_shape", ":", "val_shape", "=", "flow_out", ".", "op", ".", "inputs", "[", "2", "]", ".", "get_shape", "(", ")", "element_shape", "=", "tensor_shape", ".", "unknown_shape", "(", ")", "if", "val_shape", ".", "dims", "is", "not", "None", ":", "element_shape", "=", "tensor_shape", ".", "TensorShape", "(", "val_shape", ".", "dims", "[", "1", ":", "]", ")", "ta", ".", "_merge_element_shape", "(", "element_shape", ")", "return", "ta" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/tensor_array_ops.py#L416-L454
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/prefilter.py
python
PrefilterManager.get_handler_by_esc
(self, esc_str)
return self._esc_handlers.get(esc_str)
Get a handler by its escape string.
Get a handler by its escape string.
[ "Get", "a", "handler", "by", "its", "escape", "string", "." ]
def get_handler_by_esc(self, esc_str): """Get a handler by its escape string.""" return self._esc_handlers.get(esc_str)
[ "def", "get_handler_by_esc", "(", "self", ",", "esc_str", ")", ":", "return", "self", ".", "_esc_handlers", ".", "get", "(", "esc_str", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/prefilter.py#L238-L240
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py
python
CompletionState.go_to_index
(self, index)
return CompletionState(self.original_document, self.current_completions, complete_index=index)
Create a new :class:`.CompletionState` object with the new index.
Create a new :class:`.CompletionState` object with the new index.
[ "Create", "a", "new", ":", "class", ":", ".", "CompletionState", "object", "with", "the", "new", "index", "." ]
def go_to_index(self, index): """ Create a new :class:`.CompletionState` object with the new index. """ return CompletionState(self.original_document, self.current_completions, complete_index=index)
[ "def", "go_to_index", "(", "self", ",", "index", ")", ":", "return", "CompletionState", "(", "self", ".", "original_document", ",", "self", ".", "current_completions", ",", "complete_index", "=", "index", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py#L132-L136
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/msvccompiler.py
python
MSVCCompiler.get_msvc_paths
(self, path, platform='x86')
return []
Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found.
Get a list of devstudio directories (include, lib or path).
[ "Get", "a", "list", "of", "devstudio", "directories", "(", "include", "lib", "or", "path", ")", "." ]
def get_msvc_paths(self, path, platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found. """ if not _can_read_reg: return [] path = path + " dirs" if self.__version >= 7: key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories" % (self.__root, self.__version)) else: key = (r"%s\6.0\Build System\Components\Platforms" r"\Win32 (%s)\Directories" % (self.__root, platform)) for base in HKEYS: d = read_values(base, key) if d: if self.__version >= 7: return string.split(self.__macros.sub(d[path]), ";") else: return string.split(d[path], ";") # MSVC 6 seems to create the registry entries we need only when # the GUI is run. if self.__version == 6: for base in HKEYS: if read_values(base, r"%s\6.0" % self.__root) is not None: self.warn("It seems you have Visual Studio 6 installed, " "but the expected registry settings are not present.\n" "You must at least run the Visual Studio GUI once " "so that these entries are created.") break return []
[ "def", "get_msvc_paths", "(", "self", ",", "path", ",", "platform", "=", "'x86'", ")", ":", "if", "not", "_can_read_reg", ":", "return", "[", "]", "path", "=", "path", "+", "\" dirs\"", "if", "self", ".", "__version", ">=", "7", ":", "key", "=", "(", "r\"%s\\%0.1f\\VC\\VC_OBJECTS_PLATFORM_INFO\\Win32\\Directories\"", "%", "(", "self", ".", "__root", ",", "self", ".", "__version", ")", ")", "else", ":", "key", "=", "(", "r\"%s\\6.0\\Build System\\Components\\Platforms\"", "r\"\\Win32 (%s)\\Directories\"", "%", "(", "self", ".", "__root", ",", "platform", ")", ")", "for", "base", "in", "HKEYS", ":", "d", "=", "read_values", "(", "base", ",", "key", ")", "if", "d", ":", "if", "self", ".", "__version", ">=", "7", ":", "return", "string", ".", "split", "(", "self", ".", "__macros", ".", "sub", "(", "d", "[", "path", "]", ")", ",", "\";\"", ")", "else", ":", "return", "string", ".", "split", "(", "d", "[", "path", "]", ",", "\";\"", ")", "# MSVC 6 seems to create the registry entries we need only when", "# the GUI is run.", "if", "self", ".", "__version", "==", "6", ":", "for", "base", "in", "HKEYS", ":", "if", "read_values", "(", "base", ",", "r\"%s\\6.0\"", "%", "self", ".", "__root", ")", "is", "not", "None", ":", "self", ".", "warn", "(", "\"It seems you have Visual Studio 6 installed, \"", "\"but the expected registry settings are not present.\\n\"", "\"You must at least run the Visual Studio GUI once \"", "\"so that these entries are created.\"", ")", "break", "return", "[", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/msvccompiler.py#L602-L637
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_trustregion_exact.py
python
gershgorin_bounds
(H)
return lb, ub
Given a square matrix ``H`` compute upper and lower bounds for its eigenvalues (Gregoshgorin Bounds). Defined ref. [1]. References ---------- .. [1] Conn, A. R., Gould, N. I., & Toint, P. L. Trust region methods. 2000. Siam. pp. 19.
Given a square matrix ``H`` compute upper and lower bounds for its eigenvalues (Gregoshgorin Bounds). Defined ref. [1].
[ "Given", "a", "square", "matrix", "H", "compute", "upper", "and", "lower", "bounds", "for", "its", "eigenvalues", "(", "Gregoshgorin", "Bounds", ")", ".", "Defined", "ref", ".", "[", "1", "]", "." ]
def gershgorin_bounds(H): """ Given a square matrix ``H`` compute upper and lower bounds for its eigenvalues (Gregoshgorin Bounds). Defined ref. [1]. References ---------- .. [1] Conn, A. R., Gould, N. I., & Toint, P. L. Trust region methods. 2000. Siam. pp. 19. """ H_diag = np.diag(H) H_diag_abs = np.abs(H_diag) H_row_sums = np.sum(np.abs(H), axis=1) lb = np.min(H_diag + H_diag_abs - H_row_sums) ub = np.max(H_diag - H_diag_abs + H_row_sums) return lb, ub
[ "def", "gershgorin_bounds", "(", "H", ")", ":", "H_diag", "=", "np", ".", "diag", "(", "H", ")", "H_diag_abs", "=", "np", ".", "abs", "(", "H_diag", ")", "H_row_sums", "=", "np", ".", "sum", "(", "np", ".", "abs", "(", "H", ")", ",", "axis", "=", "1", ")", "lb", "=", "np", ".", "min", "(", "H_diag", "+", "H_diag_abs", "-", "H_row_sums", ")", "ub", "=", "np", ".", "max", "(", "H_diag", "-", "H_diag_abs", "+", "H_row_sums", ")", "return", "lb", ",", "ub" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_trustregion_exact.py#L125-L143
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
DC.DeviceToLogicalX
(*args, **kwargs)
return _gdi_.DC_DeviceToLogicalX(*args, **kwargs)
DeviceToLogicalX(self, int x) -> int Convert device X coordinate to logical coordinate, using the current mapping mode.
DeviceToLogicalX(self, int x) -> int
[ "DeviceToLogicalX", "(", "self", "int", "x", ")", "-", ">", "int" ]
def DeviceToLogicalX(*args, **kwargs): """ DeviceToLogicalX(self, int x) -> int Convert device X coordinate to logical coordinate, using the current mapping mode. """ return _gdi_.DC_DeviceToLogicalX(*args, **kwargs)
[ "def", "DeviceToLogicalX", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_DeviceToLogicalX", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L4219-L4226
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/ops.py
python
Operation._set_device
(self, device)
Set the device of this operation. Args: device: string or device.. The device to set.
Set the device of this operation.
[ "Set", "the", "device", "of", "this", "operation", "." ]
def _set_device(self, device): """Set the device of this operation. Args: device: string or device.. The device to set. """ self._node_def.device = _device_string(device)
[ "def", "_set_device", "(", "self", ",", "device", ")", ":", "self", ".", "_node_def", ".", "device", "=", "_device_string", "(", "device", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L1371-L1377
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py
python
DatetimeLikeArrayMixin._time_shift
(self, periods, freq=None)
return self._generate_range(start=start, end=end, periods=None, freq=self.freq)
Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int Number of periods to shift by. freq : pandas.DateOffset, pandas.Timedelta, or string Frequency increment to shift by.
Shift each value by `periods`.
[ "Shift", "each", "value", "by", "periods", "." ]
def _time_shift(self, periods, freq=None): """ Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int Number of periods to shift by. freq : pandas.DateOffset, pandas.Timedelta, or string Frequency increment to shift by. """ if freq is not None and freq != self.freq: if isinstance(freq, compat.string_types): freq = frequencies.to_offset(freq) offset = periods * freq result = self + offset return result if periods == 0: # immutable so OK return self.copy() if self.freq is None: raise NullFrequencyError("Cannot shift with no freq") start = self[0] + periods * self.freq end = self[-1] + periods * self.freq # Note: in the DatetimeTZ case, _generate_range will infer the # appropriate timezone from `start` and `end`, so tz does not need # to be passed explicitly. return self._generate_range(start=start, end=end, periods=None, freq=self.freq)
[ "def", "_time_shift", "(", "self", ",", "periods", ",", "freq", "=", "None", ")", ":", "if", "freq", "is", "not", "None", "and", "freq", "!=", "self", ".", "freq", ":", "if", "isinstance", "(", "freq", ",", "compat", ".", "string_types", ")", ":", "freq", "=", "frequencies", ".", "to_offset", "(", "freq", ")", "offset", "=", "periods", "*", "freq", "result", "=", "self", "+", "offset", "return", "result", "if", "periods", "==", "0", ":", "# immutable so OK", "return", "self", ".", "copy", "(", ")", "if", "self", ".", "freq", "is", "None", ":", "raise", "NullFrequencyError", "(", "\"Cannot shift with no freq\"", ")", "start", "=", "self", "[", "0", "]", "+", "periods", "*", "self", ".", "freq", "end", "=", "self", "[", "-", "1", "]", "+", "periods", "*", "self", ".", "freq", "# Note: in the DatetimeTZ case, _generate_range will infer the", "# appropriate timezone from `start` and `end`, so tz does not need", "# to be passed explicitly.", "return", "self", ".", "_generate_range", "(", "start", "=", "start", ",", "end", "=", "end", ",", "periods", "=", "None", ",", "freq", "=", "self", ".", "freq", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py#L1140-L1176
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/utils/type_check.py
python
is_tensor
(*args)
return any(tensor_util.is_tensor(a) for a in args)
Check if any arguments are tensors. Args: *args: Python objects that may or may not be tensors. Returns: True if any *args are TensorFlow types, False if none are.
Check if any arguments are tensors.
[ "Check", "if", "any", "arguments", "are", "tensors", "." ]
def is_tensor(*args): """Check if any arguments are tensors. Args: *args: Python objects that may or may not be tensors. Returns: True if any *args are TensorFlow types, False if none are. """ return any(tensor_util.is_tensor(a) for a in args)
[ "def", "is_tensor", "(", "*", "args", ")", ":", "return", "any", "(", "tensor_util", ".", "is_tensor", "(", "a", ")", "for", "a", "in", "args", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/utils/type_check.py#L24-L33
alexgkendall/caffe-posenet
62aafbd7c45df91acdba14f5d1406d8295c2bc6f
scripts/cpp_lint.py
python
_DropCommonSuffixes
(filename)
return os.path.splitext(filename)[0]
Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed.
Drops common suffixes like _test.cc or -inl.h from filename.
[ "Drops", "common", "suffixes", "like", "_test", ".", "cc", "or", "-", "inl", ".", "h", "from", "filename", "." ]
def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0]
[ "def", "_DropCommonSuffixes", "(", "filename", ")", ":", "for", "suffix", "in", "(", "'test.cc'", ",", "'regtest.cc'", ",", "'unittest.cc'", ",", "'inl.h'", ",", "'impl.h'", ",", "'internal.h'", ")", ":", "if", "(", "filename", ".", "endswith", "(", "suffix", ")", "and", "len", "(", "filename", ")", ">", "len", "(", "suffix", ")", "and", "filename", "[", "-", "len", "(", "suffix", ")", "-", "1", "]", "in", "(", "'-'", ",", "'_'", ")", ")", ":", "return", "filename", "[", ":", "-", "len", "(", "suffix", ")", "-", "1", "]", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]" ]
https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/scripts/cpp_lint.py#L3576-L3600
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/vcs/__init__.py
python
RevOptions.make_new
(self, rev)
return self.vcs.make_rev_options(rev, extra_args=self.extra_args)
Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object.
Make a copy of the current instance, but with a new rev.
[ "Make", "a", "copy", "of", "the", "current", "instance", "but", "with", "a", "new", "rev", "." ]
def make_new(self, rev): # type: (str) -> RevOptions """ Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. """ return self.vcs.make_rev_options(rev, extra_args=self.extra_args)
[ "def", "make_new", "(", "self", ",", "rev", ")", ":", "# type: (str) -> RevOptions", "return", "self", ".", "vcs", ".", "make_rev_options", "(", "rev", ",", "extra_args", "=", "self", ".", "extra_args", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/vcs/__init__.py#L91-L99
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/_learnable_fake_quantize.py
python
_LearnableFakeQuantize.enable_static_estimate
(self)
r"""Enables static observer estimates and disbales learning of quantization parameters. Forward path returns fake quantized X.
r"""Enables static observer estimates and disbales learning of quantization parameters. Forward path returns fake quantized X.
[ "r", "Enables", "static", "observer", "estimates", "and", "disbales", "learning", "of", "quantization", "parameters", ".", "Forward", "path", "returns", "fake", "quantized", "X", "." ]
def enable_static_estimate(self): r"""Enables static observer estimates and disbales learning of quantization parameters. Forward path returns fake quantized X. """ self.toggle_qparam_learning(enabled=False) \ .toggle_fake_quant(enabled=True) \ .toggle_observer_update(enabled=True)
[ "def", "enable_static_estimate", "(", "self", ")", ":", "self", ".", "toggle_qparam_learning", "(", "enabled", "=", "False", ")", ".", "toggle_fake_quant", "(", "enabled", "=", "True", ")", ".", "toggle_observer_update", "(", "enabled", "=", "True", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/_learnable_fake_quantize.py#L75-L81
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/CacheDir.py
python
CacheDir.retrieve
(self, node)
return False
This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Note that there's a special trick here with the execute flag (one that's not normally done for other actions). Basically if the user requested a no_exec (-n) build, then SCons.Action.execute_actions is set to 0 and when any action is called, it does its showing but then just returns zero instead of actually calling the action execution operation. The problem for caching is that if the file does NOT exist in cache then the CacheRetrieveString won't return anything to show for the task, but the Action.__call__ won't call CacheRetrieveFunc; instead it just returns zero, which makes the code below think that the file *was* successfully retrieved from the cache, therefore it doesn't do any subsequent building. However, the CacheRetrieveString didn't print anything because it didn't actually exist in the cache, and no more build actions will be performed, so the user just sees nothing. The fix is to tell Action.__call__ to always execute the CacheRetrieveFunc and then have the latter explicitly check SCons.Action.execute_actions itself.
This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built().
[ "This", "method", "is", "called", "from", "multiple", "threads", "in", "a", "parallel", "build", "so", "only", "do", "thread", "safe", "stuff", "here", ".", "Do", "thread", "unsafe", "stuff", "in", "built", "()", "." ]
def retrieve(self, node): """ This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Note that there's a special trick here with the execute flag (one that's not normally done for other actions). Basically if the user requested a no_exec (-n) build, then SCons.Action.execute_actions is set to 0 and when any action is called, it does its showing but then just returns zero instead of actually calling the action execution operation. The problem for caching is that if the file does NOT exist in cache then the CacheRetrieveString won't return anything to show for the task, but the Action.__call__ won't call CacheRetrieveFunc; instead it just returns zero, which makes the code below think that the file *was* successfully retrieved from the cache, therefore it doesn't do any subsequent building. However, the CacheRetrieveString didn't print anything because it didn't actually exist in the cache, and no more build actions will be performed, so the user just sees nothing. The fix is to tell Action.__call__ to always execute the CacheRetrieveFunc and then have the latter explicitly check SCons.Action.execute_actions itself. """ if not self.is_enabled(): return False env = node.get_build_env() if cache_show: if CacheRetrieveSilent(node, [], env, execute=1) == 0: node.build(presub=0, execute=0) return True else: if CacheRetrieve(node, [], env, execute=1) == 0: return True return False
[ "def", "retrieve", "(", "self", ",", "node", ")", ":", "if", "not", "self", ".", "is_enabled", "(", ")", ":", "return", "False", "env", "=", "node", ".", "get_build_env", "(", ")", "if", "cache_show", ":", "if", "CacheRetrieveSilent", "(", "node", ",", "[", "]", ",", "env", ",", "execute", "=", "1", ")", "==", "0", ":", "node", ".", "build", "(", "presub", "=", "0", ",", "execute", "=", "0", ")", "return", "True", "else", ":", "if", "CacheRetrieve", "(", "node", ",", "[", "]", ",", "env", ",", "execute", "=", "1", ")", "==", "0", ":", "return", "True", "return", "False" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/CacheDir.py#L229-L266
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/tlslite/tlslite/X509.py
python
X509.parse
(self, s)
return self
Parse a PEM-encoded X.509 certificate. @type s: str @param s: A PEM-encoded X.509 certificate (i.e. a base64-encoded certificate wrapped with "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" tags).
Parse a PEM-encoded X.509 certificate.
[ "Parse", "a", "PEM", "-", "encoded", "X", ".", "509", "certificate", "." ]
def parse(self, s): """Parse a PEM-encoded X.509 certificate. @type s: str @param s: A PEM-encoded X.509 certificate (i.e. a base64-encoded certificate wrapped with "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" tags). """ start = s.find("-----BEGIN CERTIFICATE-----") end = s.find("-----END CERTIFICATE-----") if start == -1: raise SyntaxError("Missing PEM prefix") if end == -1: raise SyntaxError("Missing PEM postfix") s = s[start+len("-----BEGIN CERTIFICATE-----") : end] bytes = base64ToBytes(s) self.parseBinary(bytes) return self
[ "def", "parse", "(", "self", ",", "s", ")", ":", "start", "=", "s", ".", "find", "(", "\"-----BEGIN CERTIFICATE-----\"", ")", "end", "=", "s", ".", "find", "(", "\"-----END CERTIFICATE-----\"", ")", "if", "start", "==", "-", "1", ":", "raise", "SyntaxError", "(", "\"Missing PEM prefix\"", ")", "if", "end", "==", "-", "1", ":", "raise", "SyntaxError", "(", "\"Missing PEM postfix\"", ")", "s", "=", "s", "[", "start", "+", "len", "(", "\"-----BEGIN CERTIFICATE-----\"", ")", ":", "end", "]", "bytes", "=", "base64ToBytes", "(", "s", ")", "self", ".", "parseBinary", "(", "bytes", ")", "return", "self" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/X509.py#L26-L45
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/layer_norm_beta_gamma_backprop_ds.py
python
_layer_norm_beta_gamma_backprop_ds_tbe
()
return
LayerNormBetaGammaBackprop TBE register
LayerNormBetaGammaBackprop TBE register
[ "LayerNormBetaGammaBackprop", "TBE", "register" ]
def _layer_norm_beta_gamma_backprop_ds_tbe(): """LayerNormBetaGammaBackprop TBE register""" return
[ "def", "_layer_norm_beta_gamma_backprop_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/layer_norm_beta_gamma_backprop_ds.py#L43-L45
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/protobuf/python/mox.py
python
MockAnything.__getattr__
(self, method_name)
return self._CreateMockMethod(method_name)
Intercept method calls on this object. A new MockMethod is returned that is aware of the MockAnything's state (record or replay). The call will be recorded or replayed by the MockMethod's __call__. Args: # method name: the name of the method being called. method_name: str Returns: A new MockMethod aware of MockAnything's state (record or replay).
Intercept method calls on this object.
[ "Intercept", "method", "calls", "on", "this", "object", "." ]
def __getattr__(self, method_name): """Intercept method calls on this object. A new MockMethod is returned that is aware of the MockAnything's state (record or replay). The call will be recorded or replayed by the MockMethod's __call__. Args: # method name: the name of the method being called. method_name: str Returns: A new MockMethod aware of MockAnything's state (record or replay). """ return self._CreateMockMethod(method_name)
[ "def", "__getattr__", "(", "self", ",", "method_name", ")", ":", "return", "self", ".", "_CreateMockMethod", "(", "method_name", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/mox.py#L278-L293
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/numeric.py
python
geterrcall
()
return umath.geterrobj()[2]
Return the current callback function used on floating-point errors. When the error handling for a floating-point error (one of "divide", "over", "under", or "invalid") is set to 'call' or 'log', the function that is called or the log instance that is written to is returned by `geterrcall`. This function or log instance has been set with `seterrcall`. Returns ------- errobj : callable, log instance or None The current error handler. If no handler was set through `seterrcall`, ``None`` is returned. See Also -------- seterrcall, seterr, geterr Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> np.geterrcall() # we did not yet set a handler, returns None >>> oldsettings = np.seterr(all='call') >>> def err_handler(type, flag): ... print "Floating point error (%s), with flag %s" % (type, flag) >>> oldhandler = np.seterrcall(err_handler) >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 array([ Inf, Inf, Inf]) >>> cur_handler = np.geterrcall() >>> cur_handler is err_handler True
Return the current callback function used on floating-point errors.
[ "Return", "the", "current", "callback", "function", "used", "on", "floating", "-", "point", "errors", "." ]
def geterrcall(): """ Return the current callback function used on floating-point errors. When the error handling for a floating-point error (one of "divide", "over", "under", or "invalid") is set to 'call' or 'log', the function that is called or the log instance that is written to is returned by `geterrcall`. This function or log instance has been set with `seterrcall`. Returns ------- errobj : callable, log instance or None The current error handler. If no handler was set through `seterrcall`, ``None`` is returned. See Also -------- seterrcall, seterr, geterr Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> np.geterrcall() # we did not yet set a handler, returns None >>> oldsettings = np.seterr(all='call') >>> def err_handler(type, flag): ... print "Floating point error (%s), with flag %s" % (type, flag) >>> oldhandler = np.seterrcall(err_handler) >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 array([ Inf, Inf, Inf]) >>> cur_handler = np.geterrcall() >>> cur_handler is err_handler True """ return umath.geterrobj()[2]
[ "def", "geterrcall", "(", ")", ":", "return", "umath", ".", "geterrobj", "(", ")", "[", "2", "]" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/numeric.py#L2591-L2633
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/options.py
python
OptionParser.mockable
(self)
return _Mockable(self)
Returns a wrapper around self that is compatible with `mock.patch <unittest.mock.patch>`. The `mock.patch <unittest.mock.patch>` function (included in the standard library `unittest.mock` package since Python 3.3, or in the third-party ``mock`` package for older versions of Python) is incompatible with objects like ``options`` that override ``__getattr__`` and ``__setattr__``. This function returns an object that can be used with `mock.patch.object <unittest.mock.patch.object>` to modify option values:: with mock.patch.object(options.mockable(), 'name', value): assert options.name == value
Returns a wrapper around self that is compatible with `mock.patch <unittest.mock.patch>`.
[ "Returns", "a", "wrapper", "around", "self", "that", "is", "compatible", "with", "mock", ".", "patch", "<unittest", ".", "mock", ".", "patch", ">", "." ]
def mockable(self) -> "_Mockable": """Returns a wrapper around self that is compatible with `mock.patch <unittest.mock.patch>`. The `mock.patch <unittest.mock.patch>` function (included in the standard library `unittest.mock` package since Python 3.3, or in the third-party ``mock`` package for older versions of Python) is incompatible with objects like ``options`` that override ``__getattr__`` and ``__setattr__``. This function returns an object that can be used with `mock.patch.object <unittest.mock.patch.object>` to modify option values:: with mock.patch.object(options.mockable(), 'name', value): assert options.name == value """ return _Mockable(self)
[ "def", "mockable", "(", "self", ")", "->", "\"_Mockable\"", ":", "return", "_Mockable", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/options.py#L470-L485
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/llbuild/bindings/python/llbuild.py
python
BuildEngine.task_discovered_dependency
(self, task, key)
\ task_discovered_dependency(task, key) Inform the engine of an input dependency that was discovered by the task during its execution, a la compiler generated dependency files. This call may only be made after a task has received all of its inputs; inputs discovered prior to that point should simply be requested as normal input dependencies. Such a dependency is not used to provide additional input to the task, rather it is a way for the task to report an additional input which should be considered the next time the rule is evaluated. The expected use case for a discovered dependency is is when a processing task cannot predict all of its inputs prior to being run, but can presume that any unknown inputs already exist. In such cases, the task can go ahead and run and can report the all of the discovered inputs as it executes. Once the task is complete, these inputs will be recorded as being dependencies of the task so that it will be recomputed when any of the inputs change. It is legal to call this method from any thread, but the caller is responsible for ensuring that it is never called concurrently for the same task.
\ task_discovered_dependency(task, key)
[ "\\", "task_discovered_dependency", "(", "task", "key", ")" ]
def task_discovered_dependency(self, task, key): """\ task_discovered_dependency(task, key) Inform the engine of an input dependency that was discovered by the task during its execution, a la compiler generated dependency files. This call may only be made after a task has received all of its inputs; inputs discovered prior to that point should simply be requested as normal input dependencies. Such a dependency is not used to provide additional input to the task, rather it is a way for the task to report an additional input which should be considered the next time the rule is evaluated. The expected use case for a discovered dependency is is when a processing task cannot predict all of its inputs prior to being run, but can presume that any unknown inputs already exist. In such cases, the task can go ahead and run and can report the all of the discovered inputs as it executes. Once the task is complete, these inputs will be recorded as being dependencies of the task so that it will be recomputed when any of the inputs change. It is legal to call this method from any thread, but the caller is responsible for ensuring that it is never called concurrently for the same task.""" key = _Data(key) libllbuild.llb_buildengine_task_must_follow( self._engine, task._task, key.key)
[ "def", "task_discovered_dependency", "(", "self", ",", "task", ",", "key", ")", ":", "key", "=", "_Data", "(", "key", ")", "libllbuild", ".", "llb_buildengine_task_must_follow", "(", "self", ".", "_engine", ",", "task", ".", "_task", ",", "key", ".", "key", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/llbuild/bindings/python/llbuild.py#L274-L300
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/session_bundle/exporter.py
python
Exporter._file_path_value
(self, path_tensor)
return str_value[0]
Returns the filepath value stored in constant `path_tensor`.
Returns the filepath value stored in constant `path_tensor`.
[ "Returns", "the", "filepath", "value", "stored", "in", "constant", "path_tensor", "." ]
def _file_path_value(self, path_tensor): """Returns the filepath value stored in constant `path_tensor`.""" if not isinstance(path_tensor, ops.Tensor): raise TypeError("tensor is not a Tensor") if path_tensor.op.type != "Const": raise TypeError("Only constants tensor are supported") if path_tensor.dtype != dtypes.string: raise TypeError("File paths should be string") str_value = path_tensor.op.get_attr("value").string_val if len(str_value) != 1: raise TypeError("Only scalar tensors are supported") return str_value[0]
[ "def", "_file_path_value", "(", "self", ",", "path_tensor", ")", ":", "if", "not", "isinstance", "(", "path_tensor", ",", "ops", ".", "Tensor", ")", ":", "raise", "TypeError", "(", "\"tensor is not a Tensor\"", ")", "if", "path_tensor", ".", "op", ".", "type", "!=", "\"Const\"", ":", "raise", "TypeError", "(", "\"Only constants tensor are supported\"", ")", "if", "path_tensor", ".", "dtype", "!=", "dtypes", ".", "string", ":", "raise", "TypeError", "(", "\"File paths should be string\"", ")", "str_value", "=", "path_tensor", ".", "op", ".", "get_attr", "(", "\"value\"", ")", ".", "string_val", "if", "len", "(", "str_value", ")", "!=", "1", ":", "raise", "TypeError", "(", "\"Only scalar tensors are supported\"", ")", "return", "str_value", "[", "0", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/session_bundle/exporter.py#L320-L331
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
MouseEvent.GetWheelDelta
(*args, **kwargs)
return _core_.MouseEvent_GetWheelDelta(*args, **kwargs)
GetWheelDelta(self) -> int Get wheel delta, normally 120. This is the threshold for action to be taken, and one such action (for example, scrolling one increment) should occur for each delta.
GetWheelDelta(self) -> int
[ "GetWheelDelta", "(", "self", ")", "-", ">", "int" ]
def GetWheelDelta(*args, **kwargs): """ GetWheelDelta(self) -> int Get wheel delta, normally 120. This is the threshold for action to be taken, and one such action (for example, scrolling one increment) should occur for each delta. """ return _core_.MouseEvent_GetWheelDelta(*args, **kwargs)
[ "def", "GetWheelDelta", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MouseEvent_GetWheelDelta", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5812-L5820
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_latex.py
python
SyntaxData.GetCommentPattern
(self)
return [u'%']
Returns a list of characters used to comment a block of code
Returns a list of characters used to comment a block of code
[ "Returns", "a", "list", "of", "characters", "used", "to", "comment", "a", "block", "of", "code" ]
def GetCommentPattern(self): """Returns a list of characters used to comment a block of code """ return [u'%']
[ "def", "GetCommentPattern", "(", "self", ")", ":", "return", "[", "u'%'", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_latex.py#L93-L95
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_splines.py
python
BSpline.GetResources
(self)
return {'Pixmap': 'Draft_BSpline', 'Accel': "B, S", 'MenuText': QT_TRANSLATE_NOOP("Draft_BSpline", "B-spline"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_BSpline", "Creates a multiple-point B-spline. CTRL to snap, SHIFT to constrain.")}
Set icon, menu and tooltip.
Set icon, menu and tooltip.
[ "Set", "icon", "menu", "and", "tooltip", "." ]
def GetResources(self): """Set icon, menu and tooltip.""" return {'Pixmap': 'Draft_BSpline', 'Accel': "B, S", 'MenuText': QT_TRANSLATE_NOOP("Draft_BSpline", "B-spline"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_BSpline", "Creates a multiple-point B-spline. CTRL to snap, SHIFT to constrain.")}
[ "def", "GetResources", "(", "self", ")", ":", "return", "{", "'Pixmap'", ":", "'Draft_BSpline'", ",", "'Accel'", ":", "\"B, S\"", ",", "'MenuText'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_BSpline\"", ",", "\"B-spline\"", ")", ",", "'ToolTip'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_BSpline\"", ",", "\"Creates a multiple-point B-spline. CTRL to snap, SHIFT to constrain.\"", ")", "}" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_splines.py#L55-L61
kevin-ssy/Optical-Flow-Guided-Feature
07d4501a29002ee7821c38c1820e4a64c1acf6e8
lib/caffe-action/scripts/cpp_lint.py
python
CheckIncludeLine
(filename, clean_lines, linenum, include_state, error)
Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found.
Check rules that are applicable to #include lines.
[ "Check", "rules", "that", "are", "applicable", "to", "#include", "lines", "." ]
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): error(filename, linenum, 'build/include_dir', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') if include in include_state: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, include_state[include])) else: include_state[include] = linenum # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) # Look for any of the stream classes that are part of standard C++. match = _RE_PATTERN_INCLUDE.match(line) if match: include = match.group(2) if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): # Many unit tests use cout, so we exempt them. if not _IsTestFilename(filename): error(filename, linenum, 'readability/streams', 3, 'Streams are highly discouraged.')
[ "def", "CheckIncludeLine", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "include_state", ",", "error", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename", ")", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"", "if", "_RE_PATTERN_INCLUDE_NEW_STYLE", ".", "search", "(", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include_dir'", ",", "4", ",", "'Include the directory when naming .h files'", ")", "# we shouldn't include a file more than once. actually, there are a", "# handful of instances where doing so is okay, but in general it's", "# not.", "match", "=", "_RE_PATTERN_INCLUDE", ".", "search", "(", "line", ")", "if", "match", ":", "include", "=", "match", ".", "group", "(", "2", ")", "is_system", "=", "(", "match", ".", "group", "(", "1", ")", "==", "'<'", ")", "if", "include", "in", "include_state", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include'", ",", "4", ",", "'\"%s\" already included at %s:%s'", "%", "(", "include", ",", "filename", ",", "include_state", "[", "include", "]", ")", ")", "else", ":", "include_state", "[", "include", "]", "=", "linenum", "# We want to ensure that headers appear in the right order:", "# 1) for foo.cc, foo.h (preferred location)", "# 2) c system files", "# 3) cpp system files", "# 4) for foo.cc, foo.h (deprecated location)", "# 5) other google headers", "#", "# We classify each include statement as one of those 5 types", "# using a number of techniques. The include_state object keeps", "# track of the highest type seen, and complains if we see a", "# lower type after that.", "error_message", "=", "include_state", ".", "CheckNextIncludeOrder", "(", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ")", "if", "error_message", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include_order'", ",", "4", ",", "'%s. Should be: %s.h, c system, c++ system, other.'", "%", "(", "error_message", ",", "fileinfo", ".", "BaseName", "(", ")", ")", ")", "canonical_include", "=", "include_state", ".", "CanonicalizeAlphabeticalOrder", "(", "include", ")", "if", "not", "include_state", ".", "IsInAlphabeticalOrder", "(", "clean_lines", ",", "linenum", ",", "canonical_include", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include_alpha'", ",", "4", ",", "'Include \"%s\" not in alphabetical order'", "%", "include", ")", "include_state", ".", "SetLastHeader", "(", "canonical_include", ")", "# Look for any of the stream classes that are part of standard C++.", "match", "=", "_RE_PATTERN_INCLUDE", ".", "match", "(", "line", ")", "if", "match", ":", "include", "=", "match", ".", "group", "(", "2", ")", "if", "Match", "(", "r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$'", ",", "include", ")", ":", "# Many unit tests use cout, so we exempt them.", "if", "not", "_IsTestFilename", "(", "filename", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/streams'", ",", "3", ",", "'Streams are highly discouraged.'", ")" ]
https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/scripts/cpp_lint.py#L3680-L3749
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
uCSIsCatLm
(code)
return ret
Check whether the character is part of Lm UCS Category
Check whether the character is part of Lm UCS Category
[ "Check", "whether", "the", "character", "is", "part", "of", "Lm", "UCS", "Category" ]
def uCSIsCatLm(code): """Check whether the character is part of Lm UCS Category """ ret = libxml2mod.xmlUCSIsCatLm(code) return ret
[ "def", "uCSIsCatLm", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCatLm", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2281-L2284
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/utils/_signatures.py
python
Signature.bind
(self, *args, **kwargs)
return self._bind(args, kwargs)
Get a :class:`BoundArguments` object, that maps the passed `args` and `kwargs` to the function's signature. Raises :exc:`TypeError` if the passed arguments can not be bound.
Get a :class:`BoundArguments` object, that maps the passed `args` and `kwargs` to the function's signature. Raises :exc:`TypeError` if the passed arguments can not be bound.
[ "Get", "a", ":", "class", ":", "BoundArguments", "object", "that", "maps", "the", "passed", "args", "and", "kwargs", "to", "the", "function", "s", "signature", ".", "Raises", ":", "exc", ":", "TypeError", "if", "the", "passed", "arguments", "can", "not", "be", "bound", "." ]
def bind(self, *args, **kwargs): '''Get a :class:`BoundArguments` object, that maps the passed `args` and `kwargs` to the function's signature. Raises :exc:`TypeError` if the passed arguments can not be bound. ''' return self._bind(args, kwargs)
[ "def", "bind", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_bind", "(", "args", ",", "kwargs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/_signatures.py#L775-L780
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/estimator/training.py
python
_TrainingExecutor.run_chief
(self)
return self._start_distributed_training()
Runs task chief.
Runs task chief.
[ "Runs", "task", "chief", "." ]
def run_chief(self): """Runs task chief.""" # TODO(xiejw): To allow execution framework to add train hooks. return self._start_distributed_training()
[ "def", "run_chief", "(", "self", ")", ":", "# TODO(xiejw): To allow execution framework to add train hooks.", "return", "self", ".", "_start_distributed_training", "(", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/estimator/training.py#L506-L509
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/toml/toml/encoder.py
python
dumps
(o, encoder=None)
return retval
Stringifies input dict as toml Args: o: Object to dump into toml encoder: The ``TomlEncoder`` to use for constructing the output string Returns: String containing the toml corresponding to dict Examples: ```python >>> import toml >>> output = { ... 'a': "I'm a string", ... 'b': ["I'm", "a", "list"], ... 'c': 2400 ... } >>> toml.dumps(output) 'a = "I\'m a string"\nb = [ "I\'m", "a", "list",]\nc = 2400\n' ```
Stringifies input dict as toml
[ "Stringifies", "input", "dict", "as", "toml" ]
def dumps(o, encoder=None): """Stringifies input dict as toml Args: o: Object to dump into toml encoder: The ``TomlEncoder`` to use for constructing the output string Returns: String containing the toml corresponding to dict Examples: ```python >>> import toml >>> output = { ... 'a': "I'm a string", ... 'b': ["I'm", "a", "list"], ... 'c': 2400 ... } >>> toml.dumps(output) 'a = "I\'m a string"\nb = [ "I\'m", "a", "list",]\nc = 2400\n' ``` """ retval = "" if encoder is None: encoder = TomlEncoder(o.__class__) addtoretval, sections = encoder.dump_sections(o, "") retval += addtoretval outer_objs = [id(o)] while sections: section_ids = [id(section) for section in sections.values()] for outer_obj in outer_objs: if outer_obj in section_ids: raise ValueError("Circular reference detected") outer_objs += section_ids newsections = encoder.get_empty_table() for section in sections: addtoretval, addtosections = encoder.dump_sections( sections[section], section) if addtoretval or (not addtoretval and not addtosections): if retval and retval[-2:] != "\n\n": retval += "\n" retval += "[" + section + "]\n" if addtoretval: retval += addtoretval for s in addtosections: newsections[section + "." + s] = addtosections[s] sections = newsections return retval
[ "def", "dumps", "(", "o", ",", "encoder", "=", "None", ")", ":", "retval", "=", "\"\"", "if", "encoder", "is", "None", ":", "encoder", "=", "TomlEncoder", "(", "o", ".", "__class__", ")", "addtoretval", ",", "sections", "=", "encoder", ".", "dump_sections", "(", "o", ",", "\"\"", ")", "retval", "+=", "addtoretval", "outer_objs", "=", "[", "id", "(", "o", ")", "]", "while", "sections", ":", "section_ids", "=", "[", "id", "(", "section", ")", "for", "section", "in", "sections", ".", "values", "(", ")", "]", "for", "outer_obj", "in", "outer_objs", ":", "if", "outer_obj", "in", "section_ids", ":", "raise", "ValueError", "(", "\"Circular reference detected\"", ")", "outer_objs", "+=", "section_ids", "newsections", "=", "encoder", ".", "get_empty_table", "(", ")", "for", "section", "in", "sections", ":", "addtoretval", ",", "addtosections", "=", "encoder", ".", "dump_sections", "(", "sections", "[", "section", "]", ",", "section", ")", "if", "addtoretval", "or", "(", "not", "addtoretval", "and", "not", "addtosections", ")", ":", "if", "retval", "and", "retval", "[", "-", "2", ":", "]", "!=", "\"\\n\\n\"", ":", "retval", "+=", "\"\\n\"", "retval", "+=", "\"[\"", "+", "section", "+", "\"]\\n\"", "if", "addtoretval", ":", "retval", "+=", "addtoretval", "for", "s", "in", "addtosections", ":", "newsections", "[", "section", "+", "\".\"", "+", "s", "]", "=", "addtosections", "[", "s", "]", "sections", "=", "newsections", "return", "retval" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/toml/toml/encoder.py#L34-L83
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ctypeslib.py
python
_concrete_ndptr.contents
(self)
return frombuffer(buffer, dtype=full_dtype).squeeze(axis=0)
Get an ndarray viewing the data pointed to by this pointer. This mirrors the `contents` attribute of a normal ctypes pointer
Get an ndarray viewing the data pointed to by this pointer.
[ "Get", "an", "ndarray", "viewing", "the", "data", "pointed", "to", "by", "this", "pointer", "." ]
def contents(self): """ Get an ndarray viewing the data pointed to by this pointer. This mirrors the `contents` attribute of a normal ctypes pointer """ full_dtype = _dtype((self._dtype_, self._shape_)) full_ctype = ctypes.c_char * full_dtype.itemsize buffer = ctypes.cast(self, ctypes.POINTER(full_ctype)).contents return frombuffer(buffer, dtype=full_dtype).squeeze(axis=0)
[ "def", "contents", "(", "self", ")", ":", "full_dtype", "=", "_dtype", "(", "(", "self", ".", "_dtype_", ",", "self", ".", "_shape_", ")", ")", "full_ctype", "=", "ctypes", ".", "c_char", "*", "full_dtype", ".", "itemsize", "buffer", "=", "ctypes", ".", "cast", "(", "self", ",", "ctypes", ".", "POINTER", "(", "full_ctype", ")", ")", ".", "contents", "return", "frombuffer", "(", "buffer", ",", "dtype", "=", "full_dtype", ")", ".", "squeeze", "(", "axis", "=", "0", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ctypeslib.py#L216-L225
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pgen2/grammar.py
python
Grammar.copy
(self)
return new
Copy the grammar.
Copy the grammar.
[ "Copy", "the", "grammar", "." ]
def copy(self): """ Copy the grammar. """ new = self.__class__() for dict_attr in ("symbol2number", "number2symbol", "dfas", "keywords", "tokens", "symbol2label"): setattr(new, dict_attr, getattr(self, dict_attr).copy()) new.labels = self.labels[:] new.states = self.states[:] new.start = self.start return new
[ "def", "copy", "(", "self", ")", ":", "new", "=", "self", ".", "__class__", "(", ")", "for", "dict_attr", "in", "(", "\"symbol2number\"", ",", "\"number2symbol\"", ",", "\"dfas\"", ",", "\"keywords\"", ",", "\"tokens\"", ",", "\"symbol2label\"", ")", ":", "setattr", "(", "new", ",", "dict_attr", ",", "getattr", "(", "self", ",", "dict_attr", ")", ".", "copy", "(", ")", ")", "new", ".", "labels", "=", "self", ".", "labels", "[", ":", "]", "new", ".", "states", "=", "self", ".", "states", "[", ":", "]", "new", ".", "start", "=", "self", ".", "start", "return", "new" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pgen2/grammar.py#L115-L126
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
App_CleanUp
(*args)
return _core_.App_CleanUp(*args)
App_CleanUp() For internal use only, it is used to cleanup after wxWidgets when Python shuts down.
App_CleanUp()
[ "App_CleanUp", "()" ]
def App_CleanUp(*args): """ App_CleanUp() For internal use only, it is used to cleanup after wxWidgets when Python shuts down. """ return _core_.App_CleanUp(*args)
[ "def", "App_CleanUp", "(", "*", "args", ")", ":", "return", "_core_", ".", "App_CleanUp", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L8412-L8419
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/polynomial.py
python
polymulx
(c)
return prd
Multiply a polynomial by x. Multiply the polynomial `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of polynomial coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. See Also -------- polyadd, polysub, polymul, polydiv, polypow Notes ----- .. versionadded:: 1.5.0
Multiply a polynomial by x.
[ "Multiply", "a", "polynomial", "by", "x", "." ]
def polymulx(c): """Multiply a polynomial by x. Multiply the polynomial `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of polynomial coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. See Also -------- polyadd, polysub, polymul, polydiv, polypow Notes ----- .. versionadded:: 1.5.0 """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0]*0 prd[1:] = c return prd
[ "def", "polymulx", "(", "c", ")", ":", "# c is a trimmed copy", "[", "c", "]", "=", "pu", ".", "as_series", "(", "[", "c", "]", ")", "# The zero series needs special treatment", "if", "len", "(", "c", ")", "==", "1", "and", "c", "[", "0", "]", "==", "0", ":", "return", "c", "prd", "=", "np", ".", "empty", "(", "len", "(", "c", ")", "+", "1", ",", "dtype", "=", "c", ".", "dtype", ")", "prd", "[", "0", "]", "=", "c", "[", "0", "]", "*", "0", "prd", "[", "1", ":", "]", "=", "c", "return", "prd" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/polynomial.py#L267-L304
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
samples/python/efficientnet/build_engine.py
python
EngineCalibrator.set_image_batcher
(self, image_batcher: ImageBatcher)
Define the image batcher to use, if any. If using only the cache file, an image batcher doesn't need to be defined. :param image_batcher: The ImageBatcher object
Define the image batcher to use, if any. If using only the cache file, an image batcher doesn't need to be defined. :param image_batcher: The ImageBatcher object
[ "Define", "the", "image", "batcher", "to", "use", "if", "any", ".", "If", "using", "only", "the", "cache", "file", "an", "image", "batcher", "doesn", "t", "need", "to", "be", "defined", ".", ":", "param", "image_batcher", ":", "The", "ImageBatcher", "object" ]
def set_image_batcher(self, image_batcher: ImageBatcher): """ Define the image batcher to use, if any. If using only the cache file, an image batcher doesn't need to be defined. :param image_batcher: The ImageBatcher object """ self.image_batcher = image_batcher size = int(np.dtype(self.image_batcher.dtype).itemsize * np.prod(self.image_batcher.shape)) self.batch_allocation = cuda.mem_alloc(size) self.batch_generator = self.image_batcher.get_batch()
[ "def", "set_image_batcher", "(", "self", ",", "image_batcher", ":", "ImageBatcher", ")", ":", "self", ".", "image_batcher", "=", "image_batcher", "size", "=", "int", "(", "np", ".", "dtype", "(", "self", ".", "image_batcher", ".", "dtype", ")", ".", "itemsize", "*", "np", ".", "prod", "(", "self", ".", "image_batcher", ".", "shape", ")", ")", "self", ".", "batch_allocation", "=", "cuda", ".", "mem_alloc", "(", "size", ")", "self", ".", "batch_generator", "=", "self", ".", "image_batcher", ".", "get_batch", "(", ")" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/efficientnet/build_engine.py#L49-L58
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/basic_session_run_hooks.py
python
NanTensorHook.__init__
(self, loss_tensor, fail_on_nan_loss=True)
Initializes NanLoss monitor. Args: loss_tensor: `Tensor`, the loss tensor. fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN.
Initializes NanLoss monitor.
[ "Initializes", "NanLoss", "monitor", "." ]
def __init__(self, loss_tensor, fail_on_nan_loss=True): """Initializes NanLoss monitor. Args: loss_tensor: `Tensor`, the loss tensor. fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN. """ self._loss_tensor = loss_tensor self._fail_on_nan_loss = fail_on_nan_loss
[ "def", "__init__", "(", "self", ",", "loss_tensor", ",", "fail_on_nan_loss", "=", "True", ")", ":", "self", ".", "_loss_tensor", "=", "loss_tensor", "self", ".", "_fail_on_nan_loss", "=", "fail_on_nan_loss" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/basic_session_run_hooks.py#L293-L301
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py
python
_NNTPBase.xhdr
(self, hdr, str, *, file=None)
return resp, [remove_number(line) for line in lines]
Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of (nr, value) strings
Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of (nr, value) strings
[ "Process", "an", "XHDR", "command", "(", "optional", "server", "extension", ")", ".", "Arguments", ":", "-", "hdr", ":", "the", "header", "type", "(", "e", ".", "g", ".", "subject", ")", "-", "str", ":", "an", "article", "nr", "a", "message", "id", "or", "a", "range", "nr1", "-", "nr2", "-", "file", ":", "Filename", "string", "or", "file", "object", "to", "store", "the", "result", "in", "Returns", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "list", ":", "list", "of", "(", "nr", "value", ")", "strings" ]
def xhdr(self, hdr, str, *, file=None): """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of (nr, value) strings """ pat = re.compile('^([0-9]+) ?(.*)\n?') resp, lines = self._longcmdstring('XHDR {0} {1}'.format(hdr, str), file) def remove_number(line): m = pat.match(line) return m.group(1, 2) if m else line return resp, [remove_number(line) for line in lines]
[ "def", "xhdr", "(", "self", ",", "hdr", ",", "str", ",", "*", ",", "file", "=", "None", ")", ":", "pat", "=", "re", ".", "compile", "(", "'^([0-9]+) ?(.*)\\n?'", ")", "resp", ",", "lines", "=", "self", ".", "_longcmdstring", "(", "'XHDR {0} {1}'", ".", "format", "(", "hdr", ",", "str", ")", ",", "file", ")", "def", "remove_number", "(", "line", ")", ":", "m", "=", "pat", ".", "match", "(", "line", ")", "return", "m", ".", "group", "(", "1", ",", "2", ")", "if", "m", "else", "line", "return", "resp", ",", "[", "remove_number", "(", "line", ")", "for", "line", "in", "lines", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py#L778-L792
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py
python
_signature_strip_non_python_syntax
(signature)
return clean_signature, self_parameter, last_positional_only
Private helper function. Takes a signature in Argument Clinic's extended signature format. Returns a tuple of three things: * that signature re-rendered in standard Python syntax, * the index of the "self" parameter (generally 0), or None if the function does not have a "self" parameter, and * the index of the last "positional only" parameter, or None if the signature has no positional-only parameters.
Private helper function. Takes a signature in Argument Clinic's extended signature format.
[ "Private", "helper", "function", ".", "Takes", "a", "signature", "in", "Argument", "Clinic", "s", "extended", "signature", "format", "." ]
def _signature_strip_non_python_syntax(signature): """ Private helper function. Takes a signature in Argument Clinic's extended signature format. Returns a tuple of three things: * that signature re-rendered in standard Python syntax, * the index of the "self" parameter (generally 0), or None if the function does not have a "self" parameter, and * the index of the last "positional only" parameter, or None if the signature has no positional-only parameters. """ if not signature: return signature, None, None self_parameter = None last_positional_only = None lines = [l.encode('ascii') for l in signature.split('\n')] generator = iter(lines).__next__ token_stream = tokenize.tokenize(generator) delayed_comma = False skip_next_comma = False text = [] add = text.append current_parameter = 0 OP = token.OP ERRORTOKEN = token.ERRORTOKEN # token stream always starts with ENCODING token, skip it t = next(token_stream) assert t.type == tokenize.ENCODING for t in token_stream: type, string = t.type, t.string if type == OP: if string == ',': if skip_next_comma: skip_next_comma = False else: assert not delayed_comma delayed_comma = True current_parameter += 1 continue if string == '/': assert not skip_next_comma assert last_positional_only is None skip_next_comma = True last_positional_only = current_parameter - 1 continue if (type == ERRORTOKEN) and (string == '$'): assert self_parameter is None self_parameter = current_parameter continue if delayed_comma: delayed_comma = False if not ((type == OP) and (string == ')')): add(', ') add(string) if (string == ','): add(' ') clean_signature = ''.join(text) return clean_signature, self_parameter, last_positional_only
[ "def", "_signature_strip_non_python_syntax", "(", "signature", ")", ":", "if", "not", "signature", ":", "return", "signature", ",", "None", ",", "None", "self_parameter", "=", "None", "last_positional_only", "=", "None", "lines", "=", "[", "l", ".", "encode", "(", "'ascii'", ")", "for", "l", "in", "signature", ".", "split", "(", "'\\n'", ")", "]", "generator", "=", "iter", "(", "lines", ")", ".", "__next__", "token_stream", "=", "tokenize", ".", "tokenize", "(", "generator", ")", "delayed_comma", "=", "False", "skip_next_comma", "=", "False", "text", "=", "[", "]", "add", "=", "text", ".", "append", "current_parameter", "=", "0", "OP", "=", "token", ".", "OP", "ERRORTOKEN", "=", "token", ".", "ERRORTOKEN", "# token stream always starts with ENCODING token, skip it", "t", "=", "next", "(", "token_stream", ")", "assert", "t", ".", "type", "==", "tokenize", ".", "ENCODING", "for", "t", "in", "token_stream", ":", "type", ",", "string", "=", "t", ".", "type", ",", "t", ".", "string", "if", "type", "==", "OP", ":", "if", "string", "==", "','", ":", "if", "skip_next_comma", ":", "skip_next_comma", "=", "False", "else", ":", "assert", "not", "delayed_comma", "delayed_comma", "=", "True", "current_parameter", "+=", "1", "continue", "if", "string", "==", "'/'", ":", "assert", "not", "skip_next_comma", "assert", "last_positional_only", "is", "None", "skip_next_comma", "=", "True", "last_positional_only", "=", "current_parameter", "-", "1", "continue", "if", "(", "type", "==", "ERRORTOKEN", ")", "and", "(", "string", "==", "'$'", ")", ":", "assert", "self_parameter", "is", "None", "self_parameter", "=", "current_parameter", "continue", "if", "delayed_comma", ":", "delayed_comma", "=", "False", "if", "not", "(", "(", "type", "==", "OP", ")", "and", "(", "string", "==", "')'", ")", ")", ":", "add", "(", "', '", ")", "add", "(", "string", ")", "if", "(", "string", "==", "','", ")", ":", "add", "(", "' '", ")", "clean_signature", "=", "''", ".", "join", "(", "text", ")", "return", "clean_signature", ",", "self_parameter", ",", "last_positional_only" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L1885-L1954
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/xlsgrid.py
python
XLSRichText.__init__
(self, book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10)
Default class constructor. :param `book`: an instance of the `xlrd.Book` class; :param `cell`: an instance of `xlrd.sheet.Cell` class; :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`); :param `display_text`: if Mark Hammonds' `pywin32` package is available, this is the WYSIWYG cell content; :param `hyperlink`: if this cell contains a hyperlink, it will be displayed accordingly; :param `rich_text`: if this cell contains text in rich text format, :class:`XLSGrid` will do its best to render the text as rich text; :param `default_width`: this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file). :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink* parameter will always be ``None`` as this feature is available only in `xlrd` 0.7.2 (SVN). :note: If you are using version 0.7.1 or lower for `xlrd`, this class will note be used by :class:`XLSGrid`. .. warning:: This class currently supports only single-line non-rotated text, and it discards properties like `shrink-to-fit` and `wrapping`.
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10): """ Default class constructor. :param `book`: an instance of the `xlrd.Book` class; :param `cell`: an instance of `xlrd.sheet.Cell` class; :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`); :param `display_text`: if Mark Hammonds' `pywin32` package is available, this is the WYSIWYG cell content; :param `hyperlink`: if this cell contains a hyperlink, it will be displayed accordingly; :param `rich_text`: if this cell contains text in rich text format, :class:`XLSGrid` will do its best to render the text as rich text; :param `default_width`: this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file). :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink* parameter will always be ``None`` as this feature is available only in `xlrd` 0.7.2 (SVN). :note: If you are using version 0.7.1 or lower for `xlrd`, this class will note be used by :class:`XLSGrid`. .. warning:: This class currently supports only single-line non-rotated text, and it discards properties like `shrink-to-fit` and `wrapping`. """ XLSText.__init__(self, book, cell, xf_index, display_text, hyperlink, default_width) self.BuildChunks(book, xf_index, rich_text)
[ "def", "__init__", "(", "self", ",", "book", ",", "cell", ",", "xf_index", ",", "display_text", "=", "None", ",", "hyperlink", "=", "None", ",", "rich_text", "=", "None", ",", "default_width", "=", "10", ")", ":", "XLSText", ".", "__init__", "(", "self", ",", "book", ",", "cell", ",", "xf_index", ",", "display_text", ",", "hyperlink", ",", "default_width", ")", "self", ".", "BuildChunks", "(", "book", ",", "xf_index", ",", "rich_text", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/xlsgrid.py#L980-L1014
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.push_parameter_definitions
(self, frame)
Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters.
Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters.
[ "Pushes", "all", "parameter", "targets", "from", "the", "given", "frame", "into", "a", "local", "stack", "that", "permits", "tracking", "of", "yet", "to", "be", "assigned", "parameters", ".", "In", "particular", "this", "enables", "the", "optimization", "from", "visit_Name", "to", "skip", "undefined", "expressions", "for", "parameters", "in", "macros", "as", "macros", "can", "reference", "otherwise", "unbound", "parameters", "." ]
def push_parameter_definitions(self, frame): """Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters. """ self._param_def_block.append(frame.symbols.dump_param_targets())
[ "def", "push_parameter_definitions", "(", "self", ",", "frame", ")", ":", "self", ".", "_param_def_block", ".", "append", "(", "frame", ".", "symbols", ".", "dump_param_targets", "(", ")", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py#L614-L621
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.SetEdgeMode
(*args, **kwargs)
return _stc.StyledTextCtrl_SetEdgeMode(*args, **kwargs)
SetEdgeMode(self, int mode) The edge may be displayed by a line (EDGE_LINE) or by highlighting text that goes beyond it (EDGE_BACKGROUND) or not displayed at all (EDGE_NONE).
SetEdgeMode(self, int mode)
[ "SetEdgeMode", "(", "self", "int", "mode", ")" ]
def SetEdgeMode(*args, **kwargs): """ SetEdgeMode(self, int mode) The edge may be displayed by a line (EDGE_LINE) or by highlighting text that goes beyond it (EDGE_BACKGROUND) or not displayed at all (EDGE_NONE). """ return _stc.StyledTextCtrl_SetEdgeMode(*args, **kwargs)
[ "def", "SetEdgeMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetEdgeMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4896-L4903
artyom-beilis/cppcms
463a9a68e0bc15e2d01e8b8d72cc4fcc7f2b3264
contrib/integration/session/python/cppcms.py
python
Session.session_cookie_name
(self)
return r
Get the name of the cookie that is used to store CppCMS session Note: the value of this cookie should be passed to load method when session is loaded
Get the name of the cookie that is used to store CppCMS session Note: the value of this cookie should be passed to load method when session is loaded
[ "Get", "the", "name", "of", "the", "cookie", "that", "is", "used", "to", "store", "CppCMS", "session", "Note", ":", "the", "value", "of", "this", "cookie", "should", "be", "passed", "to", "load", "method", "when", "session", "is", "loaded" ]
def session_cookie_name(self): """ Get the name of the cookie that is used to store CppCMS session Note: the value of this cookie should be passed to load method when session is loaded """ r=Loader.capi.cppcms_capi_session_get_session_cookie_name(self.d) self.check() return r
[ "def", "session_cookie_name", "(", "self", ")", ":", "r", "=", "Loader", ".", "capi", ".", "cppcms_capi_session_get_session_cookie_name", "(", "self", ".", "d", ")", "self", ".", "check", "(", ")", "return", "r" ]
https://github.com/artyom-beilis/cppcms/blob/463a9a68e0bc15e2d01e8b8d72cc4fcc7f2b3264/contrib/integration/session/python/cppcms.py#L375-L383
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/examples/skflow/text_classification_cnn.py
python
cnn_model
(x, y)
return {'class': tf.argmax(prediction, 1), 'prob': prediction}, loss, train_op
2 layer Convolutional network to predict from sequence of words to a class.
2 layer Convolutional network to predict from sequence of words to a class.
[ "2", "layer", "Convolutional", "network", "to", "predict", "from", "sequence", "of", "words", "to", "a", "class", "." ]
def cnn_model(x, y): """2 layer Convolutional network to predict from sequence of words to a class.""" # Convert indexes of words into embeddings. # This creates embeddings matrix of [n_words, EMBEDDING_SIZE] and then # maps word indexes of the sequence into [batch_size, sequence_length, # EMBEDDING_SIZE]. y = tf.one_hot(y, 15, 1, 0) word_vectors = learn.ops.categorical_variable(x, n_classes=n_words, embedding_size=EMBEDDING_SIZE, name='words') word_vectors = tf.expand_dims(word_vectors, 3) with tf.variable_scope('CNN_Layer1'): # Apply Convolution filtering on input sequence. conv1 = tf.contrib.layers.convolution2d(word_vectors, N_FILTERS, FILTER_SHAPE1, padding='VALID') # Add a RELU for non linearity. conv1 = tf.nn.relu(conv1) # Max pooling across output of Convolution+Relu. pool1 = tf.nn.max_pool(conv1, ksize=[1, POOLING_WINDOW, 1, 1], strides=[1, POOLING_STRIDE, 1, 1], padding='SAME') # Transpose matrix so that n_filters from convolution becomes width. pool1 = tf.transpose(pool1, [0, 1, 3, 2]) with tf.variable_scope('CNN_Layer2'): # Second level of convolution filtering. conv2 = tf.contrib.layers.convolution2d(pool1, N_FILTERS, FILTER_SHAPE2, padding='VALID') # Max across each filter to get useful features for classification. pool2 = tf.squeeze(tf.reduce_max(conv2, 1), squeeze_dims=[1]) # Apply regular WX + B and classification. prediction, loss = learn.models.logistic_regression(pool2, y) train_op = tf.contrib.layers.optimize_loss( loss, tf.contrib.framework.get_global_step(), optimizer='Adam', learning_rate=0.01) return {'class': tf.argmax(prediction, 1), 'prob': prediction}, loss, train_op
[ "def", "cnn_model", "(", "x", ",", "y", ")", ":", "# Convert indexes of words into embeddings.", "# This creates embeddings matrix of [n_words, EMBEDDING_SIZE] and then", "# maps word indexes of the sequence into [batch_size, sequence_length,", "# EMBEDDING_SIZE].", "y", "=", "tf", ".", "one_hot", "(", "y", ",", "15", ",", "1", ",", "0", ")", "word_vectors", "=", "learn", ".", "ops", ".", "categorical_variable", "(", "x", ",", "n_classes", "=", "n_words", ",", "embedding_size", "=", "EMBEDDING_SIZE", ",", "name", "=", "'words'", ")", "word_vectors", "=", "tf", ".", "expand_dims", "(", "word_vectors", ",", "3", ")", "with", "tf", ".", "variable_scope", "(", "'CNN_Layer1'", ")", ":", "# Apply Convolution filtering on input sequence.", "conv1", "=", "tf", ".", "contrib", ".", "layers", ".", "convolution2d", "(", "word_vectors", ",", "N_FILTERS", ",", "FILTER_SHAPE1", ",", "padding", "=", "'VALID'", ")", "# Add a RELU for non linearity.", "conv1", "=", "tf", ".", "nn", ".", "relu", "(", "conv1", ")", "# Max pooling across output of Convolution+Relu.", "pool1", "=", "tf", ".", "nn", ".", "max_pool", "(", "conv1", ",", "ksize", "=", "[", "1", ",", "POOLING_WINDOW", ",", "1", ",", "1", "]", ",", "strides", "=", "[", "1", ",", "POOLING_STRIDE", ",", "1", ",", "1", "]", ",", "padding", "=", "'SAME'", ")", "# Transpose matrix so that n_filters from convolution becomes width.", "pool1", "=", "tf", ".", "transpose", "(", "pool1", ",", "[", "0", ",", "1", ",", "3", ",", "2", "]", ")", "with", "tf", ".", "variable_scope", "(", "'CNN_Layer2'", ")", ":", "# Second level of convolution filtering.", "conv2", "=", "tf", ".", "contrib", ".", "layers", ".", "convolution2d", "(", "pool1", ",", "N_FILTERS", ",", "FILTER_SHAPE2", ",", "padding", "=", "'VALID'", ")", "# Max across each filter to get useful features for classification.", "pool2", "=", "tf", ".", "squeeze", "(", "tf", ".", "reduce_max", "(", "conv2", ",", "1", ")", ",", "squeeze_dims", "=", "[", "1", "]", ")", "# Apply regular WX + B and classification.", "prediction", ",", "loss", "=", "learn", ".", "models", ".", "logistic_regression", "(", "pool2", ",", "y", ")", "train_op", "=", "tf", ".", "contrib", ".", "layers", ".", "optimize_loss", "(", "loss", ",", "tf", ".", "contrib", ".", "framework", ".", "get_global_step", "(", ")", ",", "optimizer", "=", "'Adam'", ",", "learning_rate", "=", "0.01", ")", "return", "{", "'class'", ":", "tf", ".", "argmax", "(", "prediction", ",", "1", ")", ",", "'prob'", ":", "prediction", "}", ",", "loss", ",", "train_op" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/examples/skflow/text_classification_cnn.py#L42-L78
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.GetPasteConvertEndings
(*args, **kwargs)
return _stc.StyledTextCtrl_GetPasteConvertEndings(*args, **kwargs)
GetPasteConvertEndings(self) -> bool Get convert-on-paste setting
GetPasteConvertEndings(self) -> bool
[ "GetPasteConvertEndings", "(", "self", ")", "-", ">", "bool" ]
def GetPasteConvertEndings(*args, **kwargs): """ GetPasteConvertEndings(self) -> bool Get convert-on-paste setting """ return _stc.StyledTextCtrl_GetPasteConvertEndings(*args, **kwargs)
[ "def", "GetPasteConvertEndings", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetPasteConvertEndings", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5599-L5605
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/core/base.py
python
ModTool._validate
(self)
Validates the arguments
Validates the arguments
[ "Validates", "the", "arguments" ]
def _validate(self): """ Validates the arguments """ if not isinstance(self.skip_subdirs['lib'], bool): raise ModToolException('Expected a boolean value for skip_lib') if not isinstance(self.skip_subdirs['pybind'], bool): raise ModToolException('Expected a boolean value for skip_pybind') if not isinstance(self.skip_subdirs['python'], bool): raise ModToolException('Expected a boolean value for skip_python') if not isinstance(self.skip_subdirs['grc'], bool): raise ModToolException('Expected a boolean value for skip_grc') self._assign()
[ "def", "_validate", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "skip_subdirs", "[", "'lib'", "]", ",", "bool", ")", ":", "raise", "ModToolException", "(", "'Expected a boolean value for skip_lib'", ")", "if", "not", "isinstance", "(", "self", ".", "skip_subdirs", "[", "'pybind'", "]", ",", "bool", ")", ":", "raise", "ModToolException", "(", "'Expected a boolean value for skip_pybind'", ")", "if", "not", "isinstance", "(", "self", ".", "skip_subdirs", "[", "'python'", "]", ",", "bool", ")", ":", "raise", "ModToolException", "(", "'Expected a boolean value for skip_python'", ")", "if", "not", "isinstance", "(", "self", ".", "skip_subdirs", "[", "'grc'", "]", ",", "bool", ")", ":", "raise", "ModToolException", "(", "'Expected a boolean value for skip_grc'", ")", "self", ".", "_assign", "(", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/core/base.py#L91-L101
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/inspector_protocol/jinja2/lexer.py
python
Token.test
(self, expr)
return False
Test a token against a token expression. This can either be a token type or ``'token_type:token_value'``. This can only test against string values and types.
Test a token against a token expression. This can either be a token type or ``'token_type:token_value'``. This can only test against string values and types.
[ "Test", "a", "token", "against", "a", "token", "expression", ".", "This", "can", "either", "be", "a", "token", "type", "or", "token_type", ":", "token_value", ".", "This", "can", "only", "test", "against", "string", "values", "and", "types", "." ]
def test(self, expr): """Test a token against a token expression. This can either be a token type or ``'token_type:token_value'``. This can only test against string values and types. """ # here we do a regular string equality check as test_any is usually # passed an iterable of not interned strings. if self.type == expr: return True elif ':' in expr: return expr.split(':', 1) == [self.type, self.value] return False
[ "def", "test", "(", "self", ",", "expr", ")", ":", "# here we do a regular string equality check as test_any is usually", "# passed an iterable of not interned strings.", "if", "self", ".", "type", "==", "expr", ":", "return", "True", "elif", "':'", "in", "expr", ":", "return", "expr", ".", "split", "(", "':'", ",", "1", ")", "==", "[", "self", ".", "type", ",", "self", ".", "value", "]", "return", "False" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/lexer.py#L247-L258
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py
python
Type.translation_unit
(self)
return self._tu
The TranslationUnit to which this Type is associated.
The TranslationUnit to which this Type is associated.
[ "The", "TranslationUnit", "to", "which", "this", "Type", "is", "associated", "." ]
def translation_unit(self): """The TranslationUnit to which this Type is associated.""" # If this triggers an AttributeError, the instance was not properly # instantiated. return self._tu
[ "def", "translation_unit", "(", "self", ")", ":", "# If this triggers an AttributeError, the instance was not properly", "# instantiated.", "return", "self", ".", "_tu" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L2005-L2009
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/appController.py
python
AppController._updateForStageChanges
(self, hasPrimResync=True)
Assuming there have been authoring changes to the already-loaded stage, make the minimal updates to the UI required to maintain a consistent state. This may still be over-zealous until we know what actually changed, but we should be able to preserve camera and playback positions (unless viewing through a stage camera that no longer exists
Assuming there have been authoring changes to the already-loaded stage, make the minimal updates to the UI required to maintain a consistent state. This may still be over-zealous until we know what actually changed, but we should be able to preserve camera and playback positions (unless viewing through a stage camera that no longer exists
[ "Assuming", "there", "have", "been", "authoring", "changes", "to", "the", "already", "-", "loaded", "stage", "make", "the", "minimal", "updates", "to", "the", "UI", "required", "to", "maintain", "a", "consistent", "state", ".", "This", "may", "still", "be", "over", "-", "zealous", "until", "we", "know", "what", "actually", "changed", "but", "we", "should", "be", "able", "to", "preserve", "camera", "and", "playback", "positions", "(", "unless", "viewing", "through", "a", "stage", "camera", "that", "no", "longer", "exists" ]
def _updateForStageChanges(self, hasPrimResync=True): """Assuming there have been authoring changes to the already-loaded stage, make the minimal updates to the UI required to maintain a consistent state. This may still be over-zealous until we know what actually changed, but we should be able to preserve camera and playback positions (unless viewing through a stage camera that no longer exists""" self._hasPrimResync = hasPrimResync or self._hasPrimResync self._clearCaches(preserveCamera=True) # Update the UIs (it gets all of them) and StageView on a timer self.updateGUI()
[ "def", "_updateForStageChanges", "(", "self", ",", "hasPrimResync", "=", "True", ")", ":", "self", ".", "_hasPrimResync", "=", "hasPrimResync", "or", "self", ".", "_hasPrimResync", "self", ".", "_clearCaches", "(", "preserveCamera", "=", "True", ")", "# Update the UIs (it gets all of them) and StageView on a timer", "self", ".", "updateGUI", "(", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L2277-L2290
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/partisn.py
python
_get_xs_names
(mat_xs_names)
return list(xs_names)
Create list of names (strings) of the nuclides that appear in the cross section library from the list of nuc_names.
Create list of names (strings) of the nuclides that appear in the cross section library from the list of nuc_names.
[ "Create", "list", "of", "names", "(", "strings", ")", "of", "the", "nuclides", "that", "appear", "in", "the", "cross", "section", "library", "from", "the", "list", "of", "nuc_names", "." ]
def _get_xs_names(mat_xs_names): """Create list of names (strings) of the nuclides that appear in the cross section library from the list of nuc_names. """ xs_names = set() list(map(xs_names.update, mat_xs_names.values())) return list(xs_names)
[ "def", "_get_xs_names", "(", "mat_xs_names", ")", ":", "xs_names", "=", "set", "(", ")", "list", "(", "map", "(", "xs_names", ".", "update", ",", "mat_xs_names", ".", "values", "(", ")", ")", ")", "return", "list", "(", "xs_names", ")" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/partisn.py#L283-L290
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py
python
Context.clear_flags
(self)
Reset all flags to zero
Reset all flags to zero
[ "Reset", "all", "flags", "to", "zero" ]
def clear_flags(self): """Reset all flags to zero""" for flag in self.flags: self.flags[flag] = 0
[ "def", "clear_flags", "(", "self", ")", ":", "for", "flag", "in", "self", ".", "flags", ":", "self", ".", "flags", "[", "flag", "]", "=", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L3998-L4001
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/connection.py
python
Route53Connection._make_qualified
(self, value)
Ensure passed domain names end in a period (.) character. This will usually make a domain fully qualified.
Ensure passed domain names end in a period (.) character. This will usually make a domain fully qualified.
[ "Ensure", "passed", "domain", "names", "end", "in", "a", "period", "(", ".", ")", "character", ".", "This", "will", "usually", "make", "a", "domain", "fully", "qualified", "." ]
def _make_qualified(self, value): """ Ensure passed domain names end in a period (.) character. This will usually make a domain fully qualified. """ if type(value) in [list, tuple, set]: new_list = [] for record in value: if record and not record[-1] == '.': new_list.append("%s." % record) else: new_list.append(record) return new_list else: value = value.strip() if value and not value[-1] == '.': value = "%s." % value return value
[ "def", "_make_qualified", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "in", "[", "list", ",", "tuple", ",", "set", "]", ":", "new_list", "=", "[", "]", "for", "record", "in", "value", ":", "if", "record", "and", "not", "record", "[", "-", "1", "]", "==", "'.'", ":", "new_list", ".", "append", "(", "\"%s.\"", "%", "record", ")", "else", ":", "new_list", ".", "append", "(", "record", ")", "return", "new_list", "else", ":", "value", "=", "value", ".", "strip", "(", ")", "if", "value", "and", "not", "value", "[", "-", "1", "]", "==", "'.'", ":", "value", "=", "\"%s.\"", "%", "value", "return", "value" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/connection.py#L563-L580
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py
python
UBMatrixPeakTable.__init__
(self, parent)
return
Initialization :param parent: :return:
Initialization :param parent: :return:
[ "Initialization", ":", "param", "parent", ":", ":", "return", ":" ]
def __init__(self, parent): """ Initialization :param parent: :return: """ tableBase.NTableWidget.__init__(self, parent) # define class variables self._cachedSpiceHKL = dict() # class variables for column indexes self._colIndexScan = None self._colIndexSpiceHKL = None self._colIndexCalculatedHKL = None self._colIndexQSample = None self._colIndexWavelength = None self._colIndexError = None return
[ "def", "__init__", "(", "self", ",", "parent", ")", ":", "tableBase", ".", "NTableWidget", ".", "__init__", "(", "self", ",", "parent", ")", "# define class variables", "self", ".", "_cachedSpiceHKL", "=", "dict", "(", ")", "# class variables for column indexes", "self", ".", "_colIndexScan", "=", "None", "self", ".", "_colIndexSpiceHKL", "=", "None", "self", ".", "_colIndexCalculatedHKL", "=", "None", "self", ".", "_colIndexQSample", "=", "None", "self", ".", "_colIndexWavelength", "=", "None", "self", ".", "_colIndexError", "=", "None", "return" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L1683-L1702
xenia-project/xenia
9b1fdac98665ac091b9660a5d0fbb259ed79e578
third_party/google-styleguide/cpplint/cpplint.py
python
CheckMakePairUsesDeduction
(filename, clean_lines, linenum, error)
Check that make_pair's template arguments are deduced. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check that make_pair's template arguments are deduced.
[ "Check", "that", "make_pair", "s", "template", "arguments", "are", "deduced", "." ]
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly')
[ "def", "CheckMakePairUsesDeduction", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "_RE_PATTERN_EXPLICIT_MAKEPAIR", ".", "search", "(", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'build/explicit_make_pair'", ",", "4", ",", "# 4 = high confidence", "'For C++11-compatibility, omit template arguments from make_pair'", "' OR use pair directly OR if appropriate, construct a pair directly'", ")" ]
https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L5245-L5263
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/elastic/rendezvous/etcd_server.py
python
EtcdServer.get_client
(self)
return etcd.Client( host=self._host, port=self._port, version_prefix="/v2", read_timeout=10 )
Returns: An etcd client object that can be used to make requests to this server.
Returns: An etcd client object that can be used to make requests to this server.
[ "Returns", ":", "An", "etcd", "client", "object", "that", "can", "be", "used", "to", "make", "requests", "to", "this", "server", "." ]
def get_client(self): """ Returns: An etcd client object that can be used to make requests to this server. """ return etcd.Client( host=self._host, port=self._port, version_prefix="/v2", read_timeout=10 )
[ "def", "get_client", "(", "self", ")", ":", "return", "etcd", ".", "Client", "(", "host", "=", "self", ".", "_host", ",", "port", "=", "self", ".", "_port", ",", "version_prefix", "=", "\"/v2\"", ",", "read_timeout", "=", "10", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/rendezvous/etcd_server.py#L228-L236
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/util/observer.py
python
Observable.get_observer_count
(self)
return len(self.observers)
Return the number of registered observers.
Return the number of registered observers.
[ "Return", "the", "number", "of", "registered", "observers", "." ]
def get_observer_count(self): """ Return the number of registered observers. """ return len(self.observers)
[ "def", "get_observer_count", "(", "self", ")", ":", "return", "len", "(", "self", ".", "observers", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/observer.py#L82-L86
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarIter.__init__
(self, tarfile)
Construct a TarIter object.
Construct a TarIter object.
[ "Construct", "a", "TarIter", "object", "." ]
def __init__(self, tarfile): """Construct a TarIter object. """ self.tarfile = tarfile self.index = 0
[ "def", "__init__", "(", "self", ",", "tarfile", ")", ":", "self", ".", "tarfile", "=", "tarfile", "self", ".", "index", "=", "0" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2560-L2564
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py
python
XCBuildPhase._AddPathToDict
(self, pbxbuildfile, path)
Adds path to the dict tracking paths belonging to this build phase. If the path is already a member of this build phase, raises an exception.
Adds path to the dict tracking paths belonging to this build phase.
[ "Adds", "path", "to", "the", "dict", "tracking", "paths", "belonging", "to", "this", "build", "phase", "." ]
def _AddPathToDict(self, pbxbuildfile, path): """Adds path to the dict tracking paths belonging to this build phase. If the path is already a member of this build phase, raises an exception. """ if path in self._files_by_path: raise ValueError('Found multiple build files with path ' + path) self._files_by_path[path] = pbxbuildfile
[ "def", "_AddPathToDict", "(", "self", ",", "pbxbuildfile", ",", "path", ")", ":", "if", "path", "in", "self", ".", "_files_by_path", ":", "raise", "ValueError", "(", "'Found multiple build files with path '", "+", "path", ")", "self", ".", "_files_by_path", "[", "path", "]", "=", "pbxbuildfile" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py#L1778-L1786
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/style/cpplint.py
python
_Quiet
()
return _cpplint_state.quiet
Return's the module's quiet setting.
Return's the module's quiet setting.
[ "Return", "s", "the", "module", "s", "quiet", "setting", "." ]
def _Quiet(): """Return's the module's quiet setting.""" return _cpplint_state.quiet
[ "def", "_Quiet", "(", ")", ":", "return", "_cpplint_state", ".", "quiet" ]
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L1180-L1182
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/blocks/block.py
python
Block.type_controller_modify
(self, direction)
return changed
Change the type controller. Args: direction: +1 or -1 Returns: true for change
Change the type controller.
[ "Change", "the", "type", "controller", "." ]
def type_controller_modify(self, direction): """ Change the type controller. Args: direction: +1 or -1 Returns: true for change """ changed = False type_param = None for param in filter(lambda p: p.is_enum(), self.get_params()): children = self.get_ports() + self.get_params() # Priority to the type controller if param.get_key() in ' '.join(map(lambda p: p._type, children)): type_param = param # Use param if type param is unset if not type_param: type_param = param if type_param: # Try to increment the enum by direction try: keys = type_param.get_option_keys() old_index = keys.index(type_param.get_value()) new_index = (old_index + direction + len(keys)) % len(keys) type_param.set_value(keys[new_index]) changed = True except: pass return changed
[ "def", "type_controller_modify", "(", "self", ",", "direction", ")", ":", "changed", "=", "False", "type_param", "=", "None", "for", "param", "in", "filter", "(", "lambda", "p", ":", "p", ".", "is_enum", "(", ")", ",", "self", ".", "get_params", "(", ")", ")", ":", "children", "=", "self", ".", "get_ports", "(", ")", "+", "self", ".", "get_params", "(", ")", "# Priority to the type controller", "if", "param", ".", "get_key", "(", ")", "in", "' '", ".", "join", "(", "map", "(", "lambda", "p", ":", "p", ".", "_type", ",", "children", ")", ")", ":", "type_param", "=", "param", "# Use param if type param is unset", "if", "not", "type_param", ":", "type_param", "=", "param", "if", "type_param", ":", "# Try to increment the enum by direction", "try", ":", "keys", "=", "type_param", ".", "get_option_keys", "(", ")", "old_index", "=", "keys", ".", "index", "(", "type_param", ".", "get_value", "(", ")", ")", "new_index", "=", "(", "old_index", "+", "direction", "+", "len", "(", "keys", ")", ")", "%", "len", "(", "keys", ")", "type_param", ".", "set_value", "(", "keys", "[", "new_index", "]", ")", "changed", "=", "True", "except", ":", "pass", "return", "changed" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/blocks/block.py#L699-L728
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sarray.py
python
SArray.shape
(self)
return (len(self),)
The shape of the SArray, in a tuple. The first entry is the number of rows. Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.shape (3,)
The shape of the SArray, in a tuple. The first entry is the number of rows.
[ "The", "shape", "of", "the", "SArray", "in", "a", "tuple", ".", "The", "first", "entry", "is", "the", "number", "of", "rows", "." ]
def shape(self): """ The shape of the SArray, in a tuple. The first entry is the number of rows. Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.shape (3,) """ return (len(self),)
[ "def", "shape", "(", "self", ")", ":", "return", "(", "len", "(", "self", ")", ",", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L939-L950
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/vis/glprogram.py
python
GLProgram.run
(self)
Starts a new event loop with this object as the main program. Note: might not return, in the case of GLUT.
Starts a new event loop with this object as the main program. Note: might not return, in the case of GLUT.
[ "Starts", "a", "new", "event", "loop", "with", "this", "object", "as", "the", "main", "program", ".", "Note", ":", "might", "not", "return", "in", "the", "case", "of", "GLUT", "." ]
def run(self): """Starts a new event loop with this object as the main program. Note: might not return, in the case of GLUT. """ from . import visualization visualization.setWindowTitle(self.name) visualization.run(self)
[ "def", "run", "(", "self", ")", ":", "from", ".", "import", "visualization", "visualization", ".", "setWindowTitle", "(", "self", ".", "name", ")", "visualization", ".", "run", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/glprogram.py#L57-L63
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/multiprocessing/pool.py
python
Pool.apply
(self, func, args=(), kwds={})
return self.apply_async(func, args, kwds).get()
Equivalent of `func(*args, **kwds)`. Pool must be running.
Equivalent of `func(*args, **kwds)`. Pool must be running.
[ "Equivalent", "of", "func", "(", "*", "args", "**", "kwds", ")", ".", "Pool", "must", "be", "running", "." ]
def apply(self, func, args=(), kwds={}): ''' Equivalent of `func(*args, **kwds)`. Pool must be running. ''' return self.apply_async(func, args, kwds).get()
[ "def", "apply", "(", "self", ",", "func", ",", "args", "=", "(", ")", ",", "kwds", "=", "{", "}", ")", ":", "return", "self", ".", "apply_async", "(", "func", ",", "args", ",", "kwds", ")", ".", "get", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/multiprocessing/pool.py#L256-L261
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/polynomial/chebyshev.py
python
_zseries_int
(zs)
return zs
Integrate a z-series. The integral is with respect to x, not z. This is achieved by a change of variable using dx/dz given in the module notes. Parameters ---------- zs : z-series The z-series to integrate Returns ------- integral : z-series The indefinite integral Notes ----- The zseries for x (ns) has been multiplied by two in order to avoid using floats that are incompatible with Decimal and likely other specialized scalar types. This scaling has been compensated by dividing the resulting zs by two.
Integrate a z-series.
[ "Integrate", "a", "z", "-", "series", "." ]
def _zseries_int(zs): """Integrate a z-series. The integral is with respect to x, not z. This is achieved by a change of variable using dx/dz given in the module notes. Parameters ---------- zs : z-series The z-series to integrate Returns ------- integral : z-series The indefinite integral Notes ----- The zseries for x (ns) has been multiplied by two in order to avoid using floats that are incompatible with Decimal and likely other specialized scalar types. This scaling has been compensated by dividing the resulting zs by two. """ n = 1 + len(zs)//2 ns = np.array([-1, 0, 1], dtype=zs.dtype) zs = _zseries_mul(zs, ns) div = np.arange(-n, n+1)*2 zs[:n] /= div[:n] zs[n+1:] /= div[n+1:] zs[n] = 0 return zs
[ "def", "_zseries_int", "(", "zs", ")", ":", "n", "=", "1", "+", "len", "(", "zs", ")", "//", "2", "ns", "=", "np", ".", "array", "(", "[", "-", "1", ",", "0", ",", "1", "]", ",", "dtype", "=", "zs", ".", "dtype", ")", "zs", "=", "_zseries_mul", "(", "zs", ",", "ns", ")", "div", "=", "np", ".", "arange", "(", "-", "n", ",", "n", "+", "1", ")", "*", "2", "zs", "[", ":", "n", "]", "/=", "div", "[", ":", "n", "]", "zs", "[", "n", "+", "1", ":", "]", "/=", "div", "[", "n", "+", "1", ":", "]", "zs", "[", "n", "]", "=", "0", "return", "zs" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/chebyshev.py#L309-L340
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
site_scons/libdeps.py
python
LibdepLinter._make_linter_decorator
()
return linter_rule_func
This is used for gathering the functions by decorator that will be used for linting a given libdep.
This is used for gathering the functions by decorator that will be used for linting a given libdep.
[ "This", "is", "used", "for", "gathering", "the", "functions", "by", "decorator", "that", "will", "be", "used", "for", "linting", "a", "given", "libdep", "." ]
def _make_linter_decorator(): """ This is used for gathering the functions by decorator that will be used for linting a given libdep. """ funcs = {} def linter_rule_func(func): funcs[func.__name__] = func return func linter_rule_func.all = funcs return linter_rule_func
[ "def", "_make_linter_decorator", "(", ")", ":", "funcs", "=", "{", "}", "def", "linter_rule_func", "(", "func", ")", ":", "funcs", "[", "func", ".", "__name__", "]", "=", "func", "return", "func", "linter_rule_func", ".", "all", "=", "funcs", "return", "linter_rule_func" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/site_scons/libdeps.py#L241-L253
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
PyApp_SetMacPreferencesMenuItemId
(*args, **kwargs)
return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)
PyApp_SetMacPreferencesMenuItemId(long val)
PyApp_SetMacPreferencesMenuItemId(long val)
[ "PyApp_SetMacPreferencesMenuItemId", "(", "long", "val", ")" ]
def PyApp_SetMacPreferencesMenuItemId(*args, **kwargs): """PyApp_SetMacPreferencesMenuItemId(long val)""" return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)
[ "def", "PyApp_SetMacPreferencesMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_SetMacPreferencesMenuItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L8302-L8304
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathWaterline.py
python
ObjectWaterline._extractWaterlines
(self, obj, oclScan, lyr, layDep)
return loopList
_extractWaterlines(obj, oclScan, lyr, layDep) ... Extract water lines from OCL scan data.
_extractWaterlines(obj, oclScan, lyr, layDep) ... Extract water lines from OCL scan data.
[ "_extractWaterlines", "(", "obj", "oclScan", "lyr", "layDep", ")", "...", "Extract", "water", "lines", "from", "OCL", "scan", "data", "." ]
def _extractWaterlines(self, obj, oclScan, lyr, layDep): """_extractWaterlines(obj, oclScan, lyr, layDep) ... Extract water lines from OCL scan data.""" srch = True lastPnt = len(self.topoMap[0]) - 1 lastLn = len(self.topoMap) - 1 maxSrchs = 5 srchCnt = 1 loopList = [] loop = [] loopNum = 0 if self.CutClimb is True: lC = [ -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, ] pC = [ -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, ] else: lC = [ 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, ] pC = [ -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, ] while srch is True: srch = False if srchCnt > maxSrchs: PathLog.debug( "Max search scans, " + str(maxSrchs) + " reached\nPossible incomplete waterline result!" ) break for L in range(1, lastLn): for P in range(1, lastPnt): if self.topoMap[L][P] == 1: # start loop follow srch = True loopNum += 1 loop = self._trackLoop(oclScan, lC, pC, L, P, loopNum) self.topoMap[L][P] = 0 # Mute the starting point loopList.append(loop) srchCnt += 1 PathLog.debug( "Search count for layer " + str(lyr) + " is " + str(srchCnt) + ", with " + str(loopNum) + " loops." ) return loopList
[ "def", "_extractWaterlines", "(", "self", ",", "obj", ",", "oclScan", ",", "lyr", ",", "layDep", ")", ":", "srch", "=", "True", "lastPnt", "=", "len", "(", "self", ".", "topoMap", "[", "0", "]", ")", "-", "1", "lastLn", "=", "len", "(", "self", ".", "topoMap", ")", "-", "1", "maxSrchs", "=", "5", "srchCnt", "=", "1", "loopList", "=", "[", "]", "loop", "=", "[", "]", "loopNum", "=", "0", "if", "self", ".", "CutClimb", "is", "True", ":", "lC", "=", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "]", "pC", "=", "[", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "]", "else", ":", "lC", "=", "[", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "]", "pC", "=", "[", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "1", ",", "1", ",", "1", ",", "0", ",", "-", "1", ",", "-", "1", ",", "]", "while", "srch", "is", "True", ":", "srch", "=", "False", "if", "srchCnt", ">", "maxSrchs", ":", "PathLog", ".", "debug", "(", "\"Max search scans, \"", "+", "str", "(", "maxSrchs", ")", "+", "\" reached\\nPossible incomplete waterline result!\"", ")", "break", "for", "L", "in", "range", "(", "1", ",", "lastLn", ")", ":", "for", "P", "in", "range", "(", "1", ",", "lastPnt", ")", ":", "if", "self", ".", "topoMap", "[", "L", "]", "[", "P", "]", "==", "1", ":", "# start loop follow", "srch", "=", "True", "loopNum", "+=", "1", "loop", "=", "self", ".", "_trackLoop", "(", "oclScan", ",", "lC", ",", "pC", ",", "L", ",", "P", ",", "loopNum", ")", "self", ".", "topoMap", "[", "L", "]", "[", "P", "]", "=", "0", "# Mute the starting point", "loopList", ".", "append", "(", "loop", ")", "srchCnt", "+=", "1", "PathLog", ".", "debug", "(", "\"Search count for layer \"", "+", "str", "(", "lyr", ")", "+", "\" is \"", "+", "str", "(", "srchCnt", ")", "+", "\", with \"", "+", "str", "(", "loopNum", ")", "+", "\" loops.\"", ")", "return", "loopList" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathWaterline.py#L1464-L1610
facebookresearch/mvfst-rl
778bc4259ae7277e67c2ead593a493845c93db83
scripts/plotting/plot_sweep.py
python
flags_to_set
(flags: Dict)
return {(k, tuple(v) if isinstance(v, list) else v) for k, v in flags.items()}
Turn a dictionary of settings into a set of unique (key, value) pairs
Turn a dictionary of settings into a set of unique (key, value) pairs
[ "Turn", "a", "dictionary", "of", "settings", "into", "a", "set", "of", "unique", "(", "key", "value", ")", "pairs" ]
def flags_to_set(flags: Dict) -> Set: """Turn a dictionary of settings into a set of unique (key, value) pairs""" # The tricky part is that some flags may be lists, that are not hashable. # We convert them to tuples here. return {(k, tuple(v) if isinstance(v, list) else v) for k, v in flags.items()}
[ "def", "flags_to_set", "(", "flags", ":", "Dict", ")", "->", "Set", ":", "# The tricky part is that some flags may be lists, that are not hashable.", "# We convert them to tuples here.", "return", "{", "(", "k", ",", "tuple", "(", "v", ")", "if", "isinstance", "(", "v", ",", "list", ")", "else", "v", ")", "for", "k", ",", "v", "in", "flags", ".", "items", "(", ")", "}" ]
https://github.com/facebookresearch/mvfst-rl/blob/778bc4259ae7277e67c2ead593a493845c93db83/scripts/plotting/plot_sweep.py#L175-L180
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/parent.py
python
ROSLaunchParent.start
(self, auto_terminate=True)
Run the parent roslaunch. @param auto_terminate: stop process monitor once there are no more processes to monitor (default True). This defaults to True, which is the command-line behavior of roslaunch. Scripts may wish to set this to False if they wish to keep the roslauch infrastructure up regardless of processes being monitored.
Run the parent roslaunch.
[ "Run", "the", "parent", "roslaunch", "." ]
def start(self, auto_terminate=True): """ Run the parent roslaunch. @param auto_terminate: stop process monitor once there are no more processes to monitor (default True). This defaults to True, which is the command-line behavior of roslaunch. Scripts may wish to set this to False if they wish to keep the roslauch infrastructure up regardless of processes being monitored. """ self.logger.info("starting roslaunch parent run") # load config, start XMLRPC servers and process monitor try: self._start_infrastructure() except: # infrastructure did not initialize, do teardown on whatever did come up self._stop_infrastructure() raise # Initialize the actual runner. # Requires config, pm, server and remote_runner self._init_runner() # Start the launch self.runner.launch() # inform process monitor that we are done with process registration if auto_terminate: self.pm.registrations_complete() self.logger.info("... roslaunch parent running, waiting for process exit") if self.process_listeners: for l in self.process_listeners: self.runner.pm.add_process_listener(l)
[ "def", "start", "(", "self", ",", "auto_terminate", "=", "True", ")", ":", "self", ".", "logger", ".", "info", "(", "\"starting roslaunch parent run\"", ")", "# load config, start XMLRPC servers and process monitor", "try", ":", "self", ".", "_start_infrastructure", "(", ")", "except", ":", "# infrastructure did not initialize, do teardown on whatever did come up", "self", ".", "_stop_infrastructure", "(", ")", "raise", "# Initialize the actual runner. ", "# Requires config, pm, server and remote_runner", "self", ".", "_init_runner", "(", ")", "# Start the launch", "self", ".", "runner", ".", "launch", "(", ")", "# inform process monitor that we are done with process registration", "if", "auto_terminate", ":", "self", ".", "pm", ".", "registrations_complete", "(", ")", "self", ".", "logger", ".", "info", "(", "\"... roslaunch parent running, waiting for process exit\"", ")", "if", "self", ".", "process_listeners", ":", "for", "l", "in", "self", ".", "process_listeners", ":", "self", ".", "runner", ".", "pm", ".", "add_process_listener", "(", "l", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/parent.py#L253-L288
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/pfor.py
python
WhileOp.pfor_converter
(self)
return self
Return a converter for the while loop.
Return a converter for the while loop.
[ "Return", "a", "converter", "for", "the", "while", "loop", "." ]
def pfor_converter(self): """Return a converter for the while loop.""" return self
[ "def", "pfor_converter", "(", "self", ")", ":", "return", "self" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/pfor.py#L260-L262
stitchEm/stitchEm
0f399501d41ab77933677f2907f41f80ceb704d7
lib/bindings/samples/server/glfw.py
python
get_version_string
()
return _glfw.glfwGetVersionString()
Returns a string describing the compile-time configuration. Wrapper for: const char* glfwGetVersionString(void);
Returns a string describing the compile-time configuration.
[ "Returns", "a", "string", "describing", "the", "compile", "-", "time", "configuration", "." ]
def get_version_string(): """ Returns a string describing the compile-time configuration. Wrapper for: const char* glfwGetVersionString(void); """ return _glfw.glfwGetVersionString()
[ "def", "get_version_string", "(", ")", ":", "return", "_glfw", ".", "glfwGetVersionString", "(", ")" ]
https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/glfw.py#L733-L740
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/keras/python/keras/engine/topology.py
python
Container.save_weights
(self, filepath, overwrite=True)
Dumps all layer weights to a HDF5 file. The weight file has: - `layer_names` (attribute), a list of strings (ordered names of model layers). - For every layer, a `group` named `layer.name` - For every such layer group, a group attribute `weight_names`, a list of strings (ordered names of weights tensor of the layer). - For every weight in the layer, a dataset storing the weight value, named after the weight tensor. Arguments: filepath: String, path to the file to save the weights to. overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt. Raises: ImportError: If h5py is not available.
Dumps all layer weights to a HDF5 file.
[ "Dumps", "all", "layer", "weights", "to", "a", "HDF5", "file", "." ]
def save_weights(self, filepath, overwrite=True): """Dumps all layer weights to a HDF5 file. The weight file has: - `layer_names` (attribute), a list of strings (ordered names of model layers). - For every layer, a `group` named `layer.name` - For every such layer group, a group attribute `weight_names`, a list of strings (ordered names of weights tensor of the layer). - For every weight in the layer, a dataset storing the weight value, named after the weight tensor. Arguments: filepath: String, path to the file to save the weights to. overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt. Raises: ImportError: If h5py is not available. """ if h5py is None: raise ImportError('`save_weights` requires h5py.') # If file exists and should not be overwritten: if not overwrite and os.path.isfile(filepath): proceed = ask_to_proceed_with_overwrite(filepath) if not proceed: return f = h5py.File(filepath, 'w') save_weights_to_hdf5_group(f, self.layers) f.flush() f.close()
[ "def", "save_weights", "(", "self", ",", "filepath", ",", "overwrite", "=", "True", ")", ":", "if", "h5py", "is", "None", ":", "raise", "ImportError", "(", "'`save_weights` requires h5py.'", ")", "# If file exists and should not be overwritten:", "if", "not", "overwrite", "and", "os", ".", "path", ".", "isfile", "(", "filepath", ")", ":", "proceed", "=", "ask_to_proceed_with_overwrite", "(", "filepath", ")", "if", "not", "proceed", ":", "return", "f", "=", "h5py", ".", "File", "(", "filepath", ",", "'w'", ")", "save_weights_to_hdf5_group", "(", "f", ",", "self", ".", "layers", ")", "f", ".", "flush", "(", ")", "f", ".", "close", "(", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/engine/topology.py#L2217-L2248
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/filters.py
python
do_unique
(environment, value, case_sensitive=False, attribute=None)
Returns a list of unique items from the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute.
Returns a list of unique items from the given iterable.
[ "Returns", "a", "list", "of", "unique", "items", "from", "the", "given", "iterable", "." ]
def do_unique(environment, value, case_sensitive=False, attribute=None): """Returns a list of unique items from the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. """ getter = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) seen = set() for item in value: key = getter(item) if key not in seen: seen.add(key) yield item
[ "def", "do_unique", "(", "environment", ",", "value", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "getter", "=", "make_attrgetter", "(", "environment", ",", "attribute", ",", "postprocess", "=", "ignore_case", "if", "not", "case_sensitive", "else", "None", ")", "seen", "=", "set", "(", ")", "for", "item", "in", "value", ":", "key", "=", "getter", "(", "item", ")", "if", "key", "not", "in", "seen", ":", "seen", ".", "add", "(", "key", ")", "yield", "item" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/filters.py#L352-L376
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Task.py
python
deep_inputs
(cls)
return cls
Task class decorator to enable rebuilds on input files task signatures
Task class decorator to enable rebuilds on input files task signatures
[ "Task", "class", "decorator", "to", "enable", "rebuilds", "on", "input", "files", "task", "signatures" ]
def deep_inputs(cls): """ Task class decorator to enable rebuilds on input files task signatures """ def sig_explicit_deps(self): Task.sig_explicit_deps(self) Task.sig_deep_inputs(self) cls.sig_explicit_deps = sig_explicit_deps return cls
[ "def", "deep_inputs", "(", "cls", ")", ":", "def", "sig_explicit_deps", "(", "self", ")", ":", "Task", ".", "sig_explicit_deps", "(", "self", ")", "Task", ".", "sig_deep_inputs", "(", "self", ")", "cls", ".", "sig_explicit_deps", "=", "sig_explicit_deps", "return", "cls" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Task.py#L1337-L1345
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/enum_type_wrapper.py
python
EnumTypeWrapper.__getattr__
(self, name)
Returns the value corresponding to the given enum name.
Returns the value corresponding to the given enum name.
[ "Returns", "the", "value", "corresponding", "to", "the", "given", "enum", "name", "." ]
def __getattr__(self, name): """Returns the value corresponding to the given enum name.""" try: return super( EnumTypeWrapper, self).__getattribute__('_enum_type').values_by_name[name].number except KeyError: pass # fall out to break exception chaining raise AttributeError('Enum {} has no value defined for name {!r}'.format( self._enum_type.name, name))
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "try", ":", "return", "super", "(", "EnumTypeWrapper", ",", "self", ")", ".", "__getattribute__", "(", "'_enum_type'", ")", ".", "values_by_name", "[", "name", "]", ".", "number", "except", "KeyError", ":", "pass", "# fall out to break exception chaining", "raise", "AttributeError", "(", "'Enum {} has no value defined for name {!r}'", ".", "format", "(", "self", ".", "_enum_type", ".", "name", ",", "name", ")", ")" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/enum_type_wrapper.py#L106-L115