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
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/graph_editor/select.py
python
filter_ops_from_regex
(ops, regex)
return filter_ops(ops, lambda op: regex_obj.search(op.name))
Get all the operations that match the given regex. Args: ops: an object convertible to a list of tf.Operation. regex: a regular expression matching the operation's name. For example, "^foo(/.*)?$" will match all the operations in the "foo" scope. Returns: A list of tf.Operation. Raises: TypeError: if ops cannot be converted to a list of tf.Operation.
Get all the operations that match the given regex.
[ "Get", "all", "the", "operations", "that", "match", "the", "given", "regex", "." ]
def filter_ops_from_regex(ops, regex): """Get all the operations that match the given regex. Args: ops: an object convertible to a list of tf.Operation. regex: a regular expression matching the operation's name. For example, "^foo(/.*)?$" will match all the operations in the "foo" scope. Returns: A list of tf.Operation. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ ops = util.make_list_of_op(ops) regex_obj = make_regex(regex) return filter_ops(ops, lambda op: regex_obj.search(op.name))
[ "def", "filter_ops_from_regex", "(", "ops", ",", "regex", ")", ":", "ops", "=", "util", ".", "make_list_of_op", "(", "ops", ")", "regex_obj", "=", "make_regex", "(", "regex", ")", "return", "filter_ops", "(", "ops", ",", "lambda", "op", ":", "regex_obj", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/select.py#L154-L169
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/browser/extension_dict.py
python
ExtensionDict.GetByExtensionId
(self, extension_id)
return self._extension_backend[extension_id]
Returns a list of extensions given an extension id. This is useful for connecting to built-in apps and component extensions.
Returns a list of extensions given an extension id. This is useful for connecting to built-in apps and component extensions.
[ "Returns", "a", "list", "of", "extensions", "given", "an", "extension", "id", ".", "This", "is", "useful", "for", "connecting", "to", "built", "-", "in", "apps", "and", "component", "extensions", "." ]
def GetByExtensionId(self, extension_id): """Returns a list of extensions given an extension id. This is useful for connecting to built-in apps and component extensions.""" return self._extension_backend[extension_id]
[ "def", "GetByExtensionId", "(", "self", ",", "extension_id", ")", ":", "return", "self", ".", "_extension_backend", "[", "extension_id", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/browser/extension_dict.py#L30-L33
netease-youdao/hex
d7b8773dae8dde63f3807cef1d48c017077db727
tools/file_util.py
python
backup_file
(name)
Rename the file to a name that includes the current time stamp.
Rename the file to a name that includes the current time stamp.
[ "Rename", "the", "file", "to", "a", "name", "that", "includes", "the", "current", "time", "stamp", "." ]
def backup_file(name): """ Rename the file to a name that includes the current time stamp. """ move_file(name, name+'.'+time.strftime('%Y-%m-%d-%H-%M-%S'))
[ "def", "backup_file", "(", "name", ")", ":", "move_file", "(", "name", ",", "name", "+", "'.'", "+", "time", ".", "strftime", "(", "'%Y-%m-%d-%H-%M-%S'", ")", ")" ]
https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/file_util.py#L53-L55
openweave/openweave-core
11ceb6b7efd39fe05de7f79229247a5774d56766
src/device-manager/python/openweave/WeaveBleBase.py
python
WeaveBleBase.connect
(self, identifier)
return
API to initiate BLE connection to peripheral device whose identifier == identifier.
API to initiate BLE connection to peripheral device whose identifier == identifier.
[ "API", "to", "initiate", "BLE", "connection", "to", "peripheral", "device", "whose", "identifier", "==", "identifier", "." ]
def connect(self, identifier): """ API to initiate BLE connection to peripheral device whose identifier == identifier.""" return
[ "def", "connect", "(", "self", ",", "identifier", ")", ":", "return" ]
https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/openweave/WeaveBleBase.py#L57-L59
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/summary/_writer_pool.py
python
WriterPool._flush
(self)
Flush the writers in the subprocess.
Flush the writers in the subprocess.
[ "Flush", "the", "writers", "in", "the", "subprocess", "." ]
def _flush(self): """Flush the writers in the subprocess.""" for writer in self._writers: writer.flush()
[ "def", "_flush", "(", "self", ")", ":", "for", "writer", "in", "self", ".", "_writers", ":", "writer", ".", "flush", "(", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/summary/_writer_pool.py#L159-L162
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typeinfer.py
python
TypeInferer.get_function_types
(self, typemap)
return calltypes
Fill and return the calltypes map.
Fill and return the calltypes map.
[ "Fill", "and", "return", "the", "calltypes", "map", "." ]
def get_function_types(self, typemap): """ Fill and return the calltypes map. """ # XXX why can't this be done on the fly? calltypes = self.calltypes for call, constraint in self.calls: calltypes[call] = constraint.get_call_signature() return calltypes
[ "def", "get_function_types", "(", "self", ",", "typemap", ")", ":", "# XXX why can't this be done on the fly?", "calltypes", "=", "self", ".", "calltypes", "for", "call", ",", "constraint", "in", "self", ".", "calls", ":", "calltypes", "[", "call", "]", "=", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typeinfer.py#L1207-L1215
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/ultratb.py
python
VerboseTB.debugger
(self, force=False)
Call up the pdb debugger if desired, always clean up the tb reference. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false. If the call_pdb flag is set, the pdb interactive debugger is invoked. In all cases, the self.tb reference to the current traceback is deleted to prevent lingering references which hamper memory management. Note that each call to pdb() does an 'import readline', so if your app requires a special setup for the readline completers, you'll have to fix that by hand after invoking the exception handler.
Call up the pdb debugger if desired, always clean up the tb reference.
[ "Call", "up", "the", "pdb", "debugger", "if", "desired", "always", "clean", "up", "the", "tb", "reference", "." ]
def debugger(self, force=False): """Call up the pdb debugger if desired, always clean up the tb reference. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false. If the call_pdb flag is set, the pdb interactive debugger is invoked. In all cases, the self.tb reference to the current traceback is deleted to prevent lingering references which hamper memory management. Note that each call to pdb() does an 'import readline', so if your app requires a special setup for the readline completers, you'll have to fix that by hand after invoking the exception handler.""" if force or self.call_pdb: if self.pdb is None: self.pdb = self.debugger_cls() # the system displayhook may have changed, restore the original # for pdb display_trap = DisplayTrap(hook=sys.__displayhook__) with display_trap: self.pdb.reset() # Find the right frame so we don't pop up inside ipython itself if hasattr(self, 'tb') and self.tb is not None: etb = self.tb else: etb = self.tb = sys.last_traceback while self.tb is not None and self.tb.tb_next is not None: self.tb = self.tb.tb_next if etb and etb.tb_next: etb = etb.tb_next self.pdb.botframe = etb.tb_frame self.pdb.interaction(None, etb) if hasattr(self, 'tb'): del self.tb
[ "def", "debugger", "(", "self", ",", "force", "=", "False", ")", ":", "if", "force", "or", "self", ".", "call_pdb", ":", "if", "self", ".", "pdb", "is", "None", ":", "self", ".", "pdb", "=", "self", ".", "debugger_cls", "(", ")", "# the system displa...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/ultratb.py#L1160-L1201
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/nn_ops.py
python
_AvgPool3DGradShape
(op)
return [tensor_shape.TensorShape(orig_input_shape).with_rank(5)]
Shape function for the AvgPool3DGrad op.
Shape function for the AvgPool3DGrad op.
[ "Shape", "function", "for", "the", "AvgPool3DGrad", "op", "." ]
def _AvgPool3DGradShape(op): """Shape function for the AvgPool3DGrad op.""" orig_input_shape = tensor_util.constant_value(op.inputs[0]) return [tensor_shape.TensorShape(orig_input_shape).with_rank(5)]
[ "def", "_AvgPool3DGradShape", "(", "op", ")", ":", "orig_input_shape", "=", "tensor_util", ".", "constant_value", "(", "op", ".", "inputs", "[", "0", "]", ")", "return", "[", "tensor_shape", ".", "TensorShape", "(", "orig_input_shape", ")", ".", "with_rank", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/nn_ops.py#L1000-L1003
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/transforms/scalarize.py
python
targets_and_priorities
( objectives: List[Union[Minimize, Maximize]], priorities, targets, limits=None, off_target: float = 1e-5 )
Combines objectives with penalties within a range between target and limit. Each Minimize objective i has value priorities[i]*objectives[i] when objectives[i] >= targets[i] +infinity when objectives[i] > limits[i] Each Maximize objective i has value priorities[i]*objectives[i] when objectives[i] <= targets[i] +infinity when objectives[i] < limits[i] Args: objectives: A list of Minimize/Maximize objectives. priorities: The weight within the trange. targets: The start (end) of penalty for Minimize (Maximize) limits: The hard end (start) of penalty for Minimize (Maximize) off_target: Penalty outside of target. Returns: A Minimize/Maximize objective.
Combines objectives with penalties within a range between target and limit.
[ "Combines", "objectives", "with", "penalties", "within", "a", "range", "between", "target", "and", "limit", "." ]
def targets_and_priorities( objectives: List[Union[Minimize, Maximize]], priorities, targets, limits=None, off_target: float = 1e-5 ) -> Union[Minimize, Maximize]: """Combines objectives with penalties within a range between target and limit. Each Minimize objective i has value priorities[i]*objectives[i] when objectives[i] >= targets[i] +infinity when objectives[i] > limits[i] Each Maximize objective i has value priorities[i]*objectives[i] when objectives[i] <= targets[i] +infinity when objectives[i] < limits[i] Args: objectives: A list of Minimize/Maximize objectives. priorities: The weight within the trange. targets: The start (end) of penalty for Minimize (Maximize) limits: The hard end (start) of penalty for Minimize (Maximize) off_target: Penalty outside of target. Returns: A Minimize/Maximize objective. """ num_objs = len(objectives) new_objs: List[Union[Minimize, Maximize]] = [] for i in range(num_objs): obj = objectives[i] sign = 1 if Constant.cast_to_const(priorities[i]).is_nonneg() else -1 off_target *= sign if type(obj) == Minimize: expr = (priorities[i] - off_target)*atoms.pos(obj.args[0] - targets[i]) expr += off_target*obj.args[0] if limits is not None: expr += sign*indicator([obj.args[0] <= limits[i]]) new_objs.append(expr) else: # Maximize expr = (priorities[i] - off_target)*atoms.min_elemwise(obj.args[0], targets[i]) expr += off_target*obj.args[0] if limits is not None: expr += sign*indicator([obj.args[0] >= limits[i]]) new_objs.append(expr) obj_expr = sum(new_objs) if obj_expr.is_convex(): return Minimize(obj_expr) else: return Maximize(obj_expr)
[ "def", "targets_and_priorities", "(", "objectives", ":", "List", "[", "Union", "[", "Minimize", ",", "Maximize", "]", "]", ",", "priorities", ",", "targets", ",", "limits", "=", "None", ",", "off_target", ":", "float", "=", "1e-5", ")", "->", "Union", "[...
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/transforms/scalarize.py#L38-L91
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/docs/parser.py
python
_ClassPageInfo.for_class
(self)
return True
Returns true if this object documents a class.
Returns true if this object documents a class.
[ "Returns", "true", "if", "this", "object", "documents", "a", "class", "." ]
def for_class(self): """Returns true if this object documents a class.""" return True
[ "def", "for_class", "(", "self", ")", ":", "return", "True" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/docs/parser.py#L985-L987
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/gen_protorpc.py
python
generate_file_descriptor
(dest_dir, file_descriptor, force_overwrite)
Generate a single file descriptor to destination directory. Will generate a single Python file from a file descriptor under dest_dir. The sub-directory where the file is generated is determined by the package name of descriptor. Descriptors without package names will not be generated. Descriptors that are part of the ProtoRPC distribution will not be generated. Args: dest_dir: Directory under which to generate files. file_descriptor: FileDescriptor instance to generate source code from. force_overwrite: If True, existing files will be overwritten.
Generate a single file descriptor to destination directory.
[ "Generate", "a", "single", "file", "descriptor", "to", "destination", "directory", "." ]
def generate_file_descriptor(dest_dir, file_descriptor, force_overwrite): """Generate a single file descriptor to destination directory. Will generate a single Python file from a file descriptor under dest_dir. The sub-directory where the file is generated is determined by the package name of descriptor. Descriptors without package names will not be generated. Descriptors that are part of the ProtoRPC distribution will not be generated. Args: dest_dir: Directory under which to generate files. file_descriptor: FileDescriptor instance to generate source code from. force_overwrite: If True, existing files will be overwritten. """ package = file_descriptor.package if not package: # TODO(rafek): Option to cause an error on this condition. logging.warn('Will not generate descriptor without package name') return if package in EXCLUDED_PACKAGES: logging.warn('Will not generate main ProtoRPC class %s' % package) return package_path = package.split('.') directory = package_path[:-1] package_file_name = package_path[-1] directory_name = os.path.join(dest_dir, *directory) output_file_name = os.path.join(directory_name, '%s.py' % (package_file_name,)) try: os.makedirs(directory_name) except OSError, err: if err.errno != errno.EEXIST: raise if not force_overwrite and os.path.exists(output_file_name): logging.warn('Not overwriting %s with package %s', output_file_name, package) return output_file = open(output_file_name, 'w') logging.info('Writing package %s to %s', file_descriptor.package, output_file_name) generate_python.format_python_file(file_descriptor, output_file)
[ "def", "generate_file_descriptor", "(", "dest_dir", ",", "file_descriptor", ",", "force_overwrite", ")", ":", "package", "=", "file_descriptor", ".", "package", "if", "not", "package", ":", "# TODO(rafek): Option to cause an error on this condition.", "logging", ".", "war...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/gen_protorpc.py#L79-L127
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/xml/dom/minidom.py
python
ElementInfo.isIdNS
(self, namespaceURI, localName)
return False
Returns true iff the identified attribute is a DTD-style ID.
Returns true iff the identified attribute is a DTD-style ID.
[ "Returns", "true", "iff", "the", "identified", "attribute", "is", "a", "DTD", "-", "style", "ID", "." ]
def isIdNS(self, namespaceURI, localName): """Returns true iff the identified attribute is a DTD-style ID.""" return False
[ "def", "isIdNS", "(", "self", ",", "namespaceURI", ",", "localName", ")", ":", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/xml/dom/minidom.py#L1456-L1458
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Bitmap.SetSize
(*args, **kwargs)
return _gdi_.Bitmap_SetSize(*args, **kwargs)
SetSize(self, Size size) Set the bitmap size (does not affect the existing bitmap data).
SetSize(self, Size size)
[ "SetSize", "(", "self", "Size", "size", ")" ]
def SetSize(*args, **kwargs): """ SetSize(self, Size size) Set the bitmap size (does not affect the existing bitmap data). """ return _gdi_.Bitmap_SetSize(*args, **kwargs)
[ "def", "SetSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Bitmap_SetSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L781-L787
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/ComponentVisitorBase.py
python
ComponentVisitorBase.buildFileName
(self, obj)
return filename
Build the file name
Build the file name
[ "Build", "the", "file", "name" ]
def buildFileName(self, obj): """ Build the file name """ if self.config("component", "XMLDefaultFileName") == "True": filename = ( obj.get_namespace() + obj.get_name() + self.config("component", self.__visitor) ) DEBUG.info( "Generating code filename: %s, using XML namespace and name attributes..." % filename ) else: xml_file = obj.get_xml_filename() x = xml_file.split(".") s = self.config("component", "ComponentXML").split(".") l = len(s[0]) if (x[0][-l:] == s[0]) & (x[1] == s[1]): filename = x[0].split(s[0])[0] + self.config( "component", self.__visitor ) DEBUG.info("Generating code filename: %s..." % filename) else: msg = ( "XML file naming format not allowed (must be XXXComponentAi.xml), Filename: %s" % xml_file ) PRINT.info(msg) raise ValueError(msg) return filename
[ "def", "buildFileName", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "config", "(", "\"component\"", ",", "\"XMLDefaultFileName\"", ")", "==", "\"True\"", ":", "filename", "=", "(", "obj", ".", "get_namespace", "(", ")", "+", "obj", ".", "get_na...
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/ComponentVisitorBase.py#L73-L104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListMainWindow.GetTextLength
(self, s)
return lw + AUTOSIZE_COL_MARGIN
Returns the text width for the input string. :param `s`: the string to measure.
Returns the text width for the input string.
[ "Returns", "the", "text", "width", "for", "the", "input", "string", "." ]
def GetTextLength(self, s): """ Returns the text width for the input string. :param `s`: the string to measure. """ dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) lw, lh, dummy = dc.GetMultiLineTextExtent(s) return lw + AUTOSIZE_COL_MARGIN
[ "def", "GetTextLength", "(", "self", ",", "s", ")", ":", "dc", "=", "wx", ".", "ClientDC", "(", "self", ")", "dc", ".", "SetFont", "(", "self", ".", "GetFont", "(", ")", ")", "lw", ",", "lh", ",", "dummy", "=", "dc", ".", "GetMultiLineTextExtent", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L8389-L8401
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
cpp/build-support/cpplint.py
python
CleanseComments
(line)
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed.
Removes //-comments and single-line C-style /* */ comments.
[ "Removes", "//", "-", "comments", "and", "single", "-", "line", "C", "-", "style", "/", "*", "*", "/", "comments", "." ]
def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
[ "def", "CleanseComments", "(", "line", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", "and", "not", "IsCppString", "(", "line", "[", ":", "commentpos", "]", ")", ":", "line", "=", "line", "[", ...
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/cpp/build-support/cpplint.py#L1578-L1591
bareos/bareos
56a10bb368b0a81e977bb51304033fe49d59efb0
core/src/plugins/filed/python/vmware/BareosFdPluginVMware.py
python
BareosVADPWrapper.get_vm_disk_root_filename
(self, disk_device_backing)
return actual_backing.fileName
Get the disk name from the ende of the parents chain When snapshots exist, the original disk filename is needed. If no snapshots exist, the disk has no parent and the filename is the same.
Get the disk name from the ende of the parents chain When snapshots exist, the original disk filename is needed. If no snapshots exist, the disk has no parent and the filename is the same.
[ "Get", "the", "disk", "name", "from", "the", "ende", "of", "the", "parents", "chain", "When", "snapshots", "exist", "the", "original", "disk", "filename", "is", "needed", ".", "If", "no", "snapshots", "exist", "the", "disk", "has", "no", "parent", "and", ...
def get_vm_disk_root_filename(self, disk_device_backing): """ Get the disk name from the ende of the parents chain When snapshots exist, the original disk filename is needed. If no snapshots exist, the disk has no parent and the filename is the same. """ actual_backing = disk_device_backing while actual_backing.parent: actual_backing = actual_backing.parent return actual_backing.fileName
[ "def", "get_vm_disk_root_filename", "(", "self", ",", "disk_device_backing", ")", ":", "actual_backing", "=", "disk_device_backing", "while", "actual_backing", ".", "parent", ":", "actual_backing", "=", "actual_backing", ".", "parent", "return", "actual_backing", ".", ...
https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/filed/python/vmware/BareosFdPluginVMware.py#L1203-L1213
briantrice/slate-language
a0daf5c8a40ba3e5d5368e34ab651284d803e570
src/profiler/gprof2dot.py
python
Profile._tarjan
(self, function, order, stack, orders, lowlinks, visited)
return order
Tarjan's strongly connected components algorithm. See also: - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
Tarjan's strongly connected components algorithm.
[ "Tarjan", "s", "strongly", "connected", "components", "algorithm", "." ]
def _tarjan(self, function, order, stack, orders, lowlinks, visited): """Tarjan's strongly connected components algorithm. See also: - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm """ visited.add(function) orders[function] = order lowlinks[function] = order order += 1 pos = len(stack) stack.append(function) for call in function.calls.itervalues(): callee = self.functions[call.callee_id] # TODO: use a set to optimize lookup if callee not in orders: order = self._tarjan(callee, order, stack, orders, lowlinks, visited) lowlinks[function] = min(lowlinks[function], lowlinks[callee]) elif callee in stack: lowlinks[function] = min(lowlinks[function], orders[callee]) if lowlinks[function] == orders[function]: # Strongly connected component found members = stack[pos:] del stack[pos:] if len(members) > 1: cycle = Cycle() for member in members: cycle.add_function(member) return order
[ "def", "_tarjan", "(", "self", ",", "function", ",", "order", ",", "stack", ",", "orders", ",", "lowlinks", ",", "visited", ")", ":", "visited", ".", "add", "(", "function", ")", "orders", "[", "function", "]", "=", "order", "lowlinks", "[", "function"...
https://github.com/briantrice/slate-language/blob/a0daf5c8a40ba3e5d5368e34ab651284d803e570/src/profiler/gprof2dot.py#L263-L292
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/grappler/model_analyzer.py
python
GenerateModelReport
(metagraph)
return ret_from_swig
Report what's known statically about each node in the provided metagraph. Args: metagraph: A TensorFlow MetaGraphDef. Returns: A string containing the report.
Report what's known statically about each node in the provided metagraph.
[ "Report", "what", "s", "known", "statically", "about", "each", "node", "in", "the", "provided", "metagraph", "." ]
def GenerateModelReport(metagraph): """Report what's known statically about each node in the provided metagraph. Args: metagraph: A TensorFlow MetaGraphDef. Returns: A string containing the report. """ with errors.raise_exception_on_not_ok_status(): ret_from_swig = tf_wrap.GenerateModelReport(metagraph.SerializeToString()) return ret_from_swig
[ "def", "GenerateModelReport", "(", "metagraph", ")", ":", "with", "errors", ".", "raise_exception_on_not_ok_status", "(", ")", ":", "ret_from_swig", "=", "tf_wrap", ".", "GenerateModelReport", "(", "metagraph", ".", "SerializeToString", "(", ")", ")", "return", "r...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/grappler/model_analyzer.py#L25-L37
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/serialposix.py
python
Serial.in_waiting
(self)
return struct.unpack('I', s)[0]
Return the number of bytes currently in the input buffer.
Return the number of bytes currently in the input buffer.
[ "Return", "the", "number", "of", "bytes", "currently", "in", "the", "input", "buffer", "." ]
def in_waiting(self): """Return the number of bytes currently in the input buffer.""" #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I', s)[0]
[ "def", "in_waiting", "(", "self", ")", ":", "#~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)", "s", "=", "fcntl", ".", "ioctl", "(", "self", ".", "fd", ",", "TIOCINQ", ",", "TIOCM_zero_str", ")", "return", "struct", ".", "unpack", "(", "'I'", ",", ...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/serialposix.py#L464-L468
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/io/__init__.py
python
MinibatchSource.next_minibatch
(self, minibatch_size_in_samples, input_map=None, device=None, num_data_partitions=None, partition_index=None)
return self._last_mb_data
Reads a minibatch that contains data for all input streams. The minibatch size is specified in terms of #samples and/or #sequences for the primary input stream; value of 0 for #samples/#sequences means unspecified. In case the size is specified in terms of both #sequences and #samples, the smaller of the 2 is taken. An empty map is returned when the MinibatchSource has no more data to return. Args: minibatch_size_in_samples (int): number of samples to retrieve for the next minibatch. Must be > 0. **Important:** Click :cntkwiki:`here <BrainScript-minibatchSize-and-Python-minibatch_size_in_samples-in-CNTK>` for a full description of this parameter. input_map (dict): mapping of :class:`~cntk.variables.Variable` to :class:`StreamInformation` which will be used to convert the returned data. device (`DeviceDescriptor`, defaults to `None`): CNTK DeviceDescriptor num_data_partitions: Used for distributed training, indicates into how many partitions the source should split the data. partition_index (`int`, defaults to `None`): Used for distributed training, indicates data from which partition to take. Returns: cntk.io.MinibatchData: A mapping of :class:`StreamInformation` to :class:`MinibatchData` if `input_map` was not specified. Otherwise, the returned value will be a mapping of :class:`~cntk.variables.Variable` to class:`MinibatchData`. When the maximum number of epochs/samples is exhausted, the return value is an empty dict.
Reads a minibatch that contains data for all input streams. The minibatch size is specified in terms of #samples and/or #sequences for the primary input stream; value of 0 for #samples/#sequences means unspecified. In case the size is specified in terms of both #sequences and #samples, the smaller of the 2 is taken. An empty map is returned when the MinibatchSource has no more data to return.
[ "Reads", "a", "minibatch", "that", "contains", "data", "for", "all", "input", "streams", ".", "The", "minibatch", "size", "is", "specified", "in", "terms", "of", "#samples", "and", "/", "or", "#sequences", "for", "the", "primary", "input", "stream", ";", "...
def next_minibatch(self, minibatch_size_in_samples, input_map=None, device=None, num_data_partitions=None, partition_index=None): ''' Reads a minibatch that contains data for all input streams. The minibatch size is specified in terms of #samples and/or #sequences for the primary input stream; value of 0 for #samples/#sequences means unspecified. In case the size is specified in terms of both #sequences and #samples, the smaller of the 2 is taken. An empty map is returned when the MinibatchSource has no more data to return. Args: minibatch_size_in_samples (int): number of samples to retrieve for the next minibatch. Must be > 0. **Important:** Click :cntkwiki:`here <BrainScript-minibatchSize-and-Python-minibatch_size_in_samples-in-CNTK>` for a full description of this parameter. input_map (dict): mapping of :class:`~cntk.variables.Variable` to :class:`StreamInformation` which will be used to convert the returned data. device (`DeviceDescriptor`, defaults to `None`): CNTK DeviceDescriptor num_data_partitions: Used for distributed training, indicates into how many partitions the source should split the data. partition_index (`int`, defaults to `None`): Used for distributed training, indicates data from which partition to take. Returns: cntk.io.MinibatchData: A mapping of :class:`StreamInformation` to :class:`MinibatchData` if `input_map` was not specified. Otherwise, the returned value will be a mapping of :class:`~cntk.variables.Variable` to class:`MinibatchData`. When the maximum number of epochs/samples is exhausted, the return value is an empty dict. ''' if self._last_mb_data is not None: self._last_mb_data.clear() if device is None: device = use_default_device() if num_data_partitions is None: num_data_partitions = 1 if partition_index is None: partition_index = 0 parent_inst = super(MinibatchSource, self) mb = parent_inst.get_next_minibatch(0, minibatch_size_in_samples, num_data_partitions, partition_index, device) if not mb: return mb if not input_map: return mb # We copy minibatch data here, # we need to make sure it is cleaned when next_minibatch # is called next time. self._last_mb_data = {key: mb[value] for (key, value) in input_map.items()} return self._last_mb_data
[ "def", "next_minibatch", "(", "self", ",", "minibatch_size_in_samples", ",", "input_map", "=", "None", ",", "device", "=", "None", ",", "num_data_partitions", "=", "None", ",", "partition_index", "=", "None", ")", ":", "if", "self", ".", "_last_mb_data", "is",...
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/io/__init__.py#L285-L344
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/fx/experimental/unification/utils.py
python
transitive_get
(key, d)
return key
Transitive dict.get >>> d = {1: 2, 2: 3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1, d) 4
Transitive dict.get >>> d = {1: 2, 2: 3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1, d) 4
[ "Transitive", "dict", ".", "get", ">>>", "d", "=", "{", "1", ":", "2", "2", ":", "3", "3", ":", "4", "}", ">>>", "d", ".", "get", "(", "1", ")", "2", ">>>", "transitive_get", "(", "1", "d", ")", "4" ]
def transitive_get(key, d): """ Transitive dict.get >>> d = {1: 2, 2: 3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1, d) 4 """ while hashable(key) and key in d: key = d[key] return key
[ "def", "transitive_get", "(", "key", ",", "d", ")", ":", "while", "hashable", "(", "key", ")", "and", "key", "in", "d", ":", "key", "=", "d", "[", "key", "]", "return", "key" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/unification/utils.py#L9-L19
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar._find_no_duplicates
(self, name, domain=None, path=None)
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. Takes as args name and optional domain and path. Returns a cookie.value. Throws KeyError if cookie is not found and CookieConflictError if there are multiple cookies that match name and optionally domain and path.
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. Takes as args name and optional domain and path. Returns a cookie.value. Throws KeyError if cookie is not found and CookieConflictError if there are multiple cookies that match name and optionally domain and path.
[ "Both", "__get_item__", "and", "get", "call", "this", "function", ":", "it", "s", "never", "used", "elsewhere", "in", "Requests", ".", "Takes", "as", "args", "name", "and", "optional", "domain", "and", "path", ".", "Returns", "a", "cookie", ".", "value", ...
def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. Takes as args name and optional domain and path. Returns a cookie.value. Throws KeyError if cookie is not found and CookieConflictError if there are multiple cookies that match name and optionally domain and path.""" toReturn = None for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError('There are multiple cookies with name, %r' % (name)) toReturn = cookie.value # we will eventually return this as long as no cookie conflict if toReturn: return toReturn raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
[ "def", "_find_no_duplicates", "(", "self", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "toReturn", "=", "None", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "name", "==", "name", ":", "...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py#L324-L341
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_d.py
python
SyntaxData.GetKeywords
(self)
return [D_KEYWORDS, D_TYPES, DOC_KEYWORDS]
Returns Specified Keywords List
Returns Specified Keywords List
[ "Returns", "Specified", "Keywords", "List" ]
def GetKeywords(self): """Returns Specified Keywords List """ return [D_KEYWORDS, D_TYPES, DOC_KEYWORDS]
[ "def", "GetKeywords", "(", "self", ")", ":", "return", "[", "D_KEYWORDS", ",", "D_TYPES", ",", "DOC_KEYWORDS", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_d.py#L130-L132
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py
python
MaskedArray._set_shape
(self, newshape)
Set the array's shape.
Set the array's shape.
[ "Set", "the", "array", "s", "shape", "." ]
def _set_shape (self, newshape): "Set the array's shape." self._data.shape = newshape if self._mask is not nomask: self._mask = self._mask.copy() self._mask.shape = newshape
[ "def", "_set_shape", "(", "self", ",", "newshape", ")", ":", "self", ".", "_data", ".", "shape", "=", "newshape", "if", "self", ".", "_mask", "is", "not", "nomask", ":", "self", ".", "_mask", "=", "self", ".", "_mask", ".", "copy", "(", ")", "self"...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L677-L682
INK-USC/USC-DS-RelationExtraction
eebcfa7fd2eda5bba92f3ef8158797cdf91e6981
code/Evaluation/evaluation.py
python
evaluate_rm
(prediction, ground_truth)
return precision,recall,f1
Evaluation matrix. :param prediction: a dictionary of labels. e.g {0:[1,0],1:[2],2:[3,4],3:[5,6,7]} :param ground_truth: a dictionary of labels :return:
Evaluation matrix. :param prediction: a dictionary of labels. e.g {0:[1,0],1:[2],2:[3,4],3:[5,6,7]} :param ground_truth: a dictionary of labels :return:
[ "Evaluation", "matrix", ".", ":", "param", "prediction", ":", "a", "dictionary", "of", "labels", ".", "e", ".", "g", "{", "0", ":", "[", "1", "0", "]", "1", ":", "[", "2", "]", "2", ":", "[", "3", "4", "]", "3", ":", "[", "5", "6", "7", "...
def evaluate_rm(prediction, ground_truth): """ Evaluation matrix. :param prediction: a dictionary of labels. e.g {0:[1,0],1:[2],2:[3,4],3:[5,6,7]} :param ground_truth: a dictionary of labels :return: """ pos_pred = 0.0 pos_gt = len(ground_truth) + 0.0 true_pos = 0.0 for i in prediction: # classified as pos example (Is-A-Relation) pos_pred += 1.0 if i in ground_truth and prediction[i] == ground_truth[i]: true_pos += 1.0 precision = true_pos / (pos_pred + 1e-8) recall = true_pos / (pos_gt + 1e-8) f1 = 2 * precision * recall / (precision + recall + 1e-8) # print "predicted # Pos RMs:%d, ground-truth #Pos RMs:%d"%(int(pos_pred), int(pos_gt)) return precision,recall,f1
[ "def", "evaluate_rm", "(", "prediction", ",", "ground_truth", ")", ":", "pos_pred", "=", "0.0", "pos_gt", "=", "len", "(", "ground_truth", ")", "+", "0.0", "true_pos", "=", "0.0", "for", "i", "in", "prediction", ":", "# classified as pos example (Is-A-Relation)"...
https://github.com/INK-USC/USC-DS-RelationExtraction/blob/eebcfa7fd2eda5bba92f3ef8158797cdf91e6981/code/Evaluation/evaluation.py#L56-L79
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.SetLineState
(*args, **kwargs)
return _stc.StyledTextCtrl_SetLineState(*args, **kwargs)
SetLineState(self, int line, int state) Used to hold extra styling information for each line.
SetLineState(self, int line, int state)
[ "SetLineState", "(", "self", "int", "line", "int", "state", ")" ]
def SetLineState(*args, **kwargs): """ SetLineState(self, int line, int state) Used to hold extra styling information for each line. """ return _stc.StyledTextCtrl_SetLineState(*args, **kwargs)
[ "def", "SetLineState", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetLineState", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2963-L2969
arx/ArxLibertatis
0313c51625f3f55016cdad43d2c7f7296d27949c
scripts/cpplint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). 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.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). 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] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone # is using braces in a block to explicitly create a new scope, # which is commonly used to control the lifetime of # stack-allocated variables. We don't detect this perfectly: we # just don't complain if the last non-whitespace character on the # previous non-blank line is ';', ':', '{', or '}'. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if not Search(r'[;:}{]\s*$', prevline): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Braces shouldn't be followed by a ; unless they're defining a struct # or initializing an array. # We can't tell in general, but we can for some common cases. prevlinenum = linenum while True: (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum) if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'): line = prevline + line else: break if (Search(r'{.*}\s*;', line) and line.count('{') == line.count('}') and not Search(r'struct|class|enum|\s*=\s*{|return|\[.*\]\(.*\).*{', line)): error(filename, linenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", ...
https://github.com/arx/ArxLibertatis/blob/0313c51625f3f55016cdad43d2c7f7296d27949c/scripts/cpplint.py#L2187-L2258
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiManager.Render
(self, dc)
Fires a render event, which is normally handled by :meth:`OnRender`. This allows the render function to be overridden via the render event. This can be useful for painting custom graphics in the main window. Default behavior can be invoked in the overridden function by calling :meth:`OnRender`. :param `dc`: a :class:`DC` device context object.
Fires a render event, which is normally handled by :meth:`OnRender`. This allows the render function to be overridden via the render event.
[ "Fires", "a", "render", "event", "which", "is", "normally", "handled", "by", ":", "meth", ":", "OnRender", ".", "This", "allows", "the", "render", "function", "to", "be", "overridden", "via", "the", "render", "event", "." ]
def Render(self, dc): """ Fires a render event, which is normally handled by :meth:`OnRender`. This allows the render function to be overridden via the render event. This can be useful for painting custom graphics in the main window. Default behavior can be invoked in the overridden function by calling :meth:`OnRender`. :param `dc`: a :class:`DC` device context object. """ e = AuiManagerEvent(wxEVT_AUI_RENDER) e.SetManager(self) e.SetDC(dc) self.ProcessMgrEvent(e)
[ "def", "Render", "(", "self", ",", "dc", ")", ":", "e", "=", "AuiManagerEvent", "(", "wxEVT_AUI_RENDER", ")", "e", ".", "SetManager", "(", "self", ")", "e", ".", "SetDC", "(", "dc", ")", "self", ".", "ProcessMgrEvent", "(", "e", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L8715-L8730
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/_vendor/packaging/specifiers.py
python
BaseSpecifier.filter
(self, iterable, prereleases=None)
Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it.
Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it.
[ "Takes", "an", "iterable", "of", "items", "and", "filters", "them", "so", "that", "only", "items", "which", "are", "contained", "within", "this", "specifier", "are", "allowed", "in", "it", "." ]
def filter(self, iterable, prereleases=None): """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """
[ "def", "filter", "(", "self", ",", "iterable", ",", "prereleases", "=", "None", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/_vendor/packaging/specifiers.py#L70-L74
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
clang/utils/check_cfc/check_cfc.py
python
add_output_file
(args, output_file)
return args + ['-o', output_file]
Append an output file to args, presuming not already specified.
Append an output file to args, presuming not already specified.
[ "Append", "an", "output", "file", "to", "args", "presuming", "not", "already", "specified", "." ]
def add_output_file(args, output_file): """Append an output file to args, presuming not already specified.""" return args + ['-o', output_file]
[ "def", "add_output_file", "(", "args", ",", "output_file", ")", ":", "return", "args", "+", "[", "'-o'", ",", "output_file", "]" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/utils/check_cfc/check_cfc.py#L172-L174
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/collections.py
python
Counter.__add__
(self, other)
return result
Add counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1})
Add counts from two counters.
[ "Add", "counts", "from", "two", "counters", "." ]
def __add__(self, other): '''Add counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): newcount = count + other[elem] if newcount > 0: result[elem] = newcount for elem, count in other.items(): if elem not in self and count > 0: result[elem] = count return result
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Counter", ")", ":", "return", "NotImplemented", "result", "=", "Counter", "(", ")", "for", "elem", ",", "count", "in", "self", ".", "items", "(", ")...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/collections.py#L633-L650
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Tools/MakeMacBundleRelocatable.py
python
get_rpaths
(library)
return rpaths
Returns a list of rpaths specified within library
Returns a list of rpaths specified within library
[ "Returns", "a", "list", "of", "rpaths", "specified", "within", "library" ]
def get_rpaths(library): "Returns a list of rpaths specified within library" out = check_output(["otool", "-l", library]) pathRegex = r"^path (.*) \(offset \d+\)$" expectingRpath = False rpaths = [] for line in out.split('\n'): line = line.strip() if "cmd LC_RPATH" in line: expectingRpath = True elif "Load command" in line: expectingRpath = False elif expectingRpath: m = re.match(pathRegex, line) if m: rpaths.append(m.group(1)) expectingRpath = False return rpaths
[ "def", "get_rpaths", "(", "library", ")", ":", "out", "=", "check_output", "(", "[", "\"otool\"", ",", "\"-l\"", ",", "library", "]", ")", "pathRegex", "=", "r\"^path (.*) \\(offset \\d+\\)$\"", "expectingRpath", "=", "False", "rpaths", "=", "[", "]", "for", ...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Tools/MakeMacBundleRelocatable.py#L271-L292
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_handlers.py
python
MessagingHandler.on_link_closed
(self, event: Event)
Called when the link is closed. :param event: The underlying event object. Use this to obtain further information on the event.
Called when the link is closed.
[ "Called", "when", "the", "link", "is", "closed", "." ]
def on_link_closed(self, event: Event) -> None: """ Called when the link is closed. :param event: The underlying event object. Use this to obtain further information on the event. """ pass
[ "def", "on_link_closed", "(", "self", ",", "event", ":", "Event", ")", "->", "None", ":", "pass" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_handlers.py#L780-L787
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/compile_java.py
python
_InfoFileContext.Commit
(self, output_path)
Writes a .jar.info file. Maps fully qualified names for classes to either the java file that they are defined in or the path of the srcjar that they came from.
Writes a .jar.info file.
[ "Writes", "a", ".", "jar", ".", "info", "file", "." ]
def Commit(self, output_path): """Writes a .jar.info file. Maps fully qualified names for classes to either the java file that they are defined in or the path of the srcjar that they came from. """ logging.info('Collecting info file entries') entries = self._Collect() logging.info('Writing info file: %s', output_path) with build_utils.AtomicOutput(output_path, mode='wb') as f: jar_info_utils.WriteJarInfoFile(f, entries, self._srcjar_files) logging.info('Completed info file: %s', output_path)
[ "def", "Commit", "(", "self", ",", "output_path", ")", ":", "logging", ".", "info", "(", "'Collecting info file entries'", ")", "entries", "=", "self", ".", "_Collect", "(", ")", "logging", ".", "info", "(", "'Writing info file: %s'", ",", "output_path", ")", ...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/compile_java.py#L352-L364
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/build_ext.py
python
get_abi3_suffix
()
Return the file extension for an abi3-compliant Extension()
Return the file extension for an abi3-compliant Extension()
[ "Return", "the", "file", "extension", "for", "an", "abi3", "-", "compliant", "Extension", "()" ]
def get_abi3_suffix(): """Return the file extension for an abi3-compliant Extension()""" for suffix in EXTENSION_SUFFIXES: if '.abi3' in suffix: # Unix return suffix elif suffix == '.pyd': # Windows return suffix
[ "def", "get_abi3_suffix", "(", ")", ":", "for", "suffix", "in", "EXTENSION_SUFFIXES", ":", "if", "'.abi3'", "in", "suffix", ":", "# Unix", "return", "suffix", "elif", "suffix", "==", "'.pyd'", ":", "# Windows", "return", "suffix" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/build_ext.py#L74-L80
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py
python
TCPServer.shutdown
(self)
shutdown I/O resources uses by this server
shutdown I/O resources uses by this server
[ "shutdown", "I", "/", "O", "resources", "uses", "by", "this", "server" ]
def shutdown(self): """shutdown I/O resources uses by this server""" if not self.is_shutdown: self.is_shutdown = True self.server_sock.close()
[ "def", "shutdown", "(", "self", ")", ":", "if", "not", "self", ".", "is_shutdown", ":", "self", ".", "is_shutdown", "=", "True", "self", ".", "server_sock", ".", "close", "(", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py#L204-L208
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/fps/connection.py
python
FPSConnection.get_tokens
(self, action, response, **kw)
return self.get_object(action, kw, response)
Returns a list of tokens installed on the given account.
Returns a list of tokens installed on the given account.
[ "Returns", "a", "list", "of", "tokens", "installed", "on", "the", "given", "account", "." ]
def get_tokens(self, action, response, **kw): """ Returns a list of tokens installed on the given account. """ return self.get_object(action, kw, response)
[ "def", "get_tokens", "(", "self", ",", "action", ",", "response", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "get_object", "(", "action", ",", "kw", ",", "response", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/fps/connection.py#L305-L309
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Rect.GetLeft
(*args, **kwargs)
return _core_.Rect_GetLeft(*args, **kwargs)
GetLeft(self) -> int
GetLeft(self) -> int
[ "GetLeft", "(", "self", ")", "-", ">", "int" ]
def GetLeft(*args, **kwargs): """GetLeft(self) -> int""" return _core_.Rect_GetLeft(*args, **kwargs)
[ "def", "GetLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Rect_GetLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1353-L1355
liulei01/DRBox
b5c76e033c555c9009590ab384e1f7bd3c66c237
scripts/cpp_lint.py
python
CleanseRawStrings
(raw_lines)
return lines_without_raw_strings
Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings.
Removes C++11 raw strings from lines.
[ "Removes", "C", "++", "11", "raw", "strings", "from", "lines", "." ]
def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '' else: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if matched: delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings
[ "def", "CleanseRawStrings", "(", "raw_lines", ")", ":", "delimiter", "=", "None", "lines_without_raw_strings", "=", "[", "]", "for", "line", "in", "raw_lines", ":", "if", "delimiter", ":", "# Inside a raw string, look for the end", "end", "=", "line", ".", "find",...
https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/scripts/cpp_lint.py#L1062-L1120
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
support/cpplint.py
python
_IncludeState.IsInAlphabeticalOrder
(self, clean_lines, linenum, header_path)
return True
Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order.
Check if a header is in alphabetical order with the previous header.
[ "Check", "if", "a", "header", "is", "in", "alphabetical", "order", "with", "the", "previous", "header", "." ]
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): return False return True
[ "def", "IsInAlphabeticalOrder", "(", "self", ",", "clean_lines", ",", "linenum", ",", "header_path", ")", ":", "# If previous section is different from current section, _last_header will", "# be reset to empty string, so it's always less than current header.", "#", "# If previous line ...
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L792-L811
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/_max_len_seq.py
python
max_len_seq
(nbits, state=None, length=None, taps=None)
return seq, state
Maximum length sequence (MLS) generator. Parameters ---------- nbits : int Number of bits to use. Length of the resulting sequence will be ``(2**nbits) - 1``. Note that generating long sequences (e.g., greater than ``nbits == 16``) can take a long time. state : array_like, optional If array, must be of length ``nbits``, and will be cast to binary (bool) representation. If None, a seed of ones will be used, producing a repeatable representation. If ``state`` is all zeros, an error is raised as this is invalid. Default: None. length : int, optional Number of samples to compute. If None, the entire length ``(2**nbits) - 1`` is computed. taps : array_like, optional Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence). If None, taps will be automatically selected (for up to ``nbits == 32``). Returns ------- seq : array Resulting MLS sequence of 0's and 1's. state : array The final state of the shift register. Notes ----- The algorithm for MLS generation is generically described in: https://en.wikipedia.org/wiki/Maximum_length_sequence The default values for taps are specifically taken from the first option listed for each value of ``nbits`` in: http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm .. versionadded:: 0.15.0 Examples -------- MLS uses binary convention: >>> from scipy.signal import max_len_seq >>> max_len_seq(4)[0] array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8) MLS has a white spectrum (except for DC): >>> import matplotlib.pyplot as plt >>> from numpy.fft import fft, ifft, fftshift, fftfreq >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1 >>> spec = fft(seq) >>> N = len(seq) >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-') >>> plt.margins(0.1, 0.1) >>> plt.grid(True) >>> plt.show() Circular autocorrelation of MLS is an impulse: >>> acorrcirc = ifft(spec * np.conj(spec)).real >>> plt.figure() >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-') >>> plt.margins(0.1, 0.1) >>> plt.grid(True) >>> plt.show() Linear autocorrelation of MLS is approximately an impulse: >>> acorr = np.correlate(seq, seq, 'full') >>> plt.figure() >>> plt.plot(np.arange(-N+1, N), acorr, '.-') >>> plt.margins(0.1, 0.1) >>> plt.grid(True) >>> plt.show()
Maximum length sequence (MLS) generator.
[ "Maximum", "length", "sequence", "(", "MLS", ")", "generator", "." ]
def max_len_seq(nbits, state=None, length=None, taps=None): """ Maximum length sequence (MLS) generator. Parameters ---------- nbits : int Number of bits to use. Length of the resulting sequence will be ``(2**nbits) - 1``. Note that generating long sequences (e.g., greater than ``nbits == 16``) can take a long time. state : array_like, optional If array, must be of length ``nbits``, and will be cast to binary (bool) representation. If None, a seed of ones will be used, producing a repeatable representation. If ``state`` is all zeros, an error is raised as this is invalid. Default: None. length : int, optional Number of samples to compute. If None, the entire length ``(2**nbits) - 1`` is computed. taps : array_like, optional Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence). If None, taps will be automatically selected (for up to ``nbits == 32``). Returns ------- seq : array Resulting MLS sequence of 0's and 1's. state : array The final state of the shift register. Notes ----- The algorithm for MLS generation is generically described in: https://en.wikipedia.org/wiki/Maximum_length_sequence The default values for taps are specifically taken from the first option listed for each value of ``nbits`` in: http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm .. versionadded:: 0.15.0 Examples -------- MLS uses binary convention: >>> from scipy.signal import max_len_seq >>> max_len_seq(4)[0] array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8) MLS has a white spectrum (except for DC): >>> import matplotlib.pyplot as plt >>> from numpy.fft import fft, ifft, fftshift, fftfreq >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1 >>> spec = fft(seq) >>> N = len(seq) >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-') >>> plt.margins(0.1, 0.1) >>> plt.grid(True) >>> plt.show() Circular autocorrelation of MLS is an impulse: >>> acorrcirc = ifft(spec * np.conj(spec)).real >>> plt.figure() >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-') >>> plt.margins(0.1, 0.1) >>> plt.grid(True) >>> plt.show() Linear autocorrelation of MLS is approximately an impulse: >>> acorr = np.correlate(seq, seq, 'full') >>> plt.figure() >>> plt.plot(np.arange(-N+1, N), acorr, '.-') >>> plt.margins(0.1, 0.1) >>> plt.grid(True) >>> plt.show() """ if taps is None: if nbits not in _mls_taps: known_taps = np.array(list(_mls_taps.keys())) raise ValueError('nbits must be between %s and %s if taps is None' % (known_taps.min(), known_taps.max())) taps = np.array(_mls_taps[nbits], np.intp) else: taps = np.unique(np.array(taps, np.intp))[::-1] if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1: raise ValueError('taps must be non-empty with values between ' 'zero and nbits (inclusive)') taps = np.ascontiguousarray(taps) # needed for Cython n_max = (2**nbits) - 1 if length is None: length = n_max else: length = int(length) if length < 0: raise ValueError('length must be greater than or equal to 0') # We use int8 instead of bool here because numpy arrays of bools # don't seem to work nicely with Cython if state is None: state = np.ones(nbits, dtype=np.int8, order='c') else: # makes a copy if need be, ensuring it's 0's and 1's state = np.array(state, dtype=bool, order='c').astype(np.int8) if state.ndim != 1 or state.size != nbits: raise ValueError('state must be a 1-dimensional array of size nbits') if np.all(state == 0): raise ValueError('state must not be all zeros') seq = np.empty(length, dtype=np.int8, order='c') state = _max_len_seq_inner(taps, state, nbits, length, seq) return seq, state
[ "def", "max_len_seq", "(", "nbits", ",", "state", "=", "None", ",", "length", "=", "None", ",", "taps", "=", "None", ")", ":", "if", "taps", "is", "None", ":", "if", "nbits", "not", "in", "_mls_taps", ":", "known_taps", "=", "np", ".", "array", "("...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/_max_len_seq.py#L22-L137
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
python/artm/artm_model.py
python
ARTM.topic_names
(self)
return self._topic_names
:Description: Gets or sets the list of topic names of the model. :Note: * Setting topic name allows you to put new labels on the existing topics. To add, remove or reorder topics use ARTM.reshape_topics() method. * In ARTM topic names are used just as string identifiers, which give a unique name to each column of the phi matrix. Typically you want to set topic names as something like "topic0", "topic1", etc. Later operations like get_phi() allow you to specify which topics you need to retrieve. Most regularizers allow you to limit the set of topics they act upon. If you configure a rich set of regularizers it is important design your topic names according to how they are regularizerd. For example, you may use names obj0, obj1, ..., objN for *objective* topics (those where you enable sparsity regularizers), and back0, back1, ..., backM for *background* topics (those where you enable smoothing regularizers).
:Description: Gets or sets the list of topic names of the model.
[ ":", "Description", ":", "Gets", "or", "sets", "the", "list", "of", "topic", "names", "of", "the", "model", "." ]
def topic_names(self): """ :Description: Gets or sets the list of topic names of the model. :Note: * Setting topic name allows you to put new labels on the existing topics. To add, remove or reorder topics use ARTM.reshape_topics() method. * In ARTM topic names are used just as string identifiers, which give a unique name to each column of the phi matrix. Typically you want to set topic names as something like "topic0", "topic1", etc. Later operations like get_phi() allow you to specify which topics you need to retrieve. Most regularizers allow you to limit the set of topics they act upon. If you configure a rich set of regularizers it is important design your topic names according to how they are regularizerd. For example, you may use names obj0, obj1, ..., objN for *objective* topics (those where you enable sparsity regularizers), and back0, back1, ..., backM for *background* topics (those where you enable smoothing regularizers). """ return self._topic_names
[ "def", "topic_names", "(", "self", ")", ":", "return", "self", ".", "_topic_names" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/python/artm/artm_model.py#L361-L380
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
Viewport.__init__
(self)
__init__(Viewport self) -> Viewport
__init__(Viewport self) -> Viewport
[ "__init__", "(", "Viewport", "self", ")", "-", ">", "Viewport" ]
def __init__(self): """ __init__(Viewport self) -> Viewport """ this = _robotsim.new_Viewport() try: self.this.append(this) except Exception: self.this = this
[ "def", "__init__", "(", "self", ")", ":", "this", "=", "_robotsim", ".", "new_Viewport", "(", ")", "try", ":", "self", ".", "this", ".", "append", "(", "this", ")", "except", "Exception", ":", "self", ".", "this", "=", "this" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L2945-L2956
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/lib/auth_digest.py
python
HttpDigestAuthorization.is_nonce_stale
(self, max_age_seconds=600)
return True
Returns True if a validated nonce is stale. The nonce contains a timestamp in plaintext and also a secure hash of the timestamp. You should first validate the nonce to ensure the plaintext timestamp is not spoofed.
Returns True if a validated nonce is stale. The nonce contains a timestamp in plaintext and also a secure hash of the timestamp. You should first validate the nonce to ensure the plaintext timestamp is not spoofed.
[ "Returns", "True", "if", "a", "validated", "nonce", "is", "stale", ".", "The", "nonce", "contains", "a", "timestamp", "in", "plaintext", "and", "also", "a", "secure", "hash", "of", "the", "timestamp", ".", "You", "should", "first", "validate", "the", "nonc...
def is_nonce_stale(self, max_age_seconds=600): """Returns True if a validated nonce is stale. The nonce contains a timestamp in plaintext and also a secure hash of the timestamp. You should first validate the nonce to ensure the plaintext timestamp is not spoofed. """ try: timestamp, hashpart = self.nonce.split(':', 1) if int(timestamp) + max_age_seconds > int(time.time()): return False except ValueError: # int() error pass if self.debug: TRACE("nonce is stale") return True
[ "def", "is_nonce_stale", "(", "self", ",", "max_age_seconds", "=", "600", ")", ":", "try", ":", "timestamp", ",", "hashpart", "=", "self", ".", "nonce", ".", "split", "(", "':'", ",", "1", ")", "if", "int", "(", "timestamp", ")", "+", "max_age_seconds"...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/auth_digest.py#L212-L225
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/split-bst.py
python
Solution.splitBST
(self, root, V)
:type root: TreeNode :type V: int :rtype: List[TreeNode]
:type root: TreeNode :type V: int :rtype: List[TreeNode]
[ ":", "type", "root", ":", "TreeNode", ":", "type", "V", ":", "int", ":", "rtype", ":", "List", "[", "TreeNode", "]" ]
def splitBST(self, root, V): """ :type root: TreeNode :type V: int :rtype: List[TreeNode] """ if not root: return None, None elif root.val <= V: result = self.splitBST(root.right, V) root.right = result[0] return root, result[1] else: result = self.splitBST(root.left, V) root.left = result[1] return result[0], root
[ "def", "splitBST", "(", "self", ",", "root", ",", "V", ")", ":", "if", "not", "root", ":", "return", "None", ",", "None", "elif", "root", ".", "val", "<=", "V", ":", "result", "=", "self", ".", "splitBST", "(", "root", ".", "right", ",", "V", "...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/split-bst.py#L5-L20
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Action.py
python
ListAction.get_presig
(self, target, source, env)
return "".join([x.get_contents(target, source, env) for x in self.list])
Return the signature contents of this action list. Simple concatenation of the signatures of the elements.
Return the signature contents of this action list.
[ "Return", "the", "signature", "contents", "of", "this", "action", "list", "." ]
def get_presig(self, target, source, env): """Return the signature contents of this action list. Simple concatenation of the signatures of the elements. """ return "".join([x.get_contents(target, source, env) for x in self.list])
[ "def", "get_presig", "(", "self", ",", "target", ",", "source", ",", "env", ")", ":", "return", "\"\"", ".", "join", "(", "[", "x", ".", "get_contents", "(", "target", ",", "source", ",", "env", ")", "for", "x", "in", "self", ".", "list", "]", ")...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Action.py#L1124-L1129
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/stp/rc.py
python
GameInfo.is_setup
(self)
return self.state == GameState.SETUP
:return: True if the field is setting up for a penalty kick or kickoff.
:return: True if the field is setting up for a penalty kick or kickoff.
[ ":", "return", ":", "True", "if", "the", "field", "is", "setting", "up", "for", "a", "penalty", "kick", "or", "kickoff", "." ]
def is_setup(self) -> bool: """ :return: True if the field is setting up for a penalty kick or kickoff. """ return self.state == GameState.SETUP
[ "def", "is_setup", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "state", "==", "GameState", ".", "SETUP" ]
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/rc.py#L568-L572
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/shortcuteditor.py
python
ListShortcut.BuildImageList
(self, shortcut=None, index=None)
return index
Recursively builds the :class:`ListShortcut` image list based on the bitmaps in the :class:`Shortcut` hierarchy. :param `shortcut`: an instance of :class:`Shortcut`. If ``None``, it is defaulted to `self.manager` to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously); :param integer `index`: the current image index inside the :class:`ListShortcut` own :class:`ImageList`.
Recursively builds the :class:`ListShortcut` image list based on the bitmaps in the :class:`Shortcut` hierarchy.
[ "Recursively", "builds", "the", ":", "class", ":", "ListShortcut", "image", "list", "based", "on", "the", "bitmaps", "in", "the", ":", "class", ":", "Shortcut", "hierarchy", "." ]
def BuildImageList(self, shortcut=None, index=None): """ Recursively builds the :class:`ListShortcut` image list based on the bitmaps in the :class:`Shortcut` hierarchy. :param `shortcut`: an instance of :class:`Shortcut`. If ``None``, it is defaulted to `self.manager` to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously); :param integer `index`: the current image index inside the :class:`ListShortcut` own :class:`ImageList`. """ if shortcut is None: shortcut = self.manager index = 0 for child in shortcut.children: bitmap = child.GetBitmap() if bitmap.IsOk(): self.imageList.Add(bitmap) child.imageIndex = index index += 1 index = self.BuildImageList(child, index) return index
[ "def", "BuildImageList", "(", "self", ",", "shortcut", "=", "None", ",", "index", "=", "None", ")", ":", "if", "shortcut", "is", "None", ":", "shortcut", "=", "self", ".", "manager", "index", "=", "0", "for", "child", "in", "shortcut", ".", "children",...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shortcuteditor.py#L1797-L1822
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/assembly_graph.py
python
AssemblyGraph.lead_exclusively_from
(self, segment_num_1, segment_num_2)
return self.reverse_links[segment_num_1] == [segment_num_2]
Returns whether the first segment has inputs from and only from the second segment.
Returns whether the first segment has inputs from and only from the second segment.
[ "Returns", "whether", "the", "first", "segment", "has", "inputs", "from", "and", "only", "from", "the", "second", "segment", "." ]
def lead_exclusively_from(self, segment_num_1, segment_num_2): """ Returns whether the first segment has inputs from and only from the second segment. """ if segment_num_1 not in self.reverse_links: return False return self.reverse_links[segment_num_1] == [segment_num_2]
[ "def", "lead_exclusively_from", "(", "self", ",", "segment_num_1", ",", "segment_num_2", ")", ":", "if", "segment_num_1", "not", "in", "self", ".", "reverse_links", ":", "return", "False", "return", "self", ".", "reverse_links", "[", "segment_num_1", "]", "==", ...
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph.py#L799-L805
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
openr/py/openr/cli/utils/utils.py
python
print_spt_infos
( spt_infos: kv_store_types.SptInfos, roots: List[str], area: Optional[str] = None, )
print spanning tree information
print spanning tree information
[ "print", "spanning", "tree", "information" ]
def print_spt_infos( spt_infos: kv_store_types.SptInfos, roots: List[str], area: Optional[str] = None, ) -> None: """ print spanning tree information """ output = [] area = f'Area "{area}": ' if area is not None else "" # step0. print current flooding root id print(f"\n>{area}Current Flood On Root-Id: {spt_infos.floodRootId}") # step1. print neighbor level counters caption = "Neighbor DUAL Counters" column_labels = ["Neighbor", "Pkt(Tx/Rx)", "Msg(Tx/Rx)", "Is Flooding Peer"] neighbor_counters = spt_infos.counters.neighborCounters rows = [] for nb, counters in neighbor_counters.items(): state = click.style("No") if nb in spt_infos.floodPeers: state = click.style("Yes", fg="green") rows.append( [ nb, "{}/{}".format(counters.pktSent, counters.pktRecv), "{}/{}".format(counters.msgSent, counters.msgRecv), state, ] ) seg = printing.render_horizontal_table(rows, column_labels, tablefmt="plain") output.append([caption, seg]) # step2. print root level counters root_counters = spt_infos.counters.rootCounters column_labels = [ "Neighbor", "Query(Tx/Rx)", "Reply(Tx/Rx)", "Update(Tx/Rx)", "Total(Tx/Rx)", "Role", ] for root, info in spt_infos.infos.items(): if roots is not None and root not in roots: continue if info.passive: state = click.style("PASSIVE", fg="green") else: state = click.style("ACTIVE", fg="red") cap = "root@{}[{}]: parent: {}, cost: {}, ({}) children".format( root, state, info.parent, info.cost, len(info.children) ) rows = [] # pyre-fixme[16]: `Optional` has no attribute `items`. for nb, counters in root_counters.get(root).items(): role = "-" if nb == info.parent: role = "Parent" elif nb in info.children: role = "Child" if counters.querySent > counters.replyRecv: # active-state: I'm expecting receving reply from this neighbor # show it as red nb = click.style(nb, fg="red") rows.append( [ nb, "{}/{}".format(counters.querySent, counters.queryRecv), "{}/{}".format(counters.replySent, counters.replyRecv), "{}/{}".format(counters.updateSent, counters.updateRecv), "{}/{}".format(counters.totalSent, counters.totalRecv), role, ] ) seg = printing.render_horizontal_table(rows, column_labels, tablefmt="plain") output.append([cap, seg]) print(printing.render_vertical_table(output))
[ "def", "print_spt_infos", "(", "spt_infos", ":", "kv_store_types", ".", "SptInfos", ",", "roots", ":", "List", "[", "str", "]", ",", "area", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "None", ":", "output", "=", "[", "]", "area", ...
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/utils/utils.py#L1790-L1869
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.AppendPostbuildVariable
(self, variables, spec, output, binary, is_command_start=False)
Adds a 'postbuild' variable if there is a postbuild for |output|.
Adds a 'postbuild' variable if there is a postbuild for |output|.
[ "Adds", "a", "postbuild", "variable", "if", "there", "is", "a", "postbuild", "for", "|output|", "." ]
def AppendPostbuildVariable(self, variables, spec, output, binary, is_command_start=False): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(('postbuilds', postbuild))
[ "def", "AppendPostbuildVariable", "(", "self", ",", "variables", ",", "spec", ",", "output", ",", "binary", ",", "is_command_start", "=", "False", ")", ":", "postbuild", "=", "self", ".", "GetPostbuildCommand", "(", "spec", ",", "output", ",", "binary", ",",...
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/ninja.py#L1383-L1388
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/metrics/roc.py
python
ROC.clear
(self)
Clear the internal evaluation result.
Clear the internal evaluation result.
[ "Clear", "the", "internal", "evaluation", "result", "." ]
def clear(self): """Clear the internal evaluation result.""" self.y_pred = 0 self.y = 0 self.sample_weights = None self._is_update = False
[ "def", "clear", "(", "self", ")", ":", "self", ".", "y_pred", "=", "0", "self", ".", "y", "=", "0", "self", ".", "sample_weights", "=", "None", "self", ".", "_is_update", "=", "False" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/metrics/roc.py#L77-L82
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
TextAreaBase.SetModified
(*args, **kwargs)
return _core_.TextAreaBase_SetModified(*args, **kwargs)
SetModified(self, bool modified)
SetModified(self, bool modified)
[ "SetModified", "(", "self", "bool", "modified", ")" ]
def SetModified(*args, **kwargs): """SetModified(self, bool modified)""" return _core_.TextAreaBase_SetModified(*args, **kwargs)
[ "def", "SetModified", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextAreaBase_SetModified", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13412-L13414
cinder/Cinder
e83f5bb9c01a63eec20168d02953a0879e5100f7
src/freetype/tools/docmaker/utils.py
python
make_file_list
( args = None )
return file_list
Build a list of input files from command-line arguments.
Build a list of input files from command-line arguments.
[ "Build", "a", "list", "of", "input", "files", "from", "command", "-", "line", "arguments", "." ]
def make_file_list( args = None ): """Build a list of input files from command-line arguments.""" file_list = [] # sys.stderr.write( repr( sys.argv[1 :] ) + '\n' ) if not args: args = sys.argv[1:] for pathname in args: if string.find( pathname, '*' ) >= 0: newpath = glob.glob( pathname ) newpath.sort() # sort files -- this is important because # of the order of files else: newpath = [pathname] file_list.extend( newpath ) if len( file_list ) == 0: file_list = None else: # now filter the file list to remove non-existing ones file_list = filter( file_exists, file_list ) return file_list
[ "def", "make_file_list", "(", "args", "=", "None", ")", ":", "file_list", "=", "[", "]", "# sys.stderr.write( repr( sys.argv[1 :] ) + '\\n' )", "if", "not", "args", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "for", "pathname", "in", "args", ...
https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/src/freetype/tools/docmaker/utils.py#L101-L125
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/console/ironpython_console.py
python
Console.rectangle
(self, rect, attr=None, fill=' ')
Fill Rectangle.
Fill Rectangle.
[ "Fill", "Rectangle", "." ]
def rectangle(self, rect, attr=None, fill=' '): '''Fill Rectangle.''' pass oldtop=self.WindowTop oldpos=self.pos() #raise NotImplementedError x0, y0, x1, y1 = rect if attr is None: attr = self.attr if fill: rowfill=fill[:1]*abs(x1-x0) else: rowfill=' '*abs(x1-x0) for y in range(y0, y1): System.Console.SetCursorPosition(x0,y) self.write_color(rowfill,attr) self.pos(*oldpos)
[ "def", "rectangle", "(", "self", ",", "rect", ",", "attr", "=", "None", ",", "fill", "=", "' '", ")", ":", "pass", "oldtop", "=", "self", ".", "WindowTop", "oldpos", "=", "self", ".", "pos", "(", ")", "#raise NotImplementedError", "x0", ",", "y0", ",...
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/console/ironpython_console.py#L272-L288
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/context.py
python
NRTContext.incref
(self, builder, typ, value)
Recursively incref the given *value* and its members.
Recursively incref the given *value* and its members.
[ "Recursively", "incref", "the", "given", "*", "value", "*", "and", "its", "members", "." ]
def incref(self, builder, typ, value): """ Recursively incref the given *value* and its members. """ self._call_incref_decref(builder, typ, value, "NRT_incref")
[ "def", "incref", "(", "self", ",", "builder", ",", "typ", ",", "value", ")", ":", "self", ".", "_call_incref_decref", "(", "builder", ",", "typ", ",", "value", ",", "\"NRT_incref\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/context.py#L216-L220
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
panreas_hnn/hed-globalweight/scripts/cpp_lint.py
python
FileInfo.NoExtension
(self)
return '/'.join(self.Split()[0:2])
File has no source file extension.
File has no source file extension.
[ "File", "has", "no", "source", "file", "extension", "." ]
def NoExtension(self): """File has no source file extension.""" return '/'.join(self.Split()[0:2])
[ "def", "NoExtension", "(", "self", ")", ":", "return", "'/'", ".", "join", "(", "self", ".", "Split", "(", ")", "[", "0", ":", "2", "]", ")" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/scripts/cpp_lint.py#L952-L954
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
BookCtrlBase.GetClassDefaultAttributes
(*args, **kwargs)
return _core_.BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _core_.BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BookCtrlBase_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L13654-L13669
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/sun_tool.py
python
SunTool._CommandifyName
(self, name_string)
return name_string.title().replace('-', '')
Transforms a tool name like copy-info-plist to CopyInfoPlist
Transforms a tool name like copy-info-plist to CopyInfoPlist
[ "Transforms", "a", "tool", "name", "like", "copy", "-", "info", "-", "plist", "to", "CopyInfoPlist" ]
def _CommandifyName(self, name_string): """Transforms a tool name like copy-info-plist to CopyInfoPlist""" return name_string.title().replace('-', '')
[ "def", "_CommandifyName", "(", "self", ",", "name_string", ")", ":", "return", "name_string", ".", "title", "(", ")", ".", "replace", "(", "'-'", ",", "''", ")" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/sun_tool.py#L33-L35
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/boosted_trees_ops.py
python
TreeEnsemble.serialize
(self)
return gen_boosted_trees_ops.boosted_trees_serialize_ensemble( self.resource_handle)
Serializes the ensemble into proto and returns the serialized proto. Returns: stamp_token: int64 scalar Tensor to denote the stamp of the resource. serialized_proto: string scalar Tensor of the serialized proto.
Serializes the ensemble into proto and returns the serialized proto.
[ "Serializes", "the", "ensemble", "into", "proto", "and", "returns", "the", "serialized", "proto", "." ]
def serialize(self): """Serializes the ensemble into proto and returns the serialized proto. Returns: stamp_token: int64 scalar Tensor to denote the stamp of the resource. serialized_proto: string scalar Tensor of the serialized proto. """ return gen_boosted_trees_ops.boosted_trees_serialize_ensemble( self.resource_handle)
[ "def", "serialize", "(", "self", ")", ":", "return", "gen_boosted_trees_ops", ".", "boosted_trees_serialize_ensemble", "(", "self", ".", "resource_handle", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/boosted_trees_ops.py#L282-L290
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/package_index.py
python
distros_for_location
(location, basename, metadata=None)
return []
Yield egg or source distribution objects based on basename
Yield egg or source distribution objects based on basename
[ "Yield", "egg", "or", "source", "distribution", "objects", "based", "on", "basename" ]
def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): basename = basename[:-4] # strip the .zip if basename.endswith('.egg') and '-' in basename: # only one, unambiguous interpretation return [Distribution.from_location(location, basename, metadata)] if basename.endswith('.exe'): win_base, py_ver, platform = parse_bdist_wininst(basename) if win_base is not None: return interpret_distro_name( location, win_base, metadata, py_ver, BINARY_DIST, platform ) # Try source distro extensions (.zip, .tgz, etc.) # for ext in EXTENSIONS: if basename.endswith(ext): basename = basename[:-len(ext)] return interpret_distro_name(location, basename, metadata) return []
[ "def", "distros_for_location", "(", "location", ",", "basename", ",", "metadata", "=", "None", ")", ":", "if", "basename", ".", "endswith", "(", "'.egg.zip'", ")", ":", "basename", "=", "basename", "[", ":", "-", "4", "]", "# strip the .zip", "if", "basena...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/package_index.py#L88-L107
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/postgres_search.py
python
PostgresDatabase.Search
(self, search_term, start_template, end_template, placemark_)
return content
Search all tables and create results using templates.
Search all tables and create results using templates.
[ "Search", "all", "tables", "and", "create", "results", "using", "templates", "." ]
def Search(self, search_term, start_template, end_template, placemark_): """Search all tables and create results using templates.""" content = start_template % search_term for table_name in self.search_tables_: content += self.SearchTable(table_name, search_term, placemark_) content += end_template return content
[ "def", "Search", "(", "self", ",", "search_term", ",", "start_template", ",", "end_template", ",", "placemark_", ")", ":", "content", "=", "start_template", "%", "search_term", "for", "table_name", "in", "self", ".", "search_tables_", ":", "content", "+=", "se...
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/postgres_search.py#L212-L220
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/stringold.py
python
capwords
(s, sep=None)
return join(map(capitalize, s.split(sep)), sep or ' ')
capwords(s, [sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. Note that this replaces runs of whitespace characters by a single space.
capwords(s, [sep]) -> string
[ "capwords", "(", "s", "[", "sep", "]", ")", "-", ">", "string" ]
def capwords(s, sep=None): """capwords(s, [sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. Note that this replaces runs of whitespace characters by a single space. """ return join(map(capitalize, s.split(sep)), sep or ' ')
[ "def", "capwords", "(", "s", ",", "sep", "=", "None", ")", ":", "return", "join", "(", "map", "(", "capitalize", ",", "s", ".", "split", "(", "sep", ")", ")", ",", "sep", "or", "' '", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/stringold.py#L369-L378
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
libcxx/utils/libcxx/sym_check/extract.py
python
NMExtractor.extract
(self, lib)
return util.read_syms_from_list(tmp_list)
Extract symbols from a library and return the results as a dict of parsed symbols.
Extract symbols from a library and return the results as a dict of parsed symbols.
[ "Extract", "symbols", "from", "a", "library", "and", "return", "the", "results", "as", "a", "dict", "of", "parsed", "symbols", "." ]
def extract(self, lib): """ Extract symbols from a library and return the results as a dict of parsed symbols. """ cmd = [self.nm_exe] + self.flags + [lib] out, _, exit_code = libcxx.util.executeCommandVerbose(cmd) if exit_code != 0: raise RuntimeError('Failed to run %s on %s' % (self.nm_exe, lib)) fmt_syms = (self._extract_sym(l) for l in out.splitlines() if l.strip()) # Cast symbol to string. final_syms = (repr(s) for s in fmt_syms if self._want_sym(s)) # Make unique and sort strings. tmp_list = list(sorted(set(final_syms))) # Cast string back to symbol. return util.read_syms_from_list(tmp_list)
[ "def", "extract", "(", "self", ",", "lib", ")", ":", "cmd", "=", "[", "self", ".", "nm_exe", "]", "+", "self", ".", "flags", "+", "[", "lib", "]", "out", ",", "_", ",", "exit_code", "=", "libcxx", ".", "util", ".", "executeCommandVerbose", "(", "...
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/libcxx/utils/libcxx/sym_check/extract.py#L48-L64
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/cpu.py
python
CPUContext.build_list
(self, builder, list_type, items)
return listobj.build_list(self, builder, list_type, items)
Build a list from the Numba *list_type* and its initial *items*.
Build a list from the Numba *list_type* and its initial *items*.
[ "Build", "a", "list", "from", "the", "Numba", "*", "list_type", "*", "and", "its", "initial", "*", "items", "*", "." ]
def build_list(self, builder, list_type, items): """ Build a list from the Numba *list_type* and its initial *items*. """ return listobj.build_list(self, builder, list_type, items)
[ "def", "build_list", "(", "self", ",", "builder", ",", "list_type", ",", "items", ")", ":", "return", "listobj", ".", "build_list", "(", "self", ",", "builder", ",", "list_type", ",", "items", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/cpu.py#L125-L129
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load_v1_in_v2.py
python
_EagerSavedModelLoader._extract_signatures
(self, wrapped, meta_graph_def)
return signature_functions
Creates ConcreteFunctions for signatures in `meta_graph_def`.
Creates ConcreteFunctions for signatures in `meta_graph_def`.
[ "Creates", "ConcreteFunctions", "for", "signatures", "in", "meta_graph_def", "." ]
def _extract_signatures(self, wrapped, meta_graph_def): """Creates ConcreteFunctions for signatures in `meta_graph_def`.""" signature_functions = {} for signature_key, signature_def in meta_graph_def.signature_def.items(): if signature_def.inputs: input_names, input_specs = zip(*signature_def.inputs.items()) else: input_names = [] input_specs = [] # TODO(allenl): Support optional arguments feeds = [wrapped.graph.as_graph_element(inp.name) for inp in input_specs] fetches = {name: out for name, out in signature_def.outputs.items()} try: signature_fn = wrapped.prune(feeds=feeds, fetches=fetches) except lift_to_graph.UnliftableError as ex: # Mutate the exception to add a bit more detail. args = ex.args if not args: message = "" else: message = args[0] message = ( ("A SavedModel signature needs an input for each placeholder the " "signature's outputs use. An output for signature '{}' depends on " "a placeholder which is not an input (i.e. the placeholder is not " "fed a value).\n\n").format(signature_key) + message) ex.args = (message,) + args[1:] raise # pylint: disable=protected-access signature_fn._arg_keywords = input_names if len(input_names) == 1: # Allowing positional arguments does not create any ambiguity if there's # only one. signature_fn._num_positional_args = 1 else: signature_fn._num_positional_args = 0 # pylint: enable=protected-access signature_functions[signature_key] = signature_fn return signature_functions
[ "def", "_extract_signatures", "(", "self", ",", "wrapped", ",", "meta_graph_def", ")", ":", "signature_functions", "=", "{", "}", "for", "signature_key", ",", "signature_def", "in", "meta_graph_def", ".", "signature_def", ".", "items", "(", ")", ":", "if", "si...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load_v1_in_v2.py#L125-L164
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/locators.py
python
Locator.convert_url_to_download_info
(self, url, project_name)
return result
See if a URL is a candidate for a download URL for a project (the URL has typically been scraped from an HTML page). If it is, a dictionary is returned with keys "name", "version", "filename" and "url"; otherwise, None is returned.
See if a URL is a candidate for a download URL for a project (the URL has typically been scraped from an HTML page).
[ "See", "if", "a", "URL", "is", "a", "candidate", "for", "a", "download", "URL", "for", "a", "project", "(", "the", "URL", "has", "typically", "been", "scraped", "from", "an", "HTML", "page", ")", "." ]
def convert_url_to_download_info(self, url, project_name): """ See if a URL is a candidate for a download URL for a project (the URL has typically been scraped from an HTML page). If it is, a dictionary is returned with keys "name", "version", "filename" and "url"; otherwise, None is returned. """ def same_project(name1, name2): return normalize_name(name1) == normalize_name(name2) result = None scheme, netloc, path, params, query, frag = urlparse(url) if frag.lower().startswith('egg='): # pragma: no cover logger.debug('%s: version hint in fragment: %r', project_name, frag) m = HASHER_HASH.match(frag) if m: algo, digest = m.groups() else: algo, digest = None, None origpath = path if path and path[-1] == '/': # pragma: no cover path = path[:-1] if path.endswith('.whl'): try: wheel = Wheel(path) if not is_compatible(wheel, self.wheel_tags): logger.debug('Wheel not compatible: %s', path) else: if project_name is None: include = True else: include = same_project(wheel.name, project_name) if include: result = { 'name': wheel.name, 'version': wheel.version, 'filename': wheel.filename, 'url': urlunparse((scheme, netloc, origpath, params, query, '')), 'python-version': ', '.join( ['.'.join(list(v[2:])) for v in wheel.pyver]), } except Exception as e: # pragma: no cover logger.warning('invalid path for wheel: %s', path) elif not path.endswith(self.downloadable_extensions): # pragma: no cover logger.debug('Not downloadable: %s', path) else: # downloadable extension path = filename = posixpath.basename(path) for ext in self.downloadable_extensions: if path.endswith(ext): path = path[:-len(ext)] t = self.split_filename(path, project_name) if not t: # pragma: no cover logger.debug('No match for project/version: %s', path) else: name, version, pyver = t if not project_name or same_project(project_name, name): result = { 'name': name, 'version': version, 'filename': filename, 'url': urlunparse((scheme, netloc, origpath, params, query, '')), #'packagetype': 'sdist', } if pyver: # pragma: no cover result['python-version'] = pyver break if result and algo: result['%s_digest' % algo] = digest return result
[ "def", "convert_url_to_download_info", "(", "self", ",", "url", ",", "project_name", ")", ":", "def", "same_project", "(", "name1", ",", "name2", ")", ":", "return", "normalize_name", "(", "name1", ")", "==", "normalize_name", "(", "name2", ")", "result", "=...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/locators.py#L231-L303
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/summary/impl/gcs.py
python
Exists
(path)
Returns true if path exists.
Returns true if path exists.
[ "Returns", "true", "if", "path", "exists", "." ]
def Exists(path): """Returns true if path exists.""" try: ListDirectory(path) return True except subprocess.CalledProcessError: return False
[ "def", "Exists", "(", "path", ")", ":", "try", ":", "ListDirectory", "(", "path", ")", "return", "True", "except", "subprocess", ".", "CalledProcessError", ":", "return", "False" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/summary/impl/gcs.py#L104-L110
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/gem5/components/cachehierarchies/ruby/caches/abstract_directory.py
python
AbstractDirectory.connectQueues
(self, network)
Connect all of the queues for this controller.
Connect all of the queues for this controller.
[ "Connect", "all", "of", "the", "queues", "for", "this", "controller", "." ]
def connectQueues(self, network): """Connect all of the queues for this controller.""" raise NotImplementedError
[ "def", "connectQueues", "(", "self", ",", "network", ")", ":", "raise", "NotImplementedError" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/gem5/components/cachehierarchies/ruby/caches/abstract_directory.py#L49-L51
blakesmith/embedded
61d02c8feed34eff75fe64f29cc8997f1c480867
nome/hardware/KiBoM/KiBOM/component.py
python
Component.getField
(self, name, ignoreCase=True, libraryToo=True)
return ""
Return the value of a field named name. The component is first checked for the field, and then the components library part is checked for the field. If the field doesn't exist in either, an empty string is returned Keywords: name -- The name of the field to return the value for libraryToo -- look in the libpart's fields for the same name if not found in component itself
Return the value of a field named name. The component is first checked for the field, and then the components library part is checked for the field. If the field doesn't exist in either, an empty string is returned
[ "Return", "the", "value", "of", "a", "field", "named", "name", ".", "The", "component", "is", "first", "checked", "for", "the", "field", "and", "then", "the", "components", "library", "part", "is", "checked", "for", "the", "field", ".", "If", "the", "fie...
def getField(self, name, ignoreCase=True, libraryToo=True): """Return the value of a field named name. The component is first checked for the field, and then the components library part is checked for the field. If the field doesn't exist in either, an empty string is returned Keywords: name -- The name of the field to return the value for libraryToo -- look in the libpart's fields for the same name if not found in component itself """ #special fields fp = self.getFootprint().split(":") if name.lower() == ColumnList.COL_REFERENCE.lower(): return self.getRef().strip() elif name.lower() == ColumnList.COL_DESCRIPTION.lower(): return self.getDescription().strip() elif name.lower() == ColumnList.COL_DATASHEET.lower(): return self.getDatasheet().strip() # Footprint library is first element elif name.lower() == ColumnList.COL_FP_LIB.lower(): if len(fp) > 1: return fp[0].strip() else: return "" # explicit empty return elif name.lower() == ColumnList.COL_FP.lower(): if len(fp) > 1: return fp[1].strip() else: return "" # explicit empty return elif name.lower() == ColumnList.COL_VALUE.lower(): return self.getValue().strip() elif name.lower() == ColumnList.COL_PART.lower(): return self.getPartName().strip() elif name.lower() == ColumnList.COL_PART_LIB.lower(): return self.getLibName().strip() #other fields (case insensitive) for f in self.getFieldNames(): if f.lower() == name.lower(): field = self.element.get("field", "name", f) if field == "" and libraryToo: field = self.libpart.getField(f) return field.strip() #could not find a matching field return ""
[ "def", "getField", "(", "self", ",", "name", ",", "ignoreCase", "=", "True", ",", "libraryToo", "=", "True", ")", ":", "#special fields", "fp", "=", "self", ".", "getFootprint", "(", ")", ".", "split", "(", "\":\"", ")", "if", "name", ".", "lower", "...
https://github.com/blakesmith/embedded/blob/61d02c8feed34eff75fe64f29cc8997f1c480867/nome/hardware/KiBoM/KiBOM/component.py#L125-L183
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/peakmeter.py
python
PeakMeterCtrl.DrawVertBandInverted
(self, dc, rect)
Draws vertical bands inverted. :param `dc`: an instance of :class:`DC`; :param `rect`: the vertical bands client rectangle.
Draws vertical bands inverted.
[ "Draws", "vertical", "bands", "inverted", "." ]
def DrawVertBandInverted(self, dc, rect): """ Draws vertical bands inverted. :param `dc`: an instance of :class:`DC`; :param `rect`: the vertical bands client rectangle. """ vertBands = (self._ledBands > 1 and [self._ledBands] or [self._maxValue*BAND_PERCENT/100])[0] minVertLimit = self._minValue*vertBands/self._maxValue medVertLimit = self._medValue*vertBands/self._maxValue maxVertLimit = vertBands size = wx.Size(rect.width/self._numBands, rect.height/vertBands) rectBand = wx.RectPS(rect.GetTopLeft(), size) # Draw band from top? rectBand.OffsetXY(0, 0) xDecal = (self._numBands > 1 and [1] or [0])[0] yDecal = (self._ledBands > 1 and [1] or [0])[0] for horz in xrange(self._numBands): self._value = self._meterData[horz]._value vertLimit = self._value*vertBands/self._maxValue rectPrev = wx.Rect(*rectBand) for vert in xrange(vertBands): rectBand.Deflate(xDecal, 0) # Find colour based on range value colourRect = self._clrBackground if self._showGrid: colourRect = DarkenColour(self._clrBackground, GRID_INCREASEBY) # Draw grid line (level) bar if self._showGrid and (vert == minVertLimit or vert == (vertBands-1)): points = [wx.Point() for i in xrange(2)] points[0].x = rectBand.GetTopLeft().x - xDecal points[0].y = rectBand.GetTopLeft().y + (rectBand.height >> 1) points[1].x = rectBand.GetBottomRight().x + xDecal points[1].y = points[0].y dc.DrawLinePoint(points[0], points[1]) if vert < vertLimit: if InRange(vert, 0, minVertLimit-1): colourRect = self._clrNormal elif InRange(vert, minVertLimit, medVertLimit-1): colourRect = self._clrMedium elif InRange(vert, medVertLimit, maxVertLimit): colourRect = self._clrHigh dc.SetBrush(wx.Brush(colourRect)) dc.DrawRectangleRect(rectBand) rectBand.Inflate(xDecal, 0) rectBand.OffsetXY(0, size.y) # Draw falloff effect if self._showFalloff: oldPen = dc.GetPen() pen = wx.Pen(DarkenColour(self._clrBackground, FALL_INCREASEBY)) maxHeight = -size.y*vertBands points = [wx.Point() for i in xrange(2)] points[0].x = rectPrev.GetBottomLeft().x + xDecal points[0].y = rectPrev.GetTopRight().y - self._meterData[horz]._falloff*maxHeight/self._maxValue points[1].x = rectPrev.GetTopRight().x - xDecal points[1].y = points[0].y dc.SetPen(pen) dc.DrawLinePoint(points[0], points[1]) dc.SetPen(oldPen) # Move to Next Horizontal band rectBand.OffsetXY(size.x, -size.y*vertBands)
[ "def", "DrawVertBandInverted", "(", "self", ",", "dc", ",", "rect", ")", ":", "vertBands", "=", "(", "self", ".", "_ledBands", ">", "1", "and", "[", "self", ".", "_ledBands", "]", "or", "[", "self", ".", "_maxValue", "*", "BAND_PERCENT", "/", "100", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/peakmeter.py#L880-L957
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/http/client.py
python
HTTPResponse.geturl
(self)
return self.url
Return the real URL of the page. In some cases, the HTTP server redirects a client to another URL. The urlopen() function handles this transparently, but in some cases the caller needs to know which URL the client was redirected to. The geturl() method can be used to get at this redirected URL.
Return the real URL of the page.
[ "Return", "the", "real", "URL", "of", "the", "page", "." ]
def geturl(self): '''Return the real URL of the page. In some cases, the HTTP server redirects a client to another URL. The urlopen() function handles this transparently, but in some cases the caller needs to know which URL the client was redirected to. The geturl() method can be used to get at this redirected URL. ''' return self.url
[ "def", "geturl", "(", "self", ")", ":", "return", "self", ".", "url" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/http/client.py#L776-L786
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
modules/geochemistry/python/dbutils.py
python
secondarySpeciesContainingBasis
(db, sec_species_type, basis_species)
return [key for (key, value) in db[sec_species_type].items() if any(b in value['species'] for b in basis_species)]
Searches the database and returns all secondary species of given type containing at least one of the basis species
Searches the database and returns all secondary species of given type containing at least one of the basis species
[ "Searches", "the", "database", "and", "returns", "all", "secondary", "species", "of", "given", "type", "containing", "at", "least", "one", "of", "the", "basis", "species" ]
def secondarySpeciesContainingBasis(db, sec_species_type, basis_species): """ Searches the database and returns all secondary species of given type containing at least one of the basis species """ assert sec_species_type in db, "Specified secondary species type not in database" return [key for (key, value) in db[sec_species_type].items() if any(b in value['species'] for b in basis_species)]
[ "def", "secondarySpeciesContainingBasis", "(", "db", ",", "sec_species_type", ",", "basis_species", ")", ":", "assert", "sec_species_type", "in", "db", ",", "\"Specified secondary species type not in database\"", "return", "[", "key", "for", "(", "key", ",", "value", ...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/modules/geochemistry/python/dbutils.py#L11-L18
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hypertreelist.py
python
HyperTreeList.InsertColumn
(self, before, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, edit=False)
Inserts a column to the :class:`HyperTreeList` at the position specified by `before`. :param `before`: the index at which we wish to insert the new column; :param `text`: the column text label; :param `width`: the column width in pixels; :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``, ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``; :param `image`: an index within the normal image list assigned to :class:`HyperTreeList` specifying the image to use for the column; :param `shown`: ``True`` to show the column, ``False`` to hide it; :param `colour`: a valid :class:`Colour`, representing the text foreground colour for the column; :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
Inserts a column to the :class:`HyperTreeList` at the position specified by `before`.
[ "Inserts", "a", "column", "to", "the", ":", "class", ":", "HyperTreeList", "at", "the", "position", "specified", "by", "before", "." ]
def InsertColumn(self, before, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, edit=False): """ Inserts a column to the :class:`HyperTreeList` at the position specified by `before`. :param `before`: the index at which we wish to insert the new column; :param `text`: the column text label; :param `width`: the column width in pixels; :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``, ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``; :param `image`: an index within the normal image list assigned to :class:`HyperTreeList` specifying the image to use for the column; :param `shown`: ``True`` to show the column, ``False`` to hide it; :param `colour`: a valid :class:`Colour`, representing the text foreground colour for the column; :param `edit`: ``True`` to set the column as editable, ``False`` otherwise. """ self._header_win.InsertColumn(before, text, width, flag, image, shown, colour, edit) self._header_win.Refresh()
[ "def", "InsertColumn", "(", "self", ",", "before", ",", "text", ",", "width", "=", "_DEFAULT_COL_WIDTH", ",", "flag", "=", "wx", ".", "ALIGN_LEFT", ",", "image", "=", "-", "1", ",", "shown", "=", "True", ",", "colour", "=", "None", ",", "edit", "=", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L4502-L4524
vicaya/hypertable
e7386f799c238c109ae47973417c2a2c7f750825
src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py
python
Client.next_row_as_arrays
(self, scanner)
return self.recv_next_row_as_arrays()
Alternative interface using array as cell Parameters: - scanner
Alternative interface using array as cell Parameters: - scanner
[ "Alternative", "interface", "using", "array", "as", "cell", "Parameters", ":", "-", "scanner" ]
def next_row_as_arrays(self, scanner): """ Alternative interface using array as cell Parameters: - scanner """ self.send_next_row_as_arrays(scanner) return self.recv_next_row_as_arrays()
[ "def", "next_row_as_arrays", "(", "self", ",", "scanner", ")", ":", "self", ".", "send_next_row_as_arrays", "(", "scanner", ")", "return", "self", ".", "recv_next_row_as_arrays", "(", ")" ]
https://github.com/vicaya/hypertable/blob/e7386f799c238c109ae47973417c2a2c7f750825/src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py#L546-L554
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/compiler/xla/python/xla_client.py
python
register_custom_call_target
(name, fn, platform='cpu')
Registers a custom call target. Args: name: bytes containing the name of the function. fn: a PyCapsule object containing the function pointer. platform: the target platform.
Registers a custom call target.
[ "Registers", "a", "custom", "call", "target", "." ]
def register_custom_call_target(name, fn, platform='cpu'): """Registers a custom call target. Args: name: bytes containing the name of the function. fn: a PyCapsule object containing the function pointer. platform: the target platform. """ # To support AMD GPUs, we need to have xla_platform_names["gpu"] == "ROCM" # Since that is hardcoded to CUDA, we are using the following as workaround. _xla.register_custom_call_target(name, fn, xla_platform_names.get(platform, platform))
[ "def", "register_custom_call_target", "(", "name", ",", "fn", ",", "platform", "=", "'cpu'", ")", ":", "# To support AMD GPUs, we need to have xla_platform_names[\"gpu\"] == \"ROCM\"", "# Since that is hardcoded to CUDA, we are using the following as workaround.", "_xla", ".", "regis...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/compiler/xla/python/xla_client.py#L387-L398
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp3/ctptd.py
python
CtpTd.reqQryOrder
(self)
return self._requestId
查询委托
查询委托
[ "查询委托" ]
def reqQryOrder(self): """查询委托""" qryOrderField = td.QryOrderField() qryOrderField.brokerID = self._brokerID qryOrderField.investorID = self._userID # qryOrderField.instrumentID = "" self._requestId += 1 super(CtpTd, self).reqQryOrder(qryOrderField, self._requestId) return self._requestId
[ "def", "reqQryOrder", "(", "self", ")", ":", "qryOrderField", "=", "td", ".", "QryOrderField", "(", ")", "qryOrderField", ".", "brokerID", "=", "self", ".", "_brokerID", "qryOrderField", ".", "investorID", "=", "self", ".", "_userID", "# qryOrderField.instrument...
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp3/ctptd.py#L609-L617
OpenXRay/xray-15
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/scripted/splitUVCmd.py
python
splitUV.__pruneUVs
(self, validUVIndices)
This method will remove any invalid UVIds from the component list and UVId array. The benefit of this is to reduce the amount of extra processing that the node would have to perform. It will result in less iterations through the mesh as there are less UVs to search for.
This method will remove any invalid UVIds from the component list and UVId array. The benefit of this is to reduce the amount of extra processing that the node would have to perform. It will result in less iterations through the mesh as there are less UVs to search for.
[ "This", "method", "will", "remove", "any", "invalid", "UVIds", "from", "the", "component", "list", "and", "UVId", "array", ".", "The", "benefit", "of", "this", "is", "to", "reduce", "the", "amount", "of", "extra", "processing", "that", "the", "node", "woul...
def __pruneUVs(self, validUVIndices): """ This method will remove any invalid UVIds from the component list and UVId array. The benefit of this is to reduce the amount of extra processing that the node would have to perform. It will result in less iterations through the mesh as there are less UVs to search for. """ validUVIds = OpenMaya.MIntArray() for i in range(validUVIndices.length()): uvIndex = validUVIndices[i] validUVIds.append(self.__fSelUVs[uvIndex]) # Replace the local int array of UVIds # self.__fSelUVs.clear() self.__fSelUVs = validUVIds # Build the list of valid components # compFn = OpenMaya.MFnSingleIndexedComponent() try: compFn.create(OpenMaya.MFn.kMeshMapComponent) except: statusError("compFn.create( MFn::kMeshMapComponent )") try: compFn.addElements(validUVIds) except: statusError("compFn.addElements( validUVIds )") # Replace the component list # component = compFn.object() compListFn = OpenMaya.MFnComponentListData() compListFn.create() try: compListFn.add(component) except: statusError("compListFn.add( component )") self.__fComponentList = compListFn.object()
[ "def", "__pruneUVs", "(", "self", ",", "validUVIndices", ")", ":", "validUVIds", "=", "OpenMaya", ".", "MIntArray", "(", ")", "for", "i", "in", "range", "(", "validUVIndices", ".", "length", "(", ")", ")", ":", "uvIndex", "=", "validUVIndices", "[", "i",...
https://github.com/OpenXRay/xray-15/blob/1390dfb08ed20997d7e8c95147ea8e8cb71f5e86/cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/scripted/splitUVCmd.py#L313-L354
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/refactor.py
python
RefactoringTool.log_error
(self, msg, *args, **kwds)
Called when an error occurs.
Called when an error occurs.
[ "Called", "when", "an", "error", "occurs", "." ]
def log_error(self, msg, *args, **kwds): """Called when an error occurs.""" raise
[ "def", "log_error", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "raise" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/refactor.py#L255-L257
raspberrypi/tools
13474ee775d0c5ec8a7da4fb0a9fa84187abfc87
arm-bcm2708/arm-bcm2708hardfp-linux-gnueabi/share/gdb/python/gdb/command/pretty_printers.py
python
InfoPrettyPrinter.enabled_string
(printer)
Return "" if PRINTER is enabled, otherwise " [disabled]".
Return "" if PRINTER is enabled, otherwise " [disabled]".
[ "Return", "if", "PRINTER", "is", "enabled", "otherwise", "[", "disabled", "]", "." ]
def enabled_string(printer): """Return "" if PRINTER is enabled, otherwise " [disabled]".""" if printer_enabled_p(printer): return "" else: return " [disabled]"
[ "def", "enabled_string", "(", "printer", ")", ":", "if", "printer_enabled_p", "(", "printer", ")", ":", "return", "\"\"", "else", ":", "return", "\" [disabled]\"" ]
https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/arm-bcm2708hardfp-linux-gnueabi/share/gdb/python/gdb/command/pretty_printers.py#L103-L108
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/benchmark/mingw.py
python
find_in_path
(file, path=None)
return list(filter(os.path.exists, map(lambda dir, file=file: os.path.join(dir, file), path)))
Attempts to find an executable in the path
Attempts to find an executable in the path
[ "Attempts", "to", "find", "an", "executable", "in", "the", "path" ]
def find_in_path(file, path=None): ''' Attempts to find an executable in the path ''' if platform.system() == 'Windows': file += '.exe' if path is None: path = os.environ.get('PATH', '') if type(path) is type(''): path = path.split(os.pathsep) return list(filter(os.path.exists, map(lambda dir, file=file: os.path.join(dir, file), path)))
[ "def", "find_in_path", "(", "file", ",", "path", "=", "None", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "file", "+=", "'.exe'", "if", "path", "is", "None", ":", "path", "=", "os", ".", "environ", ".", "get", "(", ...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/benchmark/mingw.py#L86-L97
Vipermdl/OCR_detection_IC15
8eebd353d6fac97f5832a138d7af3bd3071670db
base/base_trainer.py
python
BaseTrainer.train
(self)
Full training logic
Full training logic
[ "Full", "training", "logic" ]
def train(self): """ Full training logic """ for epoch in range(self.start_epoch, self.epochs + 1): try: result = self._train_epoch(epoch) except torch.cuda.CudaError: self._log_memory_useage() log = {'epoch': epoch} for key, value in result.items(): if key == 'metrics': for i, metric in enumerate(self.metrics): log[metric.__name__] = result['metrics'][i] elif key == 'val_metrics': for i, metric in enumerate(self.metrics): log['val_' + metric.__name__] = result['val_metrics'][i] else: log[key] = value if self.train_logger is not None: self.train_logger.add_entry(log) if self.verbosity >= 1: for key, value in log.items(): self.logger.info(' {:15s}: {}'.format(str(key), value)) if (self.monitor_mode == 'min' and log[self.monitor] < self.monitor_best)\ or (self.monitor_mode == 'max' and log[self.monitor] > self.monitor_best): self.monitor_best = log[self.monitor] self._save_checkpoint(epoch, log, save_best=True) if epoch % self.save_freq == 0: self._save_checkpoint(epoch, log) if self.lr_scheduler and epoch % self.lr_scheduler_freq == 0: self.lr_scheduler.step(epoch) lr = self.lr_scheduler.get_lr()[0] self.logger.info('New Learning Rate: {:.8f}'.format(lr))
[ "def", "train", "(", "self", ")", ":", "for", "epoch", "in", "range", "(", "self", ".", "start_epoch", ",", "self", ".", "epochs", "+", "1", ")", ":", "try", ":", "result", "=", "self", ".", "_train_epoch", "(", "epoch", ")", "except", "torch", "."...
https://github.com/Vipermdl/OCR_detection_IC15/blob/8eebd353d6fac97f5832a138d7af3bd3071670db/base/base_trainer.py#L69-L103
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
PRESUBMIT.py
python
_CheckNoPragmaOnce
(input_api, output_api)
return []
Make sure that banned functions are not used.
Make sure that banned functions are not used.
[ "Make", "sure", "that", "banned", "functions", "are", "not", "used", "." ]
def _CheckNoPragmaOnce(input_api, output_api): """Make sure that banned functions are not used.""" files = [] pattern = input_api.re.compile(r'^#pragma\s+once', input_api.re.MULTILINE) for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile): if not f.LocalPath().endswith('.h'): continue contents = input_api.ReadFile(f) if pattern.search(contents): files.append(f) if files: return [output_api.PresubmitError( 'Do not use #pragma once in header files.\n' 'See http://www.chromium.org/developers/coding-style#TOC-File-headers', files)] return []
[ "def", "_CheckNoPragmaOnce", "(", "input_api", ",", "output_api", ")", ":", "files", "=", "[", "]", "pattern", "=", "input_api", ".", "re", ".", "compile", "(", "r'^#pragma\\s+once'", ",", "input_api", ".", "re", ".", "MULTILINE", ")", "for", "f", "in", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/PRESUBMIT.py#L433-L450
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/command/bdist_msi.py
python
PyDialog.next
(self, title, next, name = "Next", active = 1)
return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next)
Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated
Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled.
[ "Add", "a", "Next", "button", "with", "a", "given", "title", "the", "tab", "-", "next", "button", "its", "name", "in", "the", "Control", "table", "possibly", "initially", "disabled", "." ]
def next(self, title, next, name = "Next", active = 1): """Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next)
[ "def", "next", "(", "self", ",", "title", ",", "next", ",", "name", "=", "\"Next\"", ",", "active", "=", "1", ")", ":", "if", "active", ":", "flags", "=", "3", "# Visible|Enabled", "else", ":", "flags", "=", "1", "# Visible", "return", "self", ".", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/bdist_msi.py#L66-L75
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
MemoryFSHandler.CanOpen
(*args, **kwargs)
return _core_.MemoryFSHandler_CanOpen(*args, **kwargs)
CanOpen(self, String location) -> bool
CanOpen(self, String location) -> bool
[ "CanOpen", "(", "self", "String", "location", ")", "-", ">", "bool" ]
def CanOpen(*args, **kwargs): """CanOpen(self, String location) -> bool""" return _core_.MemoryFSHandler_CanOpen(*args, **kwargs)
[ "def", "CanOpen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MemoryFSHandler_CanOpen", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2574-L2576
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
docs/sphinxext/mantiddoc/directives/properties.py
python
PropertiesDirective.execute
(self)
return []
Called by Sphinx when the ..properties:: directive is encountered.
Called by Sphinx when the ..properties:: directive is encountered.
[ "Called", "by", "Sphinx", "when", "the", "..", "properties", "::", "directive", "is", "encountered", "." ]
def execute(self): """ Called by Sphinx when the ..properties:: directive is encountered. """ self._create_properties_table() return []
[ "def", "execute", "(", "self", ")", ":", "self", ".", "_create_properties_table", "(", ")", "return", "[", "]" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/docs/sphinxext/mantiddoc/directives/properties.py#L22-L27
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/autograd.py
python
predict_mode
()
return _RecordingStateScope(None, False)
Returns a scope context to be used in 'with' statement in which forward pass behavior is set to inference mode, without changing the recording states. Example:: with autograd.record(): y = model(x) with autograd.predict_mode(): y = sampling(y) backward([y])
Returns a scope context to be used in 'with' statement in which forward pass behavior is set to inference mode, without changing the recording states.
[ "Returns", "a", "scope", "context", "to", "be", "used", "in", "with", "statement", "in", "which", "forward", "pass", "behavior", "is", "set", "to", "inference", "mode", "without", "changing", "the", "recording", "states", "." ]
def predict_mode(): """Returns a scope context to be used in 'with' statement in which forward pass behavior is set to inference mode, without changing the recording states. Example:: with autograd.record(): y = model(x) with autograd.predict_mode(): y = sampling(y) backward([y]) """ return _RecordingStateScope(None, False)
[ "def", "predict_mode", "(", ")", ":", "return", "_RecordingStateScope", "(", "None", ",", "False", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/autograd.py#L181-L194
asLody/whale
6a661b27cc4cf83b7b5a3b02451597ee1ac7f264
whale/cpplint.py
python
CheckSpacingForFunctionCall
(filename, clean_lines, linenum, error)
Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing around function calls. 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] # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and not Search(r'\bcase\s+\(', fncall)): # TODO(unknown): Space after an operator function seem to be a common # error, silence those for now by restricting them to highest verbosity. if Search(r'\boperator_*\b', line): error(filename, linenum, 'whitespace/parens', 0, 'Extra space before ( in function call') else: error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have th...
https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L2940-L3014
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/burn_in_tags.py
python
_configure_logging
(verbose: bool)
Configure logging for the application. :param verbose: If True set log level to DEBUG.
Configure logging for the application.
[ "Configure", "logging", "for", "the", "application", "." ]
def _configure_logging(verbose: bool): """ Configure logging for the application. :param verbose: If True set log level to DEBUG. """ level = logging.DEBUG if verbose else logging.INFO logging.basicConfig( format="[%(asctime)s - %(name)s - %(levelname)s] %(message)s", level=level, stream=sys.stdout, ) for log_name in EXTERNAL_LOGGERS: logging.getLogger(log_name).setLevel(logging.WARNING)
[ "def", "_configure_logging", "(", "verbose", ":", "bool", ")", ":", "level", "=", "logging", ".", "DEBUG", "if", "verbose", "else", "logging", ".", "INFO", "logging", ".", "basicConfig", "(", "format", "=", "\"[%(asctime)s - %(name)s - %(levelname)s] %(message)s\"",...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/burn_in_tags.py#L187-L200
fossephate/JoyCon-Driver
857e4e76e26f05d72400ae5d9f2a22cae88f3548
joycon-driver/full/wxWidgets-3.0.3/build/tools/build-wxwidgets.py
python
numCPUs
()
return 1
Detects the number of CPUs on a system. This approach is from detectCPUs here: http://www.artima.com/weblogs/viewpost.jsp?thread=230001
Detects the number of CPUs on a system. This approach is from detectCPUs here: http://www.artima.com/weblogs/viewpost.jsp?thread=230001
[ "Detects", "the", "number", "of", "CPUs", "on", "a", "system", ".", "This", "approach", "is", "from", "detectCPUs", "here", ":", "http", ":", "//", "www", ".", "artima", ".", "com", "/", "weblogs", "/", "viewpost", ".", "jsp?thread", "=", "230001" ]
def numCPUs(): """ Detects the number of CPUs on a system. This approach is from detectCPUs here: http://www.artima.com/weblogs/viewpost.jsp?thread=230001 """ # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: # Linux & Unix: ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if isinstance(ncpus, int) and ncpus > 0: return ncpus else: # OSX: p = subprocess.Popen("sysctl -n hw.ncpu", shell=True, stdout=subprocess.PIPE) return p.stdout.read() # Windows: if "NUMBER_OF_PROCESSORS" in os.environ: ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]); if ncpus > 0: return ncpus return 1
[ "def", "numCPUs", "(", ")", ":", "# Linux, Unix and MacOS:", "if", "hasattr", "(", "os", ",", "\"sysconf\"", ")", ":", "if", "\"SC_NPROCESSORS_ONLN\"", "in", "os", ".", "sysconf_names", ":", "# Linux & Unix:", "ncpus", "=", "os", ".", "sysconf", "(", "\"SC_NPR...
https://github.com/fossephate/JoyCon-Driver/blob/857e4e76e26f05d72400ae5d9f2a22cae88f3548/joycon-driver/full/wxWidgets-3.0.3/build/tools/build-wxwidgets.py#L36-L57
KDE/krita
10ea63984e00366865769c193ab298de73a59c5c
plugins/python/scripter/ui_scripter/actions/runaction/runaction.py
python
RunAction.run
(self)
This method execute python code from an activeDocument (file) or direct from editor (ui_scripter/editor/pythoneditor.py). When executing code from a file, we use importlib to load this module/file and with "users_script" name. That's implementation seeks for a "main()" function in the script. When executing code from editor without creating a file, we compile this script to bytecode and we execute this in an empty scope. That's faster than use exec directly and cleaner, because we are using an empty scope.
This method execute python code from an activeDocument (file) or direct from editor (ui_scripter/editor/pythoneditor.py). When executing code from a file, we use importlib to load this module/file and with "users_script" name. That's implementation seeks for a "main()" function in the script. When executing code from editor without creating a file, we compile this script to bytecode and we execute this in an empty scope. That's faster than use exec directly and cleaner, because we are using an empty scope.
[ "This", "method", "execute", "python", "code", "from", "an", "activeDocument", "(", "file", ")", "or", "direct", "from", "editor", "(", "ui_scripter", "/", "editor", "/", "pythoneditor", ".", "py", ")", ".", "When", "executing", "code", "from", "a", "file"...
def run(self): """ This method execute python code from an activeDocument (file) or direct from editor (ui_scripter/editor/pythoneditor.py). When executing code from a file, we use importlib to load this module/file and with "users_script" name. That's implementation seeks for a "main()" function in the script. When executing code from editor without creating a file, we compile this script to bytecode and we execute this in an empty scope. That's faster than use exec directly and cleaner, because we are using an empty scope. """ self.scripter.uicontroller.setActiveWidget(i18n('Output')) stdout = sys.stdout stderr = sys.stderr output = docwrapper.DocWrapper(self.output.document()) if (self.editor._documentModified is True): output.write("==== Warning: Script not saved! ====\n") else: output.write("======================================\n") sys.stdout = output sys.stderr = output script = self.editor.document().toPlainText() document = self.scripter.documentcontroller.activeDocument try: if document and self.editor._documentModified is False: if PYTHON27: users_module = self.run_py2_document(document) else: users_module = self.run_py3_document(document) # maybe script is to be execed, maybe main needs to be invoked # if there is a main() then execute it, otherwise don't worry... if hasattr(users_module, "main") and inspect.isfunction(users_module.main): users_module.main() else: code = compile(script, '<string>', 'exec') globals_dict = {"__name__": EXEC_NAMESPACE} exec(code, globals_dict) except SystemExit: # user typed quit() or exit() self.scripter.uicontroller.closeScripter() except Exception: # Provide context (line number and text) for an error that is caught. # Ordinarily, syntax and Indent errors are caught during initial # compilation in exec(), and the traceback traces back to this file. # So these need to be treated separately. # Other errors trace back to the file/script being run. type_, value_, traceback_ = sys.exc_info() if type_ == SyntaxError: errorMessage = "%s\n%s" % (value_.text.rstrip(), " " * (value_.offset - 1) + "^") # rstrip to remove trailing \n, output needs to be fixed width font for the ^ to align correctly errorText = "Syntax Error on line %s" % value_.lineno elif type_ == IndentationError: # (no offset is provided for an IndentationError errorMessage = value_.text.rstrip() errorText = "Unexpected Indent on line %s" % value_.lineno else: errorText = traceback.format_exception_only(type_, value_)[0] format_string = "In file: {0}\nIn function: {2} at line: {1}. Line with error:\n{3}" tbList = traceback.extract_tb(traceback_) tb = tbList[-1] errorMessage = format_string.format(*tb) m = "\n**********************\n%s\n%s\n**********************\n" % (errorText, errorMessage) output.write(m) sys.stdout = stdout sys.stderr = stderr # scroll to bottom of output bottom = self.output.verticalScrollBar().maximum() self.output.verticalScrollBar().setValue(bottom)
[ "def", "run", "(", "self", ")", ":", "self", ".", "scripter", ".", "uicontroller", ".", "setActiveWidget", "(", "i18n", "(", "'Output'", ")", ")", "stdout", "=", "sys", ".", "stdout", "stderr", "=", "sys", ".", "stderr", "output", "=", "docwrapper", "....
https://github.com/KDE/krita/blob/10ea63984e00366865769c193ab298de73a59c5c/plugins/python/scripter/ui_scripter/actions/runaction/runaction.py#L47-L118
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/module/bulkextractor.py
python
Session.scanners
(self, scanners=None)
return list(self._scanners)
Return the list of active scanners.
Return the list of active scanners.
[ "Return", "the", "list", "of", "active", "scanners", "." ]
def scanners(self, scanners=None): """Return the list of active scanners.""" return list(self._scanners)
[ "def", "scanners", "(", "self", ",", "scanners", "=", "None", ")", ":", "return", "list", "(", "self", ".", "_scanners", ")" ]
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/module/bulkextractor.py#L134-L136
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/implementations/http.py
python
HTTPFileSystem.mkdirs
(self, url)
Make any intermediate directories to make path writable
Make any intermediate directories to make path writable
[ "Make", "any", "intermediate", "directories", "to", "make", "path", "writable" ]
def mkdirs(self, url): """Make any intermediate directories to make path writable""" raise NotImplementedError
[ "def", "mkdirs", "(", "self", ",", "url", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/implementations/http.py#L114-L116
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py
python
Counter.copy
(self)
return self.__class__(self)
Return a shallow copy.
Return a shallow copy.
[ "Return", "a", "shallow", "copy", "." ]
def copy(self): 'Return a shallow copy.' return self.__class__(self)
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py#L693-L695
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Listbox.nearest
(self, y)
return getint(self.tk.call( self._w, 'nearest', y))
Get index of item which is nearest to y coordinate Y.
Get index of item which is nearest to y coordinate Y.
[ "Get", "index", "of", "item", "which", "is", "nearest", "to", "y", "coordinate", "Y", "." ]
def nearest(self, y): """Get index of item which is nearest to y coordinate Y.""" return getint(self.tk.call( self._w, 'nearest', y))
[ "def", "nearest", "(", "self", ",", "y", ")", ":", "return", "getint", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'nearest'", ",", "y", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2581-L2584
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/AccumulativeLookup.py
python
AccumulativeLookup.size
(self, size)
Sets the vector length.
Sets the vector length.
[ "Sets", "the", "vector", "length", "." ]
def size(self, size): """Sets the vector length. """ self._internal.set_size(int(size))
[ "def", "size", "(", "self", ",", "size", ")", ":", "self", ".", "_internal", ".", "set_size", "(", "int", "(", "size", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/AccumulativeLookup.py#L74-L77
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/indexes/range.py
python
RangeIndex._extended_gcd
(self, a, b)
return old_r, old_s, old_t
Extended Euclidean algorithms to solve Bezout's identity: a*x + b*y = gcd(x, y) Finds one particular solution for x, y: s, t Returns: gcd, s, t
Extended Euclidean algorithms to solve Bezout's identity: a*x + b*y = gcd(x, y) Finds one particular solution for x, y: s, t Returns: gcd, s, t
[ "Extended", "Euclidean", "algorithms", "to", "solve", "Bezout", "s", "identity", ":", "a", "*", "x", "+", "b", "*", "y", "=", "gcd", "(", "x", "y", ")", "Finds", "one", "particular", "solution", "for", "x", "y", ":", "s", "t", "Returns", ":", "gcd"...
def _extended_gcd(self, a, b): """ Extended Euclidean algorithms to solve Bezout's identity: a*x + b*y = gcd(x, y) Finds one particular solution for x, y: s, t Returns: gcd, s, t """ s, old_s = 0, 1 t, old_t = 1, 0 r, old_r = b, a while r: quotient = old_r // r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t return old_r, old_s, old_t
[ "def", "_extended_gcd", "(", "self", ",", "a", ",", "b", ")", ":", "s", ",", "old_s", "=", "0", ",", "1", "t", ",", "old_t", "=", "1", ",", "0", "r", ",", "old_r", "=", "b", ",", "a", "while", "r", ":", "quotient", "=", "old_r", "//", "r", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/range.py#L424-L439
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py
python
BuildReachableFileSet
(entry_classes, reachability_tree, header_mapping, archive_source_file_mapping=None)
return reachable_files
Builds a set of reachable translated files from entry Java classes. Args: entry_classes: A comma separated list of Java entry classes. reachability_tree: A dict mapping translated files to their direct dependencies. header_mapping: A dict mapping Java class names to translated source files. archive_source_file_mapping: A dict mapping source files to the associated archive file that contains them. Returns: A set of reachable translated files from the given list of entry classes. Raises: Exception: If there is an entry class that is not being transpiled in this j2objc_library.
Builds a set of reachable translated files from entry Java classes.
[ "Builds", "a", "set", "of", "reachable", "translated", "files", "from", "entry", "Java", "classes", "." ]
def BuildReachableFileSet(entry_classes, reachability_tree, header_mapping, archive_source_file_mapping=None): """Builds a set of reachable translated files from entry Java classes. Args: entry_classes: A comma separated list of Java entry classes. reachability_tree: A dict mapping translated files to their direct dependencies. header_mapping: A dict mapping Java class names to translated source files. archive_source_file_mapping: A dict mapping source files to the associated archive file that contains them. Returns: A set of reachable translated files from the given list of entry classes. Raises: Exception: If there is an entry class that is not being transpiled in this j2objc_library. """ transpiled_entry_files = [] for entry_class in entry_classes.split(','): if entry_class not in header_mapping: raise Exception(entry_class + 'is not in the transitive Java deps of included ' + 'j2objc_library rules.') transpiled_entry_files.append(header_mapping[entry_class]) # Translated files going into the same static library archive with duplicated # base names also need to be added to the set of entry files. # # This edge case is ignored because we currently cannot correctly perform # dead code removal in this case. The object file entries in static library # archives are named by the base names of the original source files. If two # source files (e.g., foo/bar.m, bar/bar.m) go into the same archive and # share the same base name (bar.m), their object file entries inside the # archive will have the same name (bar.o). We cannot correctly handle this # case because current archive tools (ar, ranlib, etc.) do not handle this # case very well. if archive_source_file_mapping: transpiled_entry_files.extend(_DuplicatedFiles(archive_source_file_mapping)) # Translated files from package-info.java are also added to the entry files # because they are needed to resolve ObjC class names with prefixes and these # files may also have dependencies. for transpiled_file in reachability_tree: if transpiled_file.endswith('package-info'): transpiled_entry_files.append(transpiled_file) reachable_files = set() for transpiled_entry_file in transpiled_entry_files: reachable_files.add(transpiled_entry_file) current_level_deps = [] # We need to check if the transpiled file is in the reachability tree # because J2ObjC protos are not analyzed for dead code stripping and # therefore are not in the reachability tree at all. if transpiled_entry_file in reachability_tree: current_level_deps = reachability_tree[transpiled_entry_file] while current_level_deps: next_level_deps = [] for dep in current_level_deps: if dep not in reachable_files: reachable_files.add(dep) if dep in reachability_tree: next_level_deps.extend(reachability_tree[dep]) current_level_deps = next_level_deps return reachable_files
[ "def", "BuildReachableFileSet", "(", "entry_classes", ",", "reachability_tree", ",", "header_mapping", ",", "archive_source_file_mapping", "=", "None", ")", ":", "transpiled_entry_files", "=", "[", "]", "for", "entry_class", "in", "entry_classes", ".", "split", "(", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py#L88-L151
NeoGeographyToolkit/StereoPipeline
eedf54a919fb5cce1ab0e280bb0df4050763aa11
src/asp/IceBridge/pleiades_manager.py
python
checkRequiredTools
()
Verify that we have all the tools we will be calling during the script.
Verify that we have all the tools we will be calling during the script.
[ "Verify", "that", "we", "have", "all", "the", "tools", "we", "will", "be", "calling", "during", "the", "script", "." ]
def checkRequiredTools(): '''Verify that we have all the tools we will be calling during the script.''' scripts = ['full_processing_script.py', 'multi_process_command_runner.py', 'merge_orbitviz.py', 'process_icebridge_run.py', 'process_icebridge_batch.py', 'lvis2kml.py', 'blend_dems.py', 'gen_ortho.py'] tools = ['ortho2pinhole', 'camera_footprint', 'bundle_adjust', 'stereo', 'point2dem', 'mapproject'] for tool in tools: asp_system_utils.checkIfToolExists(tool) for script in scripts: if not os.path.exists(icebridge_common.fullPath(script)): raise Exception("Could not find: " + script)
[ "def", "checkRequiredTools", "(", ")", ":", "scripts", "=", "[", "'full_processing_script.py'", ",", "'multi_process_command_runner.py'", ",", "'merge_orbitviz.py'", ",", "'process_icebridge_run.py'", ",", "'process_icebridge_batch.py'", ",", "'lvis2kml.py'", ",", "'blend_dem...
https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/pleiades_manager.py#L903-L920