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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/base.py
python
ExtensionArray.equals
(self, other: object)
Return if another array is equivalent to this array. Equivalent means that both arrays have the same shape and dtype, and all values compare equal. Missing values in the same location are considered equal (in contrast with normal equality). Parameters ---------- other : ExtensionArray Array to compare to this Array. Returns ------- boolean Whether the arrays are equivalent.
Return if another array is equivalent to this array.
[ "Return", "if", "another", "array", "is", "equivalent", "to", "this", "array", "." ]
def equals(self, other: object) -> bool: """ Return if another array is equivalent to this array. Equivalent means that both arrays have the same shape and dtype, and all values compare equal. Missing values in the same location are considered equal (in contrast with normal equality). Parameters ---------- other : ExtensionArray Array to compare to this Array. Returns ------- boolean Whether the arrays are equivalent. """ if type(self) != type(other): return False other = cast(ExtensionArray, other) if not is_dtype_equal(self.dtype, other.dtype): return False elif len(self) != len(other): return False else: equal_values = self == other if isinstance(equal_values, ExtensionArray): # boolean array with NA -> fill with False equal_values = equal_values.fillna(False) # error: Unsupported left operand type for & ("ExtensionArray") equal_na = self.isna() & other.isna() # type: ignore[operator] return bool((equal_values | equal_na).all())
[ "def", "equals", "(", "self", ",", "other", ":", "object", ")", "->", "bool", ":", "if", "type", "(", "self", ")", "!=", "type", "(", "other", ")", ":", "return", "False", "other", "=", "cast", "(", "ExtensionArray", ",", "other", ")", "if", "not",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/base.py#L856-L888
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/bindings/python/llvm/object.py
python
Symbol.expire
(self)
Mark the object as expired to prevent future API accesses. This is called internally by this module and it is unlikely that external callers have a legitimate reason for using it.
Mark the object as expired to prevent future API accesses.
[ "Mark", "the", "object", "as", "expired", "to", "prevent", "future", "API", "accesses", "." ]
def expire(self): """Mark the object as expired to prevent future API accesses. This is called internally by this module and it is unlikely that external callers have a legitimate reason for using it. """ self.expired = True
[ "def", "expire", "(", "self", ")", ":", "self", ".", "expired", "=", "True" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/bindings/python/llvm/object.py#L349-L355
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/trace_result.py
python
TraceResult.Serialize
(self, f)
return self._impl.Serialize(f)
Serializes the trace result to a file-like object
Serializes the trace result to a file-like object
[ "Serializes", "the", "trace", "result", "to", "a", "file", "-", "like", "object" ]
def Serialize(self, f): """Serializes the trace result to a file-like object""" return self._impl.Serialize(f)
[ "def", "Serialize", "(", "self", ",", "f", ")", ":", "return", "self", ".", "_impl", ".", "Serialize", "(", "f", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/trace_result.py#L9-L11
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/control_flow_ops.py
python
_MergeShape
(op)
Shape function for the Merge op. The Merge op takes many inputs of arbitrary shapes, and produces a first output that is one of those inputs, and a second scalar output. If all input shapes are known and have the same rank, the output shape must have that rank, otherwise the output shape is unknown. Each output dimension is specified only if that dimension in all inputs are the same. Args: op: A Merge Operation. Returns: A single-element list containing the Shape of the Merge op.
Shape function for the Merge op.
[ "Shape", "function", "for", "the", "Merge", "op", "." ]
def _MergeShape(op): """Shape function for the Merge op. The Merge op takes many inputs of arbitrary shapes, and produces a first output that is one of those inputs, and a second scalar output. If all input shapes are known and have the same rank, the output shape must have that rank, otherwise the output shape is unknown. Each output dimension is specified only if that dimension in all inputs are the same. Args: op: A Merge Operation. Returns: A single-element list containing the Shape of the Merge op. """ output_shape = op.inputs[0].get_shape() if output_shape.dims is None: return [tensor_shape.unknown_shape(), tensor_shape.scalar()] else: for input_ in op.inputs[1:]: input_shape = input_.get_shape() if input_shape.dims is None or input_shape.ndims != output_shape.ndims: return [tensor_shape.unknown_shape(), tensor_shape.scalar()] else: output_shape = tensor_shape.TensorShape( [input_dim.value if input_dim.value == output_dim.value else None for input_dim, output_dim in zip(input_shape.dims, output_shape.dims)]) return [output_shape, tensor_shape.scalar()]
[ "def", "_MergeShape", "(", "op", ")", ":", "output_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "if", "output_shape", ".", "dims", "is", "None", ":", "return", "[", "tensor_shape", ".", "unknown_shape", "(", ")", ",", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/control_flow_ops.py#L2936-L2968
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/python_message.py
python
_AddSerializeToStringMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( 'Message %s is missing required fields: %s' % ( self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors()))) return self.SerializePartialToString() cls.SerializeToString = SerializeToString
[ "def", "_AddSerializeToStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "SerializeToString", "(", "self", ")", ":", "# Check if the message has all of its required fields set.", "errors", "=", "[", "]", "if", "not", "self", ".", "IsInitialized", ...
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/python_message.py#L1026-L1037
vtraag/leidenalg
b53366829360e10922a2dbf57eb405a516c23bc9
src/leidenalg/VertexPartition.py
python
MutableVertexPartition.total_weight_in_comm
(self, comm)
return _c_leiden._MutableVertexPartition_total_weight_in_comm(self._partition, comm)
The total weight (i.e. number of edges) within a community. Parameters ---------- comm Community See Also -------- :func:`~VertexPartition.MutableVertexPartition.total_weight_to_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_from_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_in_all_comms`
The total weight (i.e. number of edges) within a community.
[ "The", "total", "weight", "(", "i", ".", "e", ".", "number", "of", "edges", ")", "within", "a", "community", "." ]
def total_weight_in_comm(self, comm): """ The total weight (i.e. number of edges) within a community. Parameters ---------- comm Community See Also -------- :func:`~VertexPartition.MutableVertexPartition.total_weight_to_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_from_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_in_all_comms` """ return _c_leiden._MutableVertexPartition_total_weight_in_comm(self._partition, comm)
[ "def", "total_weight_in_comm", "(", "self", ",", "comm", ")", ":", "return", "_c_leiden", ".", "_MutableVertexPartition_total_weight_in_comm", "(", "self", ".", "_partition", ",", "comm", ")" ]
https://github.com/vtraag/leidenalg/blob/b53366829360e10922a2dbf57eb405a516c23bc9/src/leidenalg/VertexPartition.py#L270-L286
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/fuchsia/runner_exceptions.py
python
_PrintException
(value, trace)
Prints stack trace and error message for the current exception.
Prints stack trace and error message for the current exception.
[ "Prints", "stack", "trace", "and", "error", "message", "for", "the", "current", "exception", "." ]
def _PrintException(value, trace): """Prints stack trace and error message for the current exception.""" traceback.print_tb(trace) print(str(value))
[ "def", "_PrintException", "(", "value", ",", "trace", ")", ":", "traceback", ".", "print_tb", "(", "trace", ")", "print", "(", "str", "(", "value", ")", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/runner_exceptions.py#L20-L24
eric612/MobileNet-YOLO
69b4441cb3ec8d553fbdef788ad033e246f901bd
python/draw_net.py
python
parse_args
()
return args
Parse input arguments
Parse input arguments
[ "Parse", "input", "arguments" ]
def parse_args(): """Parse input arguments """ parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('input_net_proto_file', help='Input network prototxt file') parser.add_argument('output_image_file', help='Output image file') parser.add_argument('--rankdir', help=('One of TB (top-bottom, i.e., vertical), ' 'RL (right-left, i.e., horizontal), or another ' 'valid dot option; see ' 'http://www.graphviz.org/doc/info/' 'attrs.html#k:rankdir'), default='LR') parser.add_argument('--phase', help=('Which network phase to draw: can be TRAIN, ' 'TEST, or ALL. If ALL, then all layers are drawn ' 'regardless of phase.'), default="ALL") parser.add_argument('--display_lrm', action='store_true', help=('Use this flag to visualize the learning rate ' 'multiplier, when non-zero, for the learning ' 'layers (Convolution, Deconvolution, InnerProduct).')) args = parser.parse_args() return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "parser", ".", "add_argument", "(", "'input_net_proto_file'", ",", "help", "=", "'Input networ...
https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/python/draw_net.py#L13-L42
intel-iot-devkit/how-to-code-samples
b4ea616f36bbfa2e042beb1698f968cfd651d79f
earthquake-detector/python/iot_earthquake_detector/runner.py
python
Runner.detect_earthquake
(self)
Detect earthquake with USGS verification.
Detect earthquake with USGS verification.
[ "Detect", "earthquake", "with", "USGS", "verification", "." ]
def detect_earthquake(self): """ Detect earthquake with USGS verification. """ self.display_verifying() verification = verify_earthquake() if verification: self.display_warning() else: self.display_false_alarm() sleep(15) self.reset()
[ "def", "detect_earthquake", "(", "self", ")", ":", "self", ".", "display_verifying", "(", ")", "verification", "=", "verify_earthquake", "(", ")", "if", "verification", ":", "self", ".", "display_warning", "(", ")", "else", ":", "self", ".", "display_false_ala...
https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/earthquake-detector/python/iot_earthquake_detector/runner.py#L63-L76
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/index.py
python
PackageIndex.download_file
(self, url, destfile, digest=None, reporthook=None)
This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere). The method is just like the :func:`urlretrieve` function in the standard library, except that it allows digest computation to be done during download and checking that the downloaded data matched any expected value. :param url: The URL of the file to be downloaded (assumed to be available via an HTTP GET request). :param destfile: The pathname where the downloaded file is to be saved. :param digest: If specified, this must be a (hasher, value) tuple, where hasher is the algorithm used (e.g. ``'md5'``) and ``value`` is the expected value. :param reporthook: The same as for :func:`urlretrieve` in the standard library.
This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere).
[ "This", "is", "a", "convenience", "method", "for", "downloading", "a", "file", "from", "an", "URL", ".", "Normally", "this", "will", "be", "a", "file", "from", "the", "index", "though", "currently", "no", "check", "is", "made", "for", "this", "(", "i", ...
def download_file(self, url, destfile, digest=None, reporthook=None): """ This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere). The method is just like the :func:`urlretrieve` function in the standard library, except that it allows digest computation to be done during download and checking that the downloaded data matched any expected value. :param url: The URL of the file to be downloaded (assumed to be available via an HTTP GET request). :param destfile: The pathname where the downloaded file is to be saved. :param digest: If specified, this must be a (hasher, value) tuple, where hasher is the algorithm used (e.g. ``'md5'``) and ``value`` is the expected value. :param reporthook: The same as for :func:`urlretrieve` in the standard library. """ if digest is None: digester = None logger.debug('No digest specified') else: if isinstance(digest, (list, tuple)): hasher, digest = digest else: hasher = 'md5' digester = getattr(hashlib, hasher)() logger.debug('Digest specified: %s' % digest) # The following code is equivalent to urlretrieve. # We need to do it this way so that we can compute the # digest of the file as we go. with open(destfile, 'wb') as dfp: # addinfourl is not a context manager on 2.x # so we have to use try/finally sfp = self.send_request(Request(url)) try: headers = sfp.info() blocksize = 8192 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, blocksize, size) while True: block = sfp.read(blocksize) if not block: break read += len(block) dfp.write(block) if digester: digester.update(block) blocknum += 1 if reporthook: reporthook(blocknum, blocksize, size) finally: sfp.close() # check that we got the whole file, if we can if size >= 0 and read < size: raise DistlibException( 'retrieval incomplete: got only %d out of %d bytes' % (read, size)) # if we have a digest, it must match. if digester: actual = digester.hexdigest() if digest != actual: raise DistlibException('%s digest mismatch for %s: expected ' '%s, got %s' % (hasher, destfile, digest, actual)) logger.debug('Digest verified: %s', digest)
[ "def", "download_file", "(", "self", ",", "url", ",", "destfile", ",", "digest", "=", "None", ",", "reporthook", "=", "None", ")", ":", "if", "digest", "is", "None", ":", "digester", "=", "None", "logger", ".", "debug", "(", "'No digest specified'", ")",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/index.py#L373-L448
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py
python
ParserElement.scanString
(self, instring, maxMatches=_MAX_INT, overlap=False)
Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional ``maxMatches`` argument, to clip scanning after 'n' matches are found. If ``overlap`` is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See :class:`parseString` for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens, start, end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd
[]
def scanString(self, instring, maxMatches=_MAX_INT, overlap=False): """ Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional ``maxMatches`` argument, to clip scanning after 'n' matches are found. If ``overlap`` is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See :class:`parseString` for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens, start, end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd """ if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.streamline() if not self.keepTabs: instring = _ustr(instring).expandtabs() instrlen = len(instring) loc = 0 preparseFn = self.preParse parseFn = self._parse ParserElement.resetCache() matches = 0 try: while loc <= instrlen and matches < maxMatches: try: preloc = preparseFn(instring, loc) nextLoc, tokens = parseFn(instring, preloc, callPreParse=False) except ParseException: loc = preloc + 1 else: if nextLoc > loc: matches += 1 yield tokens, preloc, nextLoc if overlap: nextloc = preparseFn(instring, loc) if nextloc > loc: loc = nextLoc else: loc += 1 else: loc = nextLoc else: loc = preloc + 1 except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clearing out pyparsing internal stack trace if getattr(exc, '__traceback__', None) is not None: exc.__traceback__ = self._trim_traceback(exc.__traceback__) raise exc
[ "def", "scanString", "(", "self", ",", "instring", ",", "maxMatches", "=", "_MAX_INT", ",", "overlap", "=", "False", ")", ":", "if", "not", "self", ".", "streamlined", ":", "self", ".", "streamline", "(", ")", "for", "e", "in", "self", ".", "ignoreExpr...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L3917-L4061
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/_supervised_learning.py
python
SupervisedLearningModel._training_stats
(self)
return self.__proxy__.get_train_stats()
Return a dictionary containing statistics collected during model training. These statistics are also available with the ``get`` method, and are described in more detail in the documentation for that method. Notes -----
Return a dictionary containing statistics collected during model training. These statistics are also available with the ``get`` method, and are described in more detail in the documentation for that method.
[ "Return", "a", "dictionary", "containing", "statistics", "collected", "during", "model", "training", ".", "These", "statistics", "are", "also", "available", "with", "the", "get", "method", "and", "are", "described", "in", "more", "detail", "in", "the", "document...
def _training_stats(self): """ Return a dictionary containing statistics collected during model training. These statistics are also available with the ``get`` method, and are described in more detail in the documentation for that method. Notes ----- """ return self.__proxy__.get_train_stats()
[ "def", "_training_stats", "(", "self", ")", ":", "return", "self", ".", "__proxy__", ".", "get_train_stats", "(", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/_supervised_learning.py#L171-L180
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/contact.py
python
contactMapIKObjectives
(contactmap)
return objectives
Given a contact map, computes a set of non-conflicting IKObjective's or GeneralizedIKObjective's that enforce all simultaneous contact constraints. Usually called in conjunction with contactMap with the following sequence:: objectives = contactMapIKObjectives(contactMap(contacts,lambda x:x==None or isinstance(x,TerrainModel)))
Given a contact map, computes a set of non-conflicting IKObjective's or GeneralizedIKObjective's that enforce all simultaneous contact constraints. Usually called in conjunction with contactMap with the following sequence::
[ "Given", "a", "contact", "map", "computes", "a", "set", "of", "non", "-", "conflicting", "IKObjective", "s", "or", "GeneralizedIKObjective", "s", "that", "enforce", "all", "simultaneous", "contact", "constraints", ".", "Usually", "called", "in", "conjunction", "...
def contactMapIKObjectives(contactmap): """Given a contact map, computes a set of non-conflicting IKObjective's or GeneralizedIKObjective's that enforce all simultaneous contact constraints. Usually called in conjunction with contactMap with the following sequence:: objectives = contactMapIKObjectives(contactMap(contacts,lambda x:x==None or isinstance(x,TerrainModel))) """ objectives = [] for ((o1,o2),clist) in contactmap.iteritems(): assert o1 != None x1loc = [o1.getLocalPosition(c.x) for c in clist] if o2 is not None and not isinstance(o2,TerrainModel): x2loc = [o2.getLocalPosition(c.x) for c in clist] objectives.append(ik.objective(o1,o2,local=x1loc,world=x2loc)) else: x2 = [c.x for c in clist] objectives.append(ik.objective(o1,local=x1loc,world=x2)) return objectives
[ "def", "contactMapIKObjectives", "(", "contactmap", ")", ":", "objectives", "=", "[", "]", "for", "(", "(", "o1", ",", "o2", ")", ",", "clist", ")", "in", "contactmap", ".", "iteritems", "(", ")", ":", "assert", "o1", "!=", "None", "x1loc", "=", "[",...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/contact.py#L326-L346
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/sponge_ops.py
python
DihedralForceWithAtomEnergy.__init__
(self, dihedral_numbers)
Initialize DihedralForceWithAtomEnergy.
Initialize DihedralForceWithAtomEnergy.
[ "Initialize", "DihedralForceWithAtomEnergy", "." ]
def __init__(self, dihedral_numbers): """Initialize DihedralForceWithAtomEnergy.""" validator.check_value_type('dihedral_numbers', dihedral_numbers, int, self.name) self.dihedral_numbers = dihedral_numbers self.init_prim_io_names(inputs=['uint_crd_f', 'scaler_f', 'atom_a', 'atom_b', 'atom_c', 'atom_d', 'ipn', 'pk', 'gamc', 'gams', 'pn'], outputs=['frc_f', 'ene']) self.add_prim_attr('dihedral_numbers', self.dihedral_numbers)
[ "def", "__init__", "(", "self", ",", "dihedral_numbers", ")", ":", "validator", ".", "check_value_type", "(", "'dihedral_numbers'", ",", "dihedral_numbers", ",", "int", ",", "self", ".", "name", ")", "self", ".", "dihedral_numbers", "=", "dihedral_numbers", "sel...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/sponge_ops.py#L815-L822
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py
python
_CountingAttr.validator
(self, meth)
return meth
Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0
Decorator that adds *meth* to the list of validators.
[ "Decorator", "that", "adds", "*", "meth", "*", "to", "the", "list", "of", "validators", "." ]
def validator(self, meth): """ Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 """ if self._validator is None: self._validator = meth else: self._validator = and_(self._validator, meth) return meth
[ "def", "validator", "(", "self", ",", "meth", ")", ":", "if", "self", ".", "_validator", "is", "None", ":", "self", ".", "_validator", "=", "meth", "else", ":", "self", ".", "_validator", "=", "and_", "(", "self", ".", "_validator", ",", "meth", ")",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py#L2008-L2020
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Misc.winfo_x
(self)
return self.tk.getint( self.tk.call('winfo', 'x', self._w))
Return the x coordinate of the upper left corner of this widget in the parent.
Return the x coordinate of the upper left corner of this widget in the parent.
[ "Return", "the", "x", "coordinate", "of", "the", "upper", "left", "corner", "of", "this", "widget", "in", "the", "parent", "." ]
def winfo_x(self): """Return the x coordinate of the upper left corner of this widget in the parent.""" return self.tk.getint( self.tk.call('winfo', 'x', self._w))
[ "def", "winfo_x", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "getint", "(", "self", ".", "tk", ".", "call", "(", "'winfo'", ",", "'x'", ",", "self", ".", "_w", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1165-L1169
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/Demos/win32netdemo.py
python
UserEnum
()
Enumerates all the local users
Enumerates all the local users
[ "Enumerates", "all", "the", "local", "users" ]
def UserEnum(): "Enumerates all the local users" resume = 0 nuser = 0 while 1: data, total, resume = win32net.NetUserEnum(server, 3, win32netcon.FILTER_NORMAL_ACCOUNT, resume) verbose("Call to NetUserEnum obtained %d entries of %d total" % (len(data), total)) for user in data: verbose("Found user %s" % user['name']) nuser = nuser + 1 if not resume: break assert nuser, "Could not find any users!" print "Enumerated all the local users"
[ "def", "UserEnum", "(", ")", ":", "resume", "=", "0", "nuser", "=", "0", "while", "1", ":", "data", ",", "total", ",", "resume", "=", "win32net", ".", "NetUserEnum", "(", "server", ",", "3", ",", "win32netcon", ".", "FILTER_NORMAL_ACCOUNT", ",", "resum...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/Demos/win32netdemo.py#L44-L57
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
build/fbcode_builder/fbcode_builder.py
python
FBCodeBuilder.run
(self, shell_cmd)
Run this bash command
Run this bash command
[ "Run", "this", "bash", "command" ]
def run(self, shell_cmd): "Run this bash command" raise NotImplementedError
[ "def", "run", "(", "self", ",", "shell_cmd", ")", ":", "raise", "NotImplementedError" ]
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/build/fbcode_builder/fbcode_builder.py#L172-L174
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/style/cpplint.py
python
NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L2685-L2691
crystax/android-platform-ndk
d86e23c826179a1c46b0576d42501ed234bf1a50
build/instruments/build-python/sysconfig.py
python
get_config_var
(name)
return get_config_vars().get(name)
Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name)
Return the value of a single variable using the dictionary returned by 'get_config_vars()'.
[ "Return", "the", "value", "of", "a", "single", "variable", "using", "the", "dictionary", "returned", "by", "get_config_vars", "()", "." ]
def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ return get_config_vars().get(name)
[ "def", "get_config_var", "(", "name", ")", ":", "return", "get_config_vars", "(", ")", ".", "get", "(", "name", ")" ]
https://github.com/crystax/android-platform-ndk/blob/d86e23c826179a1c46b0576d42501ed234bf1a50/build/instruments/build-python/sysconfig.py#L126-L132
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/fife_timer.py
python
repeatCall
(period,callback)
return timer
Repeat a function call. The call is repeated until the timer is stopped. Remember to keep a reference to the timer this function returns. If you do not python will delete the timer prematurely which may case a segfault. @param period: Period between calls in milliseconds. @param callback: The function to call. @return: The timer. @rtype: L{Timer}
Repeat a function call. The call is repeated until the timer is stopped.
[ "Repeat", "a", "function", "call", ".", "The", "call", "is", "repeated", "until", "the", "timer", "is", "stopped", "." ]
def repeatCall(period,callback): """ Repeat a function call. The call is repeated until the timer is stopped. Remember to keep a reference to the timer this function returns. If you do not python will delete the timer prematurely which may case a segfault. @param period: Period between calls in milliseconds. @param callback: The function to call. @return: The timer. @rtype: L{Timer} """ timer = Timer(period, callback, 0) timer.start() return timer
[ "def", "repeatCall", "(", "period", ",", "callback", ")", ":", "timer", "=", "Timer", "(", "period", ",", "callback", ",", "0", ")", "timer", ".", "start", "(", ")", "return", "timer" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/fife_timer.py#L220-L235
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/ls_helper.py
python
PrintNewLine
()
Default function for printing new lines between directories.
Default function for printing new lines between directories.
[ "Default", "function", "for", "printing", "new", "lines", "between", "directories", "." ]
def PrintNewLine(): """Default function for printing new lines between directories.""" print
[ "def", "PrintNewLine", "(", ")", ":", "print" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/ls_helper.py#L27-L29
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/ext.py
python
Extension.parse
(self, parser)
If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
[ "If", "any", "of", "the", ":", "attr", ":", "tags", "matched", "this", "method", "is", "called", "with", "the", "parser", "as", "first", "argument", ".", "The", "token", "the", "parser", "stream", "is", "pointing", "at", "is", "the", "name", "token", "...
def parse(self, parser): """If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes. """ raise NotImplementedError()
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/ext.py#L99-L105
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/controls/PhysicsWalker.py
python
PhysicsWalker.initializeCollisions
(self, collisionTraverser, avatarNodePath, wallBitmask, floorBitmask, avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0)
Set up the avatar collisions
Set up the avatar collisions
[ "Set", "up", "the", "avatar", "collisions" ]
def initializeCollisions(self, collisionTraverser, avatarNodePath, wallBitmask, floorBitmask, avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0): """ Set up the avatar collisions """ assert self.debugPrint("initializeCollisions()") assert not avatarNodePath.isEmpty() self.cTrav = collisionTraverser self.floorOffset = floorOffset = 7.0 self.avatarNodePath = self.setupPhysics(avatarNodePath) if self.useHeightRay: #self.setupRay(floorBitmask, avatarRadius) self.setupRay(floorBitmask, 0.0) self.setupSphere(wallBitmask|floorBitmask, avatarRadius) self.setCollisionsActive(1)
[ "def", "initializeCollisions", "(", "self", ",", "collisionTraverser", ",", "avatarNodePath", ",", "wallBitmask", ",", "floorBitmask", ",", "avatarRadius", "=", "1.4", ",", "floorOffset", "=", "1.0", ",", "reach", "=", "1.0", ")", ":", "assert", "self", ".", ...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/controls/PhysicsWalker.py#L225-L244
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/tracking/base.py
python
CheckpointPosition._queue_slot_variable_for_restoration
(self, optimizer_object, variable, slot_variable_id, slot_name)
Adds a slot variable onto the restoration queue. See comment on slot_restoration_tensor_saveables in _CheckpointRestoreCoordinator.__init__ for more information. Args: optimizer_object: Optimizer that owns the slot variable. variable: Variable associated with the slot variable. slot_variable_id: ID of the slot variable. slot_name: Name of the slot variable.
Adds a slot variable onto the restoration queue.
[ "Adds", "a", "slot", "variable", "onto", "the", "restoration", "queue", "." ]
def _queue_slot_variable_for_restoration(self, optimizer_object, variable, slot_variable_id, slot_name): """Adds a slot variable onto the restoration queue. See comment on slot_restoration_tensor_saveables in _CheckpointRestoreCoordinator.__init__ for more information. Args: optimizer_object: Optimizer that owns the slot variable. variable: Variable associated with the slot variable. slot_variable_id: ID of the slot variable. slot_name: Name of the slot variable. """ slot_variable_position = CheckpointPosition( checkpoint=self.checkpoint, proto_id=slot_variable_id) # pylint: disable=protected-access slot_variable = optimizer_object._create_or_restore_slot_variable( slot_variable_position=slot_variable_position, variable=variable, slot_name=slot_name) # pylint: enable=protected-access if slot_variable is None: # The optimizer returns None if the restore should not be done (yet). return self.checkpoint.all_python_objects.add(slot_variable) self.checkpoint.matched_proto_ids.add(slot_variable_position.proto_id) self.checkpoint.object_by_proto_id[slot_variable_id] = slot_variable # pylint: disable=protected-access slot_variable._maybe_initialize_trackable() slot_variable._self_update_uid = self.checkpoint.restore_uid # pylint: enable=protected-access # Since this is a slot variable, there will be no new python_saveables, so # ignore that return value. new_restore_ops, new_tensor_saveables, _ = ( slot_variable_position.gather_ops_or_named_saveables()) self.checkpoint.new_restore_ops(new_restore_ops) self.checkpoint.slot_restoration_tensor_saveables.update( new_tensor_saveables)
[ "def", "_queue_slot_variable_for_restoration", "(", "self", ",", "optimizer_object", ",", "variable", ",", "slot_variable_id", ",", "slot_name", ")", ":", "slot_variable_position", "=", "CheckpointPosition", "(", "checkpoint", "=", "self", ".", "checkpoint", ",", "pro...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/tracking/base.py#L540-L577
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/utils/units.py
python
unit_to_internal
(family, unit, number)
return number*UnitMap[family][base]*UnitPrefix[prefix]
Converts a number of given dimensions and units into internal units. Args: family: The dimensionality of the number. unit: The units 'number' is originally in. number: The value of the parameter in the units 'unit'. Returns: The number in internal units. Raises: ValueError: Raised if the user specified units aren't given in the UnitMap dictionary. IndexError: Raised if the programmer specified dimensionality for the parameter isn't in UnitMap. Shouldn't happen, for obvious reasons. TypeError: Raised if the prefix is correct, but the base unit is not, in the user specified unit string.
Converts a number of given dimensions and units into internal units.
[ "Converts", "a", "number", "of", "given", "dimensions", "and", "units", "into", "internal", "units", "." ]
def unit_to_internal(family, unit, number): """Converts a number of given dimensions and units into internal units. Args: family: The dimensionality of the number. unit: The units 'number' is originally in. number: The value of the parameter in the units 'unit'. Returns: The number in internal units. Raises: ValueError: Raised if the user specified units aren't given in the UnitMap dictionary. IndexError: Raised if the programmer specified dimensionality for the parameter isn't in UnitMap. Shouldn't happen, for obvious reasons. TypeError: Raised if the prefix is correct, but the base unit is not, in the user specified unit string. """ if not (family == "number" or family in UnitMap): raise IndexError(family + " is an undefined units kind.") if family == "number": return number if unit == "": prefix = "" base = "" else: m = UnitPrefixRE.match(unit); if m is None: raise ValueError("Unit " + unit + " is not structured with a prefix+base syntax.") prefix = m.group(1) base = m.group(2) if not prefix in UnitPrefix: raise TypeError(prefix + " is not a valid unit prefix.") if not base in UnitMap[family]: raise TypeError(base + " is an undefined unit for kind " + family + ".") return number*UnitMap[family][base]*UnitPrefix[prefix]
[ "def", "unit_to_internal", "(", "family", ",", "unit", ",", "number", ")", ":", "if", "not", "(", "family", "==", "\"number\"", "or", "family", "in", "UnitMap", ")", ":", "raise", "IndexError", "(", "family", "+", "\" is an undefined units kind.\"", ")", "if...
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/utils/units.py#L303-L344
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/package_index.py
python
find_external_links
(url, page)
Find rel="homepage" and rel="download" links in `page`, yielding URLs
Find rel="homepage" and rel="download" links in `page`, yielding URLs
[ "Find", "rel", "=", "homepage", "and", "rel", "=", "download", "links", "in", "page", "yielding", "URLs" ]
def find_external_links(url, page): """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" for match in REL.finditer(page): tag, rel = match.groups() rels = set(map(str.strip, rel.lower().split(','))) if 'homepage' in rels or 'download' in rels: for match in HREF.finditer(tag): yield urljoin(url, htmldecode(match.group(1))) for tag in ("<th>Home Page", "<th>Download URL"): pos = page.find(tag) if pos!=-1: match = HREF.search(page,pos) if match: yield urljoin(url, htmldecode(match.group(1)))
[ "def", "find_external_links", "(", "url", ",", "page", ")", ":", "for", "match", "in", "REL", ".", "finditer", "(", "page", ")", ":", "tag", ",", "rel", "=", "match", ".", "groups", "(", ")", "rels", "=", "set", "(", "map", "(", "str", ".", "stri...
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#L183-L198
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/dashboard/controllers/_helpers.py
python
_get_function_params
(func)
return func_params
Retrieves the list of parameters declared in function. Each parameter is represented as dict with keys: * name (str): the name of the parameter * required (bool): whether the parameter is required or not * default (obj): the parameter's default value
Retrieves the list of parameters declared in function. Each parameter is represented as dict with keys: * name (str): the name of the parameter * required (bool): whether the parameter is required or not * default (obj): the parameter's default value
[ "Retrieves", "the", "list", "of", "parameters", "declared", "in", "function", ".", "Each", "parameter", "is", "represented", "as", "dict", "with", "keys", ":", "*", "name", "(", "str", ")", ":", "the", "name", "of", "the", "parameter", "*", "required", "...
def _get_function_params(func): """ Retrieves the list of parameters declared in function. Each parameter is represented as dict with keys: * name (str): the name of the parameter * required (bool): whether the parameter is required or not * default (obj): the parameter's default value """ fspec = getargspec(func) func_params = [] nd = len(fspec.args) if not fspec.defaults else -len(fspec.defaults) for param in fspec.args[1:nd]: func_params.append({'name': param, 'required': True}) if fspec.defaults: for param, val in zip(fspec.args[nd:], fspec.defaults): func_params.append({ 'name': param, 'required': False, 'default': val }) return func_params
[ "def", "_get_function_params", "(", "func", ")", ":", "fspec", "=", "getargspec", "(", "func", ")", "func_params", "=", "[", "]", "nd", "=", "len", "(", "fspec", ".", "args", ")", "if", "not", "fspec", ".", "defaults", "else", "-", "len", "(", "fspec...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/dashboard/controllers/_helpers.py#L19-L42
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/lib/hl_api_nodes.py
python
Create
(model, n=1, params=None, positions=None)
return node_ids
Create one or more nodes. Generates `n` new network objects of the supplied model type. If `n` is not given, a single node is created. Note that if setting parameters of the nodes fail, the nodes will still have been created. Parameters ---------- model : str Name of the model to create n : int, optional Number of nodes to create params : dict or list, optional Parameters for the new nodes. Can be any of the following: - A dictionary with either single values or lists of size n. The single values will be applied to all nodes, while the lists will be distributed across the nodes. Both single values and lists can be given at the same time. - A list with n dictionaries, one dictionary for each node. Values may be :py:class:`.Parameter` objects. If omitted, the model's defaults are used. positions: :py:class:`.spatial.grid` or :py:class:`.spatial.free` object, optional Object describing spatial positions of the nodes. If omitted, the nodes have no spatial attachment. Returns ------- NodeCollection: Object representing the IDs of created nodes, see :py:class:`.NodeCollection` for more. Raises ------ NESTError If setting node parameters fail. However, the nodes will still have been created. TypeError If the positions object is of wrong type.
Create one or more nodes.
[ "Create", "one", "or", "more", "nodes", "." ]
def Create(model, n=1, params=None, positions=None): """Create one or more nodes. Generates `n` new network objects of the supplied model type. If `n` is not given, a single node is created. Note that if setting parameters of the nodes fail, the nodes will still have been created. Parameters ---------- model : str Name of the model to create n : int, optional Number of nodes to create params : dict or list, optional Parameters for the new nodes. Can be any of the following: - A dictionary with either single values or lists of size n. The single values will be applied to all nodes, while the lists will be distributed across the nodes. Both single values and lists can be given at the same time. - A list with n dictionaries, one dictionary for each node. Values may be :py:class:`.Parameter` objects. If omitted, the model's defaults are used. positions: :py:class:`.spatial.grid` or :py:class:`.spatial.free` object, optional Object describing spatial positions of the nodes. If omitted, the nodes have no spatial attachment. Returns ------- NodeCollection: Object representing the IDs of created nodes, see :py:class:`.NodeCollection` for more. Raises ------ NESTError If setting node parameters fail. However, the nodes will still have been created. TypeError If the positions object is of wrong type. """ model_deprecation_warning(model) if positions is not None: # Explicitly retrieve lazy loaded spatial property from the module class. # This is needed because the automatic lookup fails. See #2135. spatial = getattr(nest.NestModule, "spatial") # We only accept positions as either a free object or a grid object. if not isinstance(positions, (spatial.free, spatial.grid)): raise TypeError('`positions` must be either a nest.spatial.free or a nest.spatial.grid object') layer_specs = {'elements': model} layer_specs['edge_wrap'] = positions.edge_wrap if isinstance(positions, spatial.free): layer_specs['positions'] = positions.pos # If the positions are based on a parameter object, the number of nodes must be specified. if isinstance(positions.pos, Parameter): layer_specs['n'] = n else: # If positions is not a free object, it must be a grid object. if n > 1: raise kernel.NESTError('Cannot specify number of nodes with grid positions') layer_specs['shape'] = positions.shape if positions.center is not None: layer_specs['center'] = positions.center if positions.extent is not None: layer_specs['extent'] = positions.extent # For compatibility with SLI. if params is None: params = {} layer = sli_func('CreateLayerParams', layer_specs, params) return layer # If any of the elements in the parameter dictionary is either an array-like object, # or a NEST parameter, we create the nodes first, then set the given values. If not, # we can pass the parameter specification to SLI when the nodes are created. iterable_or_parameter_in_params = True if isinstance(params, dict) and params: # if params is a dict and not empty iterable_or_parameter_in_params = any(is_iterable(v) or isinstance(v, Parameter) for k, v in params.items()) if not iterable_or_parameter_in_params: cmd = "/%s 3 1 roll exch Create" % model sps(params) else: cmd = "/%s exch Create" % model sps(n) sr(cmd) node_ids = spp() if params is not None and iterable_or_parameter_in_params: try: SetStatus(node_ids, params) except Exception: warnings.warn( "SetStatus() call failed, but nodes have already been " + "created! The node IDs of the new nodes are: {0}.".format(node_ids)) raise return node_ids
[ "def", "Create", "(", "model", ",", "n", "=", "1", ",", "params", "=", "None", ",", "positions", "=", "None", ")", ":", "model_deprecation_warning", "(", "model", ")", "if", "positions", "is", "not", "None", ":", "# Explicitly retrieve lazy loaded spatial prop...
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/lib/hl_api_nodes.py#L44-L142
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/activex/activex.py
python
ActiveXWindow.GetAXMethodDesc
(*args)
return _activex.ActiveXWindow_GetAXMethodDesc(*args)
GetAXMethodDesc(self, int idx) -> FuncX GetAXMethodDesc(self, String name) -> FuncX
GetAXMethodDesc(self, int idx) -> FuncX GetAXMethodDesc(self, String name) -> FuncX
[ "GetAXMethodDesc", "(", "self", "int", "idx", ")", "-", ">", "FuncX", "GetAXMethodDesc", "(", "self", "String", "name", ")", "-", ">", "FuncX" ]
def GetAXMethodDesc(*args): """ GetAXMethodDesc(self, int idx) -> FuncX GetAXMethodDesc(self, String name) -> FuncX """ return _activex.ActiveXWindow_GetAXMethodDesc(*args)
[ "def", "GetAXMethodDesc", "(", "*", "args", ")", ":", "return", "_activex", ".", "ActiveXWindow_GetAXMethodDesc", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/activex/activex.py#L276-L281
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/options.py
python
conv_float2negexp
(val)
return -1 * int(math.floor(math.log(val, 10)))
Returns the least restrictive negative exponent of the power 10 that would achieve the floating point convergence criterium *val*.
Returns the least restrictive negative exponent of the power 10 that would achieve the floating point convergence criterium *val*.
[ "Returns", "the", "least", "restrictive", "negative", "exponent", "of", "the", "power", "10", "that", "would", "achieve", "the", "floating", "point", "convergence", "criterium", "*", "val", "*", "." ]
def conv_float2negexp(val): """Returns the least restrictive negative exponent of the power 10 that would achieve the floating point convergence criterium *val*. """ return -1 * int(math.floor(math.log(val, 10)))
[ "def", "conv_float2negexp", "(", "val", ")", ":", "return", "-", "1", "*", "int", "(", "math", ".", "floor", "(", "math", ".", "log", "(", "val", ",", "10", ")", ")", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/options.py#L270-L275
scylladb/seastar
0cdd2329beb1cc4c0af8828598c26114397ffa9c
scripts/perftune.py
python
PerfTunerBase.mode
(self, new_mode)
Set the new configuration mode and recalculate the corresponding masks.
Set the new configuration mode and recalculate the corresponding masks.
[ "Set", "the", "new", "configuration", "mode", "and", "recalculate", "the", "corresponding", "masks", "." ]
def mode(self, new_mode): """ Set the new configuration mode and recalculate the corresponding masks. """ # Make sure the new_mode is of PerfTunerBase.AllowedModes type self.__mode = PerfTunerBase.SupportedModes(new_mode) self.__compute_cpu_mask = PerfTunerBase.compute_cpu_mask_for_mode(self.__mode, self.__args.cpu_mask) self.__irq_cpu_mask = PerfTunerBase.irqs_cpu_mask_for_mode(self.__mode, self.__args.cpu_mask)
[ "def", "mode", "(", "self", ",", "new_mode", ")", ":", "# Make sure the new_mode is of PerfTunerBase.AllowedModes type", "self", ".", "__mode", "=", "PerfTunerBase", ".", "SupportedModes", "(", "new_mode", ")", "self", ".", "__compute_cpu_mask", "=", "PerfTunerBase", ...
https://github.com/scylladb/seastar/blob/0cdd2329beb1cc4c0af8828598c26114397ffa9c/scripts/perftune.py#L366-L373
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
docs/conf.py
python
EnumAttributeDocumenter.add_directive_header
(self, sig)
Greatly simplified AttributeDocumenter.add_directive_header() as we know we're dealing with only specific enums here, we can append a line of doc with just their value.
Greatly simplified AttributeDocumenter.add_directive_header() as we know we're dealing with only specific enums here, we can append a line of doc with just their value.
[ "Greatly", "simplified", "AttributeDocumenter", ".", "add_directive_header", "()", "as", "we", "know", "we", "re", "dealing", "with", "only", "specific", "enums", "here", "we", "can", "append", "a", "line", "of", "doc", "with", "just", "their", "value", "." ]
def add_directive_header(self, sig): """Greatly simplified AttributeDocumenter.add_directive_header() as we know we're dealing with only specific enums here, we can append a line of doc with just their value. """ super(AttributeDocumenter, self).add_directive_header(sig)
[ "def", "add_directive_header", "(", "self", ",", "sig", ")", ":", "super", "(", "AttributeDocumenter", ",", "self", ")", ".", "add_directive_header", "(", "sig", ")" ]
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/conf.py#L321-L326
kevinlin311tw/caffe-cvprw15
45c2a1bf0368569c54e0be4edf8d34285cf79e70
scripts/cpp_lint.py
python
_CppLintState.ResetErrorCounts
(self)
Sets the module's error statistic back to zero.
Sets the module's error statistic back to zero.
[ "Sets", "the", "module", "s", "error", "statistic", "back", "to", "zero", "." ]
def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {}
[ "def", "ResetErrorCounts", "(", "self", ")", ":", "self", ".", "error_count", "=", "0", "self", ".", "errors_by_category", "=", "{", "}" ]
https://github.com/kevinlin311tw/caffe-cvprw15/blob/45c2a1bf0368569c54e0be4edf8d34285cf79e70/scripts/cpp_lint.py#L742-L745
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Entry.__init__
(self, master=None, cnf={}, **kw)
Construct an entry widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, invalidcommand, invcmd, justify, relief, selectbackground, selectborderwidth, selectforeground, show, state, takefocus, textvariable, validate, validatecommand, vcmd, width, xscrollcommand.
Construct an entry widget with the parent MASTER.
[ "Construct", "an", "entry", "widget", "with", "the", "parent", "MASTER", "." ]
def __init__(self, master=None, cnf={}, **kw): """Construct an entry widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, invalidcommand, invcmd, justify, relief, selectbackground, selectborderwidth, selectforeground, show, state, takefocus, textvariable, validate, validatecommand, vcmd, width, xscrollcommand.""" Widget.__init__(self, master, 'entry', cnf, kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "'entry'", ",", "cnf", ",", "kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2665-L2676
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
RasterAttributeTable.GetTableType
(self, *args)
return _gdal.RasterAttributeTable_GetTableType(self, *args)
r"""GetTableType(RasterAttributeTable self) -> GDALRATTableType
r"""GetTableType(RasterAttributeTable self) -> GDALRATTableType
[ "r", "GetTableType", "(", "RasterAttributeTable", "self", ")", "-", ">", "GDALRATTableType" ]
def GetTableType(self, *args): r"""GetTableType(RasterAttributeTable self) -> GDALRATTableType""" return _gdal.RasterAttributeTable_GetTableType(self, *args)
[ "def", "GetTableType", "(", "self", ",", "*", "args", ")", ":", "return", "_gdal", ".", "RasterAttributeTable_GetTableType", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3894-L3896
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/failure_handling/failure_handling.py
python
_mwms_write_checkpoint_dir
(checkpoint_dir, task_type, task_id, cluster_spec)
return os.path.join(dirpath, base)
Returns checkpoint_dir for chief and a temp dir for any other worker.
Returns checkpoint_dir for chief and a temp dir for any other worker.
[ "Returns", "checkpoint_dir", "for", "chief", "and", "a", "temp", "dir", "for", "any", "other", "worker", "." ]
def _mwms_write_checkpoint_dir(checkpoint_dir, task_type, task_id, cluster_spec): """Returns checkpoint_dir for chief and a temp dir for any other worker.""" dirpath = os.path.dirname(checkpoint_dir) base = os.path.basename(checkpoint_dir) if not multi_worker_util.is_chief( cluster_spec=cluster_spec, task_type=task_type, task_id=task_id): base_dirpath = 'workertemp_' + str(task_id) dirpath = os.path.join(dirpath, base_dirpath) gfile.MakeDirs(dirpath) return os.path.join(dirpath, base)
[ "def", "_mwms_write_checkpoint_dir", "(", "checkpoint_dir", ",", "task_type", ",", "task_id", ",", "cluster_spec", ")", ":", "dirpath", "=", "os", ".", "path", ".", "dirname", "(", "checkpoint_dir", ")", "base", "=", "os", ".", "path", ".", "basename", "(", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/failure_handling/failure_handling.py#L44-L54
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Window.GetPositionTuple
(*args, **kwargs)
return _core_.Window_GetPositionTuple(*args, **kwargs)
GetPositionTuple() -> (x,y) Get the window's position. Notice that the position is in client coordinates for child windows and screen coordinates for the top level ones, use `GetScreenPosition` if you need screen coordinates for all kinds of windows.
GetPositionTuple() -> (x,y)
[ "GetPositionTuple", "()", "-", ">", "(", "x", "y", ")" ]
def GetPositionTuple(*args, **kwargs): """ GetPositionTuple() -> (x,y) Get the window's position. Notice that the position is in client coordinates for child windows and screen coordinates for the top level ones, use `GetScreenPosition` if you need screen coordinates for all kinds of windows. """ return _core_.Window_GetPositionTuple(*args, **kwargs)
[ "def", "GetPositionTuple", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetPositionTuple", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L9465-L9474
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/index.py
python
PackageIndex.download_file
(self, url, destfile, digest=None, reporthook=None)
This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere). The method is just like the :func:`urlretrieve` function in the standard library, except that it allows digest computation to be done during download and checking that the downloaded data matched any expected value. :param url: The URL of the file to be downloaded (assumed to be available via an HTTP GET request). :param destfile: The pathname where the downloaded file is to be saved. :param digest: If specified, this must be a (hasher, value) tuple, where hasher is the algorithm used (e.g. ``'md5'``) and ``value`` is the expected value. :param reporthook: The same as for :func:`urlretrieve` in the standard library.
This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere).
[ "This", "is", "a", "convenience", "method", "for", "downloading", "a", "file", "from", "an", "URL", ".", "Normally", "this", "will", "be", "a", "file", "from", "the", "index", "though", "currently", "no", "check", "is", "made", "for", "this", "(", "i", ...
def download_file(self, url, destfile, digest=None, reporthook=None): """ This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere). The method is just like the :func:`urlretrieve` function in the standard library, except that it allows digest computation to be done during download and checking that the downloaded data matched any expected value. :param url: The URL of the file to be downloaded (assumed to be available via an HTTP GET request). :param destfile: The pathname where the downloaded file is to be saved. :param digest: If specified, this must be a (hasher, value) tuple, where hasher is the algorithm used (e.g. ``'md5'``) and ``value`` is the expected value. :param reporthook: The same as for :func:`urlretrieve` in the standard library. """ if digest is None: digester = None logger.debug('No digest specified') else: if isinstance(digest, (list, tuple)): hasher, digest = digest else: hasher = 'md5' digester = getattr(hashlib, hasher)() logger.debug('Digest specified: %s' % digest) # The following code is equivalent to urlretrieve. # We need to do it this way so that we can compute the # digest of the file as we go. with open(destfile, 'wb') as dfp: # addinfourl is not a context manager on 2.x # so we have to use try/finally sfp = self.send_request(Request(url)) try: headers = sfp.info() blocksize = 8192 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, blocksize, size) while True: block = sfp.read(blocksize) if not block: break read += len(block) dfp.write(block) if digester: digester.update(block) blocknum += 1 if reporthook: reporthook(blocknum, blocksize, size) finally: sfp.close() # check that we got the whole file, if we can if size >= 0 and read < size: raise DistlibException( 'retrieval incomplete: got only %d out of %d bytes' % (read, size)) # if we have a digest, it must match. if digester: actual = digester.hexdigest() if digest != actual: raise DistlibException('%s digest mismatch for %s: expected ' '%s, got %s' % (hasher, destfile, digest, actual)) logger.debug('Digest verified: %s', digest)
[ "def", "download_file", "(", "self", ",", "url", ",", "destfile", ",", "digest", "=", "None", ",", "reporthook", "=", "None", ")", ":", "if", "digest", "is", "None", ":", "digester", "=", "None", "logger", ".", "debug", "(", "'No digest specified'", ")",...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/index.py#L372-L447
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/_type_aliases.py
python
bitname
(obj)
return base, bits, char
Return a bit-width name for a given type object
Return a bit-width name for a given type object
[ "Return", "a", "bit", "-", "width", "name", "for", "a", "given", "type", "object" ]
def bitname(obj): """Return a bit-width name for a given type object""" bits = _bits_of(obj) dt = dtype(obj) char = dt.kind base = _kind_name(dt) if base == 'object': bits = 0 if bits != 0: char = "%s%d" % (char, bits // 8) return base, bits, char
[ "def", "bitname", "(", "obj", ")", ":", "bits", "=", "_bits_of", "(", "obj", ")", "dt", "=", "dtype", "(", "obj", ")", "char", "=", "dt", ".", "kind", "base", "=", "_kind_name", "(", "dt", ")", "if", "base", "==", "'object'", ":", "bits", "=", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/_type_aliases.py#L79-L92
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/tablez.py
python
TablesHandler.on_mouse_button_clicked_treeview_table
(self, widget, event, anchor)
return False
Catches mouse buttons clicks
Catches mouse buttons clicks
[ "Catches", "mouse", "buttons", "clicks" ]
def on_mouse_button_clicked_treeview_table(self, widget, event, anchor): """Catches mouse buttons clicks""" self.curr_table_anchor = anchor self.dad.object_set_selection(self.curr_table_anchor) if event.button == 3: menu_table = gtk.Menu() self.dad.menu_populate_popup(menu_table, menus.get_popup_menu_table(self.dad)) menu_table.popup(None, None, None, event.button, event.time) return True return False
[ "def", "on_mouse_button_clicked_treeview_table", "(", "self", ",", "widget", ",", "event", ",", "anchor", ")", ":", "self", ".", "curr_table_anchor", "=", "anchor", "self", ".", "dad", ".", "object_set_selection", "(", "self", ".", "curr_table_anchor", ")", "if"...
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/tablez.py#L643-L652
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/stats.py
python
friedmanchisquare
(*args)
return FriedmanchisquareResult(chisq, distributions.chi2.sf(chisq, k - 1))
Computes the Friedman test for repeated measurements The Friedman test tests the null hypothesis that repeated measurements of the same individuals have the same distribution. It is often used to test for consistency among measurements obtained in different ways. For example, if two measurement techniques are used on the same set of individuals, the Friedman test can be used to determine if the two measurement techniques are consistent. Parameters ---------- measurements1, measurements2, measurements3... : array_like Arrays of measurements. All of the arrays must have the same number of elements. At least 3 sets of measurements must be given. Returns ------- statistic : float the test statistic, correcting for ties pvalue : float the associated p-value assuming that the test statistic has a chi squared distribution Notes ----- Due to the assumption that the test statistic has a chi squared distribution, the p-value is only reliable for n > 10 and more than 6 repeated measurements. References ---------- .. [1] http://en.wikipedia.org/wiki/Friedman_test
Computes the Friedman test for repeated measurements
[ "Computes", "the", "Friedman", "test", "for", "repeated", "measurements" ]
def friedmanchisquare(*args): """ Computes the Friedman test for repeated measurements The Friedman test tests the null hypothesis that repeated measurements of the same individuals have the same distribution. It is often used to test for consistency among measurements obtained in different ways. For example, if two measurement techniques are used on the same set of individuals, the Friedman test can be used to determine if the two measurement techniques are consistent. Parameters ---------- measurements1, measurements2, measurements3... : array_like Arrays of measurements. All of the arrays must have the same number of elements. At least 3 sets of measurements must be given. Returns ------- statistic : float the test statistic, correcting for ties pvalue : float the associated p-value assuming that the test statistic has a chi squared distribution Notes ----- Due to the assumption that the test statistic has a chi squared distribution, the p-value is only reliable for n > 10 and more than 6 repeated measurements. References ---------- .. [1] http://en.wikipedia.org/wiki/Friedman_test """ k = len(args) if k < 3: raise ValueError('\nLess than 3 levels. Friedman test not appropriate.\n') n = len(args[0]) for i in range(1, k): if len(args[i]) != n: raise ValueError('Unequal N in friedmanchisquare. Aborting.') # Rank data data = np.vstack(args).T data = data.astype(float) for i in range(len(data)): data[i] = rankdata(data[i]) # Handle ties ties = 0 for i in range(len(data)): replist, repnum = find_repeats(array(data[i])) for t in repnum: ties += t * (t*t - 1) c = 1 - ties / float(k*(k*k - 1)*n) ssbn = np.sum(data.sum(axis=0)**2) chisq = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c return FriedmanchisquareResult(chisq, distributions.chi2.sf(chisq, k - 1))
[ "def", "friedmanchisquare", "(", "*", "args", ")", ":", "k", "=", "len", "(", "args", ")", "if", "k", "<", "3", ":", "raise", "ValueError", "(", "'\\nLess than 3 levels. Friedman test not appropriate.\\n'", ")", "n", "=", "len", "(", "args", "[", "0", "]"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L4874-L4936
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/filter_design.py
python
freqs_zpk
(z, p, k, worN=200)
return w, h
Compute frequency response of analog filter. Given the zeros `z`, poles `p`, and gain `k` of a filter, compute its frequency response:: (jw-z[0]) * (jw-z[1]) * ... * (jw-z[-1]) H(w) = k * ---------------------------------------- (jw-p[0]) * (jw-p[1]) * ... * (jw-p[-1]) Parameters ---------- z : array_like Zeroes of a linear filter p : array_like Poles of a linear filter k : scalar Gain of a linear filter worN : {None, int, array_like}, optional If None, then compute at 200 frequencies around the interesting parts of the response curve (determined by pole-zero locations). If a single integer, then compute at that many frequencies. Otherwise, compute the response at the angular frequencies (e.g. rad/s) given in `worN`. Returns ------- w : ndarray The angular frequencies at which `h` was computed. h : ndarray The frequency response. See Also -------- freqs : Compute the frequency response of an analog filter in TF form freqz : Compute the frequency response of a digital filter in TF form freqz_zpk : Compute the frequency response of a digital filter in ZPK form Notes ----- .. versionadded:: 0.19.0 Examples -------- >>> from scipy.signal import freqs_zpk, iirfilter >>> z, p, k = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1', ... output='zpk') >>> w, h = freqs_zpk(z, p, k, worN=np.logspace(-1, 2, 1000)) >>> import matplotlib.pyplot as plt >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.xlabel('Frequency') >>> plt.ylabel('Amplitude response [dB]') >>> plt.grid() >>> plt.show()
Compute frequency response of analog filter.
[ "Compute", "frequency", "response", "of", "analog", "filter", "." ]
def freqs_zpk(z, p, k, worN=200): """ Compute frequency response of analog filter. Given the zeros `z`, poles `p`, and gain `k` of a filter, compute its frequency response:: (jw-z[0]) * (jw-z[1]) * ... * (jw-z[-1]) H(w) = k * ---------------------------------------- (jw-p[0]) * (jw-p[1]) * ... * (jw-p[-1]) Parameters ---------- z : array_like Zeroes of a linear filter p : array_like Poles of a linear filter k : scalar Gain of a linear filter worN : {None, int, array_like}, optional If None, then compute at 200 frequencies around the interesting parts of the response curve (determined by pole-zero locations). If a single integer, then compute at that many frequencies. Otherwise, compute the response at the angular frequencies (e.g. rad/s) given in `worN`. Returns ------- w : ndarray The angular frequencies at which `h` was computed. h : ndarray The frequency response. See Also -------- freqs : Compute the frequency response of an analog filter in TF form freqz : Compute the frequency response of a digital filter in TF form freqz_zpk : Compute the frequency response of a digital filter in ZPK form Notes ----- .. versionadded:: 0.19.0 Examples -------- >>> from scipy.signal import freqs_zpk, iirfilter >>> z, p, k = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1', ... output='zpk') >>> w, h = freqs_zpk(z, p, k, worN=np.logspace(-1, 2, 1000)) >>> import matplotlib.pyplot as plt >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.xlabel('Frequency') >>> plt.ylabel('Amplitude response [dB]') >>> plt.grid() >>> plt.show() """ k = np.asarray(k) if k.size > 1: raise ValueError('k must be a single scalar gain') if worN is None: # For backwards compatibility w = findfreqs(z, p, 200, kind='zp') elif _is_int_type(worN): w = findfreqs(z, p, worN, kind='zp') else: w = worN w = atleast_1d(w) s = 1j * w num = polyvalfromroots(s, z) den = polyvalfromroots(s, p) h = k * num/den return w, h
[ "def", "freqs_zpk", "(", "z", ",", "p", ",", "k", ",", "worN", "=", "200", ")", ":", "k", "=", "np", ".", "asarray", "(", "k", ")", "if", "k", ".", "size", ">", "1", ":", "raise", "ValueError", "(", "'k must be a single scalar gain'", ")", "if", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/filter_design.py#L196-L272
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/polynomial/chebyshev.py
python
chebadd
(c1, c2)
return pu.trimseq(ret)
Add one Chebyshev series to another. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-d arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Chebyshev series of their sum. See Also -------- chebsub, chebmul, chebdiv, chebpow Notes ----- Unlike multiplication, division, etc., the sum of two Chebyshev series is a Chebyshev series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebadd(c1,c2) array([ 4., 4., 4.])
Add one Chebyshev series to another.
[ "Add", "one", "Chebyshev", "series", "to", "another", "." ]
def chebadd(c1, c2): """ Add one Chebyshev series to another. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-d arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Chebyshev series of their sum. See Also -------- chebsub, chebmul, chebdiv, chebpow Notes ----- Unlike multiplication, division, etc., the sum of two Chebyshev series is a Chebyshev series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebadd(c1,c2) array([ 4., 4., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] += c2 ret = c1 else : c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret)
[ "def", "chebadd", "(", "c1", ",", "c2", ")", ":", "# c1, c2 are trimmed copies", "[", "c1", ",", "c2", "]", "=", "pu", ".", "as_series", "(", "[", "c1", ",", "c2", "]", ")", "if", "len", "(", "c1", ")", ">", "len", "(", "c2", ")", ":", "c1", ...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/chebyshev.py#L534-L581
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/query.py
python
Query.entry_ok
(self)
return entry
Return non-blank entry or None.
Return non-blank entry or None.
[ "Return", "non", "-", "blank", "entry", "or", "None", "." ]
def entry_ok(self): # Example: usually replace. "Return non-blank entry or None." entry = self.entry.get().strip() if not entry: self.showerror('blank line.') return None return entry
[ "def", "entry_ok", "(", "self", ")", ":", "# Example: usually replace.", "entry", "=", "self", ".", "entry", ".", "get", "(", ")", ".", "strip", "(", ")", "if", "not", "entry", ":", "self", ".", "showerror", "(", "'blank line.'", ")", "return", "None", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/query.py#L134-L140
GrammaTech/gtirb
415dd72e1e3c475004d013723c16cdcb29c0826e
python/gtirb/symbolicexpression.py
python
SymbolicExpression.symbols
(self)
Get all the symbols involved with this symbolic expression, regardless of role.
Get all the symbols involved with this symbolic expression, regardless of role.
[ "Get", "all", "the", "symbols", "involved", "with", "this", "symbolic", "expression", "regardless", "of", "role", "." ]
def symbols(self) -> typing.Iterable[Symbol]: """Get all the symbols involved with this symbolic expression, regardless of role. """ raise NotImplementedError
[ "def", "symbols", "(", "self", ")", "->", "typing", ".", "Iterable", "[", "Symbol", "]", ":", "raise", "NotImplementedError" ]
https://github.com/GrammaTech/gtirb/blob/415dd72e1e3c475004d013723c16cdcb29c0826e/python/gtirb/symbolicexpression.py#L65-L70
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pubsub/core/topictreetraverser.py
python
ITopicTreeVisitor._accept
(self, topicObj)
return True
Override this to filter nodes of topic tree. Must return True (accept node) of False (reject node). Note that rejected nodes cause traversal to move to next branch (no children traversed).
Override this to filter nodes of topic tree. Must return True (accept node) of False (reject node). Note that rejected nodes cause traversal to move to next branch (no children traversed).
[ "Override", "this", "to", "filter", "nodes", "of", "topic", "tree", ".", "Must", "return", "True", "(", "accept", "node", ")", "of", "False", "(", "reject", "node", ")", ".", "Note", "that", "rejected", "nodes", "cause", "traversal", "to", "move", "to", ...
def _accept(self, topicObj): """Override this to filter nodes of topic tree. Must return True (accept node) of False (reject node). Note that rejected nodes cause traversal to move to next branch (no children traversed).""" return True
[ "def", "_accept", "(", "self", ",", "topicObj", ")", ":", "return", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/topictreetraverser.py#L113-L118
learnforpractice/pyeos
4f04eb982c86c1fdb413084af77c713a6fda3070
libraries/vm/vm_cpython_ss/lib/codecs.py
python
StreamReader.seek
(self, offset, whence=0)
Set the input stream's current position. Resets the codec buffers used for keeping state.
Set the input stream's current position.
[ "Set", "the", "input", "stream", "s", "current", "position", "." ]
def seek(self, offset, whence=0): """ Set the input stream's current position. Resets the codec buffers used for keeping state. """ self.stream.seek(offset, whence) self.reset()
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "self", ".", "stream", ".", "seek", "(", "offset", ",", "whence", ")", "self", ".", "reset", "(", ")" ]
https://github.com/learnforpractice/pyeos/blob/4f04eb982c86c1fdb413084af77c713a6fda3070/libraries/vm/vm_cpython_ss/lib/codecs.py#L631-L637
facebookincubator/fizz
bd0ba1b80f72023cb7ede671a4caa85f6664d3f6
build/fbcode_builder/shell_quoting.py
python
shell_join
(delim, it)
return ShellQuoted(delim.join(raw_shell(s) for s in it))
Joins an iterable of ShellQuoted with a delimiter between each two
Joins an iterable of ShellQuoted with a delimiter between each two
[ "Joins", "an", "iterable", "of", "ShellQuoted", "with", "a", "delimiter", "between", "each", "two" ]
def shell_join(delim, it): "Joins an iterable of ShellQuoted with a delimiter between each two" return ShellQuoted(delim.join(raw_shell(s) for s in it))
[ "def", "shell_join", "(", "delim", ",", "it", ")", ":", "return", "ShellQuoted", "(", "delim", ".", "join", "(", "raw_shell", "(", "s", ")", "for", "s", "in", "it", ")", ")" ]
https://github.com/facebookincubator/fizz/blob/bd0ba1b80f72023cb7ede671a4caa85f6664d3f6/build/fbcode_builder/shell_quoting.py#L84-L86
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/wsgiref/simple_server.py
python
WSGIRequestHandler.handle
(self)
Handle a single HTTP request
Handle a single HTTP request
[ "Handle", "a", "single", "HTTP", "request" ]
def handle(self): """Handle a single HTTP request""" self.raw_requestline = self.rfile.readline(65537) if len(self.raw_requestline) > 65536: self.requestline = '' self.request_version = '' self.command = '' self.send_error(414) return if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandler( self.rfile, self.wfile, self.get_stderr(), self.get_environ(), multithread=False, ) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app())
[ "def", "handle", "(", "self", ")", ":", "self", ".", "raw_requestline", "=", "self", ".", "rfile", ".", "readline", "(", "65537", ")", "if", "len", "(", "self", ".", "raw_requestline", ")", ">", "65536", ":", "self", ".", "requestline", "=", "''", "s...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/wsgiref/simple_server.py#L115-L134
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_register_for_op.py
python
Registry.register
(self, prim)
return deco
register the function.
register the function.
[ "register", "the", "function", "." ]
def register(self, prim): """register the function.""" def deco(fn): """Decorate the function.""" if isinstance(prim, str): self[prim] = fn elif issubclass(prim, Primitive): self[id(prim)] = fn return fn return deco
[ "def", "register", "(", "self", ",", "prim", ")", ":", "def", "deco", "(", "fn", ")", ":", "\"\"\"Decorate the function.\"\"\"", "if", "isinstance", "(", "prim", ",", "str", ")", ":", "self", "[", "prim", "]", "=", "fn", "elif", "issubclass", "(", "pri...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_register_for_op.py#L25-L34
microsoft/Multiverso
e45369e1d07277f656b0900beb2709d86679fa53
binding/python/multiverso/tables.py
python
ArrayTableHandler.get
(self)
return data
get the latest value from multiverso ArrayTable Data type of return value is numpy.ndarray with one-dimensional
get the latest value from multiverso ArrayTable
[ "get", "the", "latest", "value", "from", "multiverso", "ArrayTable" ]
def get(self): '''get the latest value from multiverso ArrayTable Data type of return value is numpy.ndarray with one-dimensional ''' data = np.zeros((self._size, ), dtype=np.dtype("float32")) mv_lib.MV_GetArrayTable(self._handler, data.ctypes.data_as(C_FLOAT_P), self._size) return data
[ "def", "get", "(", "self", ")", ":", "data", "=", "np", ".", "zeros", "(", "(", "self", ".", "_size", ",", ")", ",", "dtype", "=", "np", ".", "dtype", "(", "\"float32\"", ")", ")", "mv_lib", ".", "MV_GetArrayTable", "(", "self", ".", "_handler", ...
https://github.com/microsoft/Multiverso/blob/e45369e1d07277f656b0900beb2709d86679fa53/binding/python/multiverso/tables.py#L59-L66
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/nn/fast_masked_linear.py
python
FastMaskedConv1D.__call__
(self, inputs: Array)
return MaskedConv1D.__call__(self, inputs)
Applies the masked convolution to all input sites. Args: inputs: input data with dimensions (batch, size, features). Returns: The convolved data.
Applies the masked convolution to all input sites.
[ "Applies", "the", "masked", "convolution", "to", "all", "input", "sites", "." ]
def __call__(self, inputs: Array) -> Array: """ Applies the masked convolution to all input sites. Args: inputs: input data with dimensions (batch, size, features). Returns: The convolved data. """ return MaskedConv1D.__call__(self, inputs)
[ "def", "__call__", "(", "self", ",", "inputs", ":", "Array", ")", "->", "Array", ":", "return", "MaskedConv1D", ".", "__call__", "(", "self", ",", "inputs", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/nn/fast_masked_linear.py#L284-L294
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/intelhex/__init__.py
python
IntelHexError.__init__
(self, msg=None, **kw)
Initialize the Exception with the given message.
Initialize the Exception with the given message.
[ "Initialize", "the", "Exception", "with", "the", "given", "message", "." ]
def __init__(self, msg=None, **kw): """Initialize the Exception with the given message. """ self.msg = msg for key, value in dict_items_g(kw): setattr(self, key, value)
[ "def", "__init__", "(", "self", ",", "msg", "=", "None", ",", "*", "*", "kw", ")", ":", "self", ".", "msg", "=", "msg", "for", "key", ",", "value", "in", "dict_items_g", "(", "kw", ")", ":", "setattr", "(", "self", ",", "key", ",", "value", ")"...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/intelhex/__init__.py#L1290-L1295
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Spreadsheet/App/Spreadsheet_legacy.py
python
makeSpreadsheetController
(spreadsheet,cell=None,direction=None)
return obj
makeSpreadsheetController(spreadsheet,[cell,direction]): adds a controller to the given spreadsheet. Call can be a starting cell such as "A5", and direction can be "Horizontal" or "Vertical".
makeSpreadsheetController(spreadsheet,[cell,direction]): adds a controller to the given spreadsheet. Call can be a starting cell such as "A5", and direction can be "Horizontal" or "Vertical".
[ "makeSpreadsheetController", "(", "spreadsheet", "[", "cell", "direction", "]", ")", ":", "adds", "a", "controller", "to", "the", "given", "spreadsheet", ".", "Call", "can", "be", "a", "starting", "cell", "such", "as", "A5", "and", "direction", "can", "be", ...
def makeSpreadsheetController(spreadsheet,cell=None,direction=None): """makeSpreadsheetController(spreadsheet,[cell,direction]): adds a controller to the given spreadsheet. Call can be a starting cell such as "A5", and direction can be "Horizontal" or "Vertical".""" obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","CellController") SpreadsheetController(obj) if FreeCAD.GuiUp: ViewProviderSpreadsheetController(obj.ViewObject) conts = spreadsheet.Controllers conts.append(obj) spreadsheet.Controllers = conts if cell: obj.BaseCell = cell if direction: obj.Direction = direction return obj
[ "def", "makeSpreadsheetController", "(", "spreadsheet", ",", "cell", "=", "None", ",", "direction", "=", "None", ")", ":", "obj", "=", "FreeCAD", ".", "ActiveDocument", ".", "addObject", "(", "\"App::FeaturePython\"", ",", "\"CellController\"", ")", "SpreadsheetCo...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py#L989-L1004
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBBreakpoint.GetID
(self)
return _lldb.SBBreakpoint_GetID(self)
GetID(self) -> break_id_t
GetID(self) -> break_id_t
[ "GetID", "(", "self", ")", "-", ">", "break_id_t" ]
def GetID(self): """GetID(self) -> break_id_t""" return _lldb.SBBreakpoint_GetID(self)
[ "def", "GetID", "(", "self", ")", ":", "return", "_lldb", ".", "SBBreakpoint_GetID", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1445-L1447
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/quantize_wrapper.py
python
QuantizeWrapper._make_quantizer_fn
(self, quantizer, x, training, quantizer_vars)
return quantizer_fn
Use currying to return True/False specialized fns to the cond.
Use currying to return True/False specialized fns to the cond.
[ "Use", "currying", "to", "return", "True", "/", "False", "specialized", "fns", "to", "the", "cond", "." ]
def _make_quantizer_fn(self, quantizer, x, training, quantizer_vars): """Use currying to return True/False specialized fns to the cond.""" def quantizer_fn(): return quantizer(x, training, weights=quantizer_vars) return quantizer_fn
[ "def", "_make_quantizer_fn", "(", "self", ",", "quantizer", ",", "x", ",", "training", ",", "quantizer_vars", ")", ":", "def", "quantizer_fn", "(", ")", ":", "return", "quantizer", "(", "x", ",", "training", ",", "weights", "=", "quantizer_vars", ")", "ret...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/quantize_wrapper.py#L128-L134
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/model_zoo/vision/__init__.py
python
get_model
(name, **kwargs)
return models[name](**kwargs)
Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. Returns ------- gluon.HybridBlock The model.
Returns a pre-defined model by name
[ "Returns", "a", "pre", "-", "defined", "model", "by", "name" ]
def get_model(name, **kwargs): """Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. Returns ------- gluon.HybridBlock The model. """ models = {'resnet18_v1': resnet18_v1, 'resnet34_v1': resnet34_v1, 'resnet50_v1': resnet50_v1, 'resnet101_v1': resnet101_v1, 'resnet152_v1': resnet152_v1, 'resnet18_v2': resnet18_v2, 'resnet34_v2': resnet34_v2, 'resnet50_v2': resnet50_v2, 'resnet101_v2': resnet101_v2, 'resnet152_v2': resnet152_v2, 'vgg11': vgg11, 'vgg13': vgg13, 'vgg16': vgg16, 'vgg19': vgg19, 'vgg11_bn': vgg11_bn, 'vgg13_bn': vgg13_bn, 'vgg16_bn': vgg16_bn, 'vgg19_bn': vgg19_bn, 'alexnet': alexnet, 'densenet121': densenet121, 'densenet161': densenet161, 'densenet169': densenet169, 'densenet201': densenet201, 'squeezenet1.0': squeezenet1_0, 'squeezenet1.1': squeezenet1_1, 'inceptionv3': inception_v3, 'mobilenet1.0': mobilenet1_0, 'mobilenet0.75': mobilenet0_75, 'mobilenet0.5': mobilenet0_5, 'mobilenet0.25': mobilenet0_25, 'mobilenetv2_1.0': mobilenet_v2_1_0, 'mobilenetv2_0.75': mobilenet_v2_0_75, 'mobilenetv2_0.5': mobilenet_v2_0_5, 'mobilenetv2_0.25': mobilenet_v2_0_25 } name = name.lower() if name not in models: raise ValueError( 'Model %s is not supported. Available options are\n\t%s' % ( name, '\n\t'.join(sorted(models.keys())))) return models[name](**kwargs)
[ "def", "get_model", "(", "name", ",", "*", "*", "kwargs", ")", ":", "models", "=", "{", "'resnet18_v1'", ":", "resnet18_v1", ",", "'resnet34_v1'", ":", "resnet34_v1", ",", "'resnet50_v1'", ":", "resnet50_v1", ",", "'resnet101_v1'", ":", "resnet101_v1", ",", ...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/model_zoo/vision/__init__.py#L91-L152
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/ISISCommandInterface.py
python
DataPath
(path)
Sets an extra directory for Mantid to look for run files @param path: the full path to a directory containing the run files to analyse
Sets an extra directory for Mantid to look for run files
[ "Sets", "an", "extra", "directory", "for", "Mantid", "to", "look", "for", "run", "files" ]
def DataPath(path): """ Sets an extra directory for Mantid to look for run files @param path: the full path to a directory containing the run files to analyse """ ReductionSingleton().set_data_path(path)
[ "def", "DataPath", "(", "path", ")", ":", "ReductionSingleton", "(", ")", ".", "set_data_path", "(", "path", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/ISISCommandInterface.py#L1957-L1962
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/lowering.py
python
BaseLower.pre_lower
(self)
Called before lowering all blocks.
Called before lowering all blocks.
[ "Called", "before", "lowering", "all", "blocks", "." ]
def pre_lower(self): """ Called before lowering all blocks. """ # A given Lower object can be used for several LL functions # (for generators) and it's important to use a new API and # EnvironmentManager. self.pyapi = None self.debuginfo.mark_subprogram(function=self.builder.function, name=self.fndesc.qualname, loc=self.func_ir.loc)
[ "def", "pre_lower", "(", "self", ")", ":", "# A given Lower object can be used for several LL functions", "# (for generators) and it's important to use a new API and", "# EnvironmentManager.", "self", ".", "pyapi", "=", "None", "self", ".", "debuginfo", ".", "mark_subprogram", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/lowering.py#L139-L149
vnpy/vnpy
f50f2535ed39dd33272e0985ed40c7078e4c19f6
vnpy/chart/manager.py
python
BarManager.get_bar
(self, ix: float)
return self._bars[dt]
Get bar data with index.
Get bar data with index.
[ "Get", "bar", "data", "with", "index", "." ]
def get_bar(self, ix: float) -> BarData: """ Get bar data with index. """ ix = to_int(ix) dt = self._index_datetime_map.get(ix, None) if not dt: return None return self._bars[dt]
[ "def", "get_bar", "(", "self", ",", "ix", ":", "float", ")", "->", "BarData", ":", "ix", "=", "to_int", "(", "ix", ")", "dt", "=", "self", ".", "_index_datetime_map", ".", "get", "(", "ix", ",", "None", ")", "if", "not", "dt", ":", "return", "Non...
https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/chart/manager.py#L76-L85
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
ColourProperty.__init__
(self, *args, **kwargs)
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), Colour value=*wxWHITE) -> ColourProperty
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), Colour value=*wxWHITE) -> ColourProperty
[ "__init__", "(", "self", "String", "label", "=", "(", "*", "wxPGProperty", "::", "sm_wxPG_LABEL", ")", "String", "name", "=", "(", "*", "wxPGProperty", "::", "sm_wxPG_LABEL", ")", "Colour", "value", "=", "*", "wxWHITE", ")", "-", ">", "ColourProperty" ]
def __init__(self, *args, **kwargs): """ __init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), Colour value=*wxWHITE) -> ColourProperty """ _propgrid.ColourProperty_swiginit(self,_propgrid.new_ColourProperty(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_propgrid", ".", "ColourProperty_swiginit", "(", "self", ",", "_propgrid", ".", "new_ColourProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3337-L3342
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/cookies.py
python
RequestsCookieJar.list_paths
(self)
return paths
Utility method to list all the paths in the jar.
Utility method to list all the paths in the jar.
[ "Utility", "method", "to", "list", "all", "the", "paths", "in", "the", "jar", "." ]
def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
[ "def", "list_paths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "path", "not", "in", "paths", ":", "paths", ".", "append", "(", "cookie", ".", "path", ")", "return", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/cookies.py#L279-L285
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Text.delete
(self, index1, index2=None)
Delete the characters between INDEX1 and INDEX2 (not included).
Delete the characters between INDEX1 and INDEX2 (not included).
[ "Delete", "the", "characters", "between", "INDEX1", "and", "INDEX2", "(", "not", "included", ")", "." ]
def delete(self, index1, index2=None): """Delete the characters between INDEX1 and INDEX2 (not included).""" self.tk.call(self._w, 'delete', index1, index2)
[ "def", "delete", "(", "self", ",", "index1", ",", "index2", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'delete'", ",", "index1", ",", "index2", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L3137-L3139
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/TopologyIDVisitor.py
python
TopologyIDVisitor.finishSourceFilesVisit
(self, obj)
Defined to generate ending static code within files.
Defined to generate ending static code within files.
[ "Defined", "to", "generate", "ending", "static", "code", "within", "files", "." ]
def finishSourceFilesVisit(self, obj): """ Defined to generate ending static code within files. """ # c = finishComponentCpp.finishComponentCpp() # self._writeTmpl(c, "finishSourceFilesVisit") self.__fp.close()
[ "def", "finishSourceFilesVisit", "(", "self", ",", "obj", ")", ":", "# c = finishComponentCpp.finishComponentCpp()", "# self._writeTmpl(c, \"finishSourceFilesVisit\")", "self", ".", "__fp", ".", "close", "(", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/TopologyIDVisitor.py#L189-L195
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/polybond/lmpsdata.py
python
booleanarray.getelement
(self,rownum,colnum)
return self.array[rownum][colnum]
Returns element in the list of lists (array) at rownum and colnum.
Returns element in the list of lists (array) at rownum and colnum.
[ "Returns", "element", "in", "the", "list", "of", "lists", "(", "array", ")", "at", "rownum", "and", "colnum", "." ]
def getelement(self,rownum,colnum): """Returns element in the list of lists (array) at rownum and colnum.""" return self.array[rownum][colnum]
[ "def", "getelement", "(", "self", ",", "rownum", ",", "colnum", ")", ":", "return", "self", ".", "array", "[", "rownum", "]", "[", "colnum", "]" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/polybond/lmpsdata.py#L902-L904
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/importlib/_bootstrap_external.py
python
_validate_timestamp_pyc
(data, source_mtime, source_size, name, exc_details)
Validate a pyc against the source last-modified time. *data* is the contents of the pyc file. (Only the first 16 bytes are required.) *source_mtime* is the last modified timestamp of the source file. *source_size* is None or the size of the source file in bytes. *name* is the name of the module being imported. It is used for logging. *exc_details* is a dictionary passed to ImportError if it raised for improved debugging. An ImportError is raised if the bytecode is stale.
Validate a pyc against the source last-modified time.
[ "Validate", "a", "pyc", "against", "the", "source", "last", "-", "modified", "time", "." ]
def _validate_timestamp_pyc(data, source_mtime, source_size, name, exc_details): """Validate a pyc against the source last-modified time. *data* is the contents of the pyc file. (Only the first 16 bytes are required.) *source_mtime* is the last modified timestamp of the source file. *source_size* is None or the size of the source file in bytes. *name* is the name of the module being imported. It is used for logging. *exc_details* is a dictionary passed to ImportError if it raised for improved debugging. An ImportError is raised if the bytecode is stale. """ if _unpack_uint32(data[8:12]) != (source_mtime & 0xFFFFFFFF): message = f'bytecode is stale for {name!r}' _bootstrap._verbose_message('{}', message) raise ImportError(message, **exc_details) if (source_size is not None and _unpack_uint32(data[12:16]) != (source_size & 0xFFFFFFFF)): raise ImportError(f'bytecode is stale for {name!r}', **exc_details)
[ "def", "_validate_timestamp_pyc", "(", "data", ",", "source_mtime", ",", "source_size", ",", "name", ",", "exc_details", ")", ":", "if", "_unpack_uint32", "(", "data", "[", "8", ":", "12", "]", ")", "!=", "(", "source_mtime", "&", "0xFFFFFFFF", ")", ":", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/_bootstrap_external.py#L593-L618
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeCtrl.Collapse
(*args, **kwargs)
return _controls_.TreeCtrl_Collapse(*args, **kwargs)
Collapse(self, TreeItemId item)
Collapse(self, TreeItemId item)
[ "Collapse", "(", "self", "TreeItemId", "item", ")" ]
def Collapse(*args, **kwargs): """Collapse(self, TreeItemId item)""" return _controls_.TreeCtrl_Collapse(*args, **kwargs)
[ "def", "Collapse", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_Collapse", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5482-L5484
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/_inputstream.py
python
EncodingParser.__init__
(self, data)
string - the data to work on for encoding detection
string - the data to work on for encoding detection
[ "string", "-", "the", "data", "to", "work", "on", "for", "encoding", "detection" ]
def __init__(self, data): """string - the data to work on for encoding detection""" self.data = EncodingBytes(data) self.encoding = None
[ "def", "__init__", "(", "self", ",", "data", ")", ":", "self", ".", "data", "=", "EncodingBytes", "(", "data", ")", "self", ".", "encoding", "=", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/_inputstream.py#L1357-L1363
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/msvccompiler.py
python
MSVCCompiler.get_msvc_paths
(self, path, platform='x86')
return []
Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found.
Get a list of devstudio directories (include, lib or path).
[ "Get", "a", "list", "of", "devstudio", "directories", "(", "include", "lib", "or", "path", ")", "." ]
def get_msvc_paths(self, path, platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found. """ if not _can_read_reg: return [] path = path + " dirs" if self.__version >= 7: key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories" % (self.__root, self.__version)) else: key = (r"%s\6.0\Build System\Components\Platforms" r"\Win32 (%s)\Directories" % (self.__root, platform)) for base in HKEYS: d = read_values(base, key) if d: if self.__version >= 7: return self.__macros.sub(d[path]).split(";") else: return d[path].split(";") # MSVC 6 seems to create the registry entries we need only when # the GUI is run. if self.__version == 6: for base in HKEYS: if read_values(base, r"%s\6.0" % self.__root) is not None: self.warn("It seems you have Visual Studio 6 installed, " "but the expected registry settings are not present.\n" "You must at least run the Visual Studio GUI once " "so that these entries are created.") break return []
[ "def", "get_msvc_paths", "(", "self", ",", "path", ",", "platform", "=", "'x86'", ")", ":", "if", "not", "_can_read_reg", ":", "return", "[", "]", "path", "=", "path", "+", "\" dirs\"", "if", "self", ".", "__version", ">=", "7", ":", "key", "=", "(",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/msvccompiler.py#L587-L621
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/supervisor.py
python
Supervisor._verify_setup
(self)
Check that all is good. Raises: ValueError: If something is not good.
Check that all is good.
[ "Check", "that", "all", "is", "good", "." ]
def _verify_setup(self): """Check that all is good. Raises: ValueError: If something is not good. """ # Not running as chief means that replicas are used. # In that case all Variables must have their device set. if not self._is_chief: for op in self._graph.get_operations(): if op.type == "Variable" and not op.device: raise ValueError("When using replicas, all Variables must have " "their device set: %s" % op)
[ "def", "_verify_setup", "(", "self", ")", ":", "# Not running as chief means that replicas are used.", "# In that case all Variables must have their device set.", "if", "not", "self", ".", "_is_chief", ":", "for", "op", "in", "self", ".", "_graph", ".", "get_operations", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/supervisor.py#L883-L895
tensorflow/io
92b44e180674a8af0e12e405530f7343e3e693e4
tensorflow_io/python/ops/ffmpeg_ops.py
python
_load_libraries
(p)
load_dependency_and_library
load_dependency_and_library
[ "load_dependency_and_library" ]
def _load_libraries(p): """load_dependency_and_library""" for library in p: try: v = _load_library(library) # Only Linux utilize the library for # EncodeAACFunctionFiniFFmpeg # EncodeAACFunctionInitFFmpeg # EncodeAACFunctionCallFFmpeg # DecodeAACFunctionFiniFFmpeg # DecodeAACFunctionInitFFmpeg # DecodeAACFunctionCallFFmpeg l = ( _load_library(library, "dependency") if sys.platform == "linux" else None ) if v is not None: return v, l except NotImplementedError as e: warnings.warn(f"could not load {library}: {e}") NotImplementedError raise NotImplementedError("could not find ffmpeg after search through ", p)
[ "def", "_load_libraries", "(", "p", ")", ":", "for", "library", "in", "p", ":", "try", ":", "v", "=", "_load_library", "(", "library", ")", "# Only Linux utilize the library for", "# EncodeAACFunctionFiniFFmpeg", "# EncodeAACFunctionInitFFmpeg", "# EncodeAACFunctionCallFF...
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/ops/ffmpeg_ops.py#L23-L45
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_view.py
python
GeneralFittingView.setup_fit_by_specifier
(self, specifiers: list)
Setup the fit by specifier combo box.
Setup the fit by specifier combo box.
[ "Setup", "the", "fit", "by", "specifier", "combo", "box", "." ]
def setup_fit_by_specifier(self, specifiers: list) -> None: """Setup the fit by specifier combo box.""" self.general_fitting_options.setup_fit_by_specifier(specifiers)
[ "def", "setup_fit_by_specifier", "(", "self", ",", "specifiers", ":", "list", ")", "->", "None", ":", "self", ".", "general_fitting_options", ".", "setup_fit_by_specifier", "(", "specifiers", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_view.py#L100-L102
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/python-package/catboost/utils.py
python
get_fnr_curve
(model=None, data=None, curve=None, thread_count=-1, plot=False)
return thresholds, fnr
Build points of FNR curve. Parameters ---------- model : catboost.CatBoost The trained model. data : catboost.Pool or list of catboost.Pool A set of samples to build ROC curve with. curve : tuple of three arrays (fpr, tpr, thresholds) ROC curve points in format of get_roc_curve returned value. If set, data parameter must not be set. thread_count : int (default=-1) Number of threads to work with. If -1, then the number of threads is set to the number of CPU cores. plot : bool, optional (default=False) If True, draw curve. Returns ------- curve points : tuple of two arrays (thresholds, fnr)
Build points of FNR curve.
[ "Build", "points", "of", "FNR", "curve", "." ]
def get_fnr_curve(model=None, data=None, curve=None, thread_count=-1, plot=False): """ Build points of FNR curve. Parameters ---------- model : catboost.CatBoost The trained model. data : catboost.Pool or list of catboost.Pool A set of samples to build ROC curve with. curve : tuple of three arrays (fpr, tpr, thresholds) ROC curve points in format of get_roc_curve returned value. If set, data parameter must not be set. thread_count : int (default=-1) Number of threads to work with. If -1, then the number of threads is set to the number of CPU cores. plot : bool, optional (default=False) If True, draw curve. Returns ------- curve points : tuple of two arrays (thresholds, fnr) """ if curve is not None: if data is not None: raise CatBoostError('Only one of the parameters data and curve should be set.') if not (isinstance(curve, list) or isinstance(curve, tuple)) or len(curve) != 3: raise CatBoostError('curve must be list or tuple of three arrays (fpr, tpr, thresholds).') tpr, thresholds = curve[1], curve[2][:] else: if model is None or data is None: raise CatBoostError('model and data parameters should be set when curve parameter is None.') _, tpr, thresholds = get_roc_curve(model, data, thread_count) fnr = np.array([1 - x for x in tpr]) if plot: with _import_matplotlib() as plt: _draw(plt, thresholds, fnr, 'Thresholds', 'False Negative Rate', 'FNR Curve') return thresholds, fnr
[ "def", "get_fnr_curve", "(", "model", "=", "None", ",", "data", "=", "None", ",", "curve", "=", "None", ",", "thread_count", "=", "-", "1", ",", "plot", "=", "False", ")", ":", "if", "curve", "is", "not", "None", ":", "if", "data", "is", "not", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/utils.py#L420-L463
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/swift_build_support/swift_build_support/products/swiftevolve.py
python
SwiftEvolve.product_source_name
(cls)
return "swift-stress-tester"
product_source_name() -> str The name of the source code directory of this product.
product_source_name() -> str
[ "product_source_name", "()", "-", ">", "str" ]
def product_source_name(cls): """product_source_name() -> str The name of the source code directory of this product. """ return "swift-stress-tester"
[ "def", "product_source_name", "(", "cls", ")", ":", "return", "\"swift-stress-tester\"" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/products/swiftevolve.py#L29-L34
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/errors.py
python
ParserContext.add_struct_field_must_be_empty_error
(self, location, name, field_name)
Add an error about field must be empty for fields of type struct.
Add an error about field must be empty for fields of type struct.
[ "Add", "an", "error", "about", "field", "must", "be", "empty", "for", "fields", "of", "type", "struct", "." ]
def add_struct_field_must_be_empty_error(self, location, name, field_name): # type: (common.SourceLocation, unicode, unicode) -> None """Add an error about field must be empty for fields of type struct.""" # pylint: disable=invalid-name self._add_error(location, ERROR_ID_FIELD_MUST_BE_EMPTY_FOR_STRUCT, ( "Field '%s' cannot contain a value for property '%s' when a field's type is a struct") % (name, field_name))
[ "def", "add_struct_field_must_be_empty_error", "(", "self", ",", "location", ",", "name", ",", "field_name", ")", ":", "# type: (common.SourceLocation, unicode, unicode) -> None", "# pylint: disable=invalid-name", "self", ".", "_add_error", "(", "location", ",", "ERROR_ID_FIE...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/errors.py#L393-L399
opencv/opencv
76aff8478883858f0e46746044348ebb16dc3c67
modules/java/generator/gen_java.py
python
GeneralInfo.parseName
(self, name, namespaces)
input: full name and available namespaces returns: (namespace, classpath, classname, name)
input: full name and available namespaces returns: (namespace, classpath, classname, name)
[ "input", ":", "full", "name", "and", "available", "namespaces", "returns", ":", "(", "namespace", "classpath", "classname", "name", ")" ]
def parseName(self, name, namespaces): ''' input: full name and available namespaces returns: (namespace, classpath, classname, name) ''' name = name[name.find(" ")+1:].strip() # remove struct/class/const prefix parent = name[:name.rfind('.')].strip() if len(parent) == 0: parent = None spaceName = "" localName = name # <classes>.<name> for namespace in sorted(namespaces, key=len, reverse=True): if name.startswith(namespace + "."): spaceName = namespace localName = name.replace(namespace + ".", "") break pieces = localName.split(".") if len(pieces) > 2: # <class>.<class>.<class>.<name> return name, parent, spaceName, ".".join(pieces[:-1]), pieces[-2], pieces[-1] elif len(pieces) == 2: # <class>.<name> return name, parent, spaceName, pieces[0], pieces[0], pieces[1] elif len(pieces) == 1: # <name> return name, parent, spaceName, "", "", pieces[0] else: return name, parent, spaceName, "", ""
[ "def", "parseName", "(", "self", ",", "name", ",", "namespaces", ")", ":", "name", "=", "name", "[", "name", ".", "find", "(", "\" \"", ")", "+", "1", ":", "]", ".", "strip", "(", ")", "# remove struct/class/const prefix", "parent", "=", "name", "[", ...
https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/modules/java/generator/gen_java.py#L148-L172
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/software/scene_retrieving/src/nlohmann_json/benchmarks/thirdparty/benchmark/tools/gbench/util.py
python
check_input_file
(filename)
return ftype
Classify the file named by 'filename' and return the classification. If the file is classified as 'IT_Invalid' print an error message and exit the program.
Classify the file named by 'filename' and return the classification. If the file is classified as 'IT_Invalid' print an error message and exit the program.
[ "Classify", "the", "file", "named", "by", "filename", "and", "return", "the", "classification", ".", "If", "the", "file", "is", "classified", "as", "IT_Invalid", "print", "an", "error", "message", "and", "exit", "the", "program", "." ]
def check_input_file(filename): """ Classify the file named by 'filename' and return the classification. If the file is classified as 'IT_Invalid' print an error message and exit the program. """ ftype, msg = classify_input_file(filename) if ftype == IT_Invalid: print("Invalid input file: %s" % msg) sys.exit(1) return ftype
[ "def", "check_input_file", "(", "filename", ")", ":", "ftype", ",", "msg", "=", "classify_input_file", "(", "filename", ")", "if", "ftype", "==", "IT_Invalid", ":", "print", "(", "\"Invalid input file: %s\"", "%", "msg", ")", "sys", ".", "exit", "(", "1", ...
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/software/scene_retrieving/src/nlohmann_json/benchmarks/thirdparty/benchmark/tools/gbench/util.py#L75-L85
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py
python
RFC2217Serial._telnetReadLoop
(self)
read loop for the socket.
read loop for the socket.
[ "read", "loop", "for", "the", "socket", "." ]
def _telnetReadLoop(self): """read loop for the socket.""" mode = M_NORMAL suboption = None try: while self._socket is not None: try: data = self._socket.recv(1024) except socket.timeout: # just need to get out of recv form time to time to check if # still alive continue except socket.error, e: # connection fails -> terminate loop if self.logger: self.logger.debug("socket error in reader thread: %s" % (e,)) break if not data: break # lost connection for byte in data: if mode == M_NORMAL: # interpret as command or as data if byte == IAC: mode = M_IAC_SEEN else: # store data in read buffer or sub option buffer # depending on state if suboption is not None: suboption.append(byte) else: self._read_buffer.put(byte) elif mode == M_IAC_SEEN: if byte == IAC: # interpret as command doubled -> insert character # itself if suboption is not None: suboption.append(IAC) else: self._read_buffer.put(IAC) mode = M_NORMAL elif byte == SB: # sub option start suboption = bytearray() mode = M_NORMAL elif byte == SE: # sub option end -> process it now self._telnetProcessSubnegotiation(bytes(suboption)) suboption = None mode = M_NORMAL elif byte in (DO, DONT, WILL, WONT): # negotiation telnet_command = byte mode = M_NEGOTIATE else: # other telnet commands self._telnetProcessCommand(byte) mode = M_NORMAL elif mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following self._telnetNegotiateOption(telnet_command, byte) mode = M_NORMAL finally: self._thread = None if self.logger: self.logger.debug("read thread terminated")
[ "def", "_telnetReadLoop", "(", "self", ")", ":", "mode", "=", "M_NORMAL", "suboption", "=", "None", "try", ":", "while", "self", ".", "_socket", "is", "not", "None", ":", "try", ":", "data", "=", "self", ".", "_socket", ".", "recv", "(", "1024", ")",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py#L684-L746
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/reduction_gui/reduction/sans/data_cat.py
python
DataSet.__str__
(self)
return "%-6s %-60s %-16s %-7g %-10.0f" % (self.run_number, self.title, self.run_start, self.duration, self.sdd)
Pretty print the current data set attributes
Pretty print the current data set attributes
[ "Pretty", "print", "the", "current", "data", "set", "attributes" ]
def __str__(self): """ Pretty print the current data set attributes """ return "%-6s %-60s %-16s %-7g %-10.0f" % (self.run_number, self.title, self.run_start, self.duration, self.sdd)
[ "def", "__str__", "(", "self", ")", ":", "return", "\"%-6s %-60s %-16s %-7g %-10.0f\"", "%", "(", "self", ".", "run_number", ",", "self", ".", "title", ",", "self", ".", "run_start", ",", "self", ".", "duration", ",", "self", ".", "sdd", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/sans/data_cat.py#L107-L111
gwaldron/osgearth
4c521857d59a69743e4a9cedba00afe570f984e8
src/third_party/tinygltf/deps/cpplint.py
python
CheckRedundantVirtual
(filename, clean_lines, linenum, error)
Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check if line contains a redundant "virtual" function-specifier.
[ "Check", "if", "line", "contains", "a", "redundant", "virtual", "function", "-", "specifier", "." ]
def CheckRedundantVirtual(filename, clean_lines, linenum, error): """Check if line contains a redundant "virtual" function-specifier. 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. """ # Look for "virtual" on current line. line = clean_lines.elided[linenum] virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) if not virtual: return # Ignore "virtual" keywords that are near access-specifiers. These # are only used in class base-specifier and do not apply to member # functions. if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or Match(r'^\s+(public|protected|private)\b', virtual.group(3))): return # Ignore the "virtual" keyword from virtual base classes. Usually # there is a column on the same line in these cases (virtual base # classes are rare in google3 because multiple inheritance is rare). if Match(r'^.*[^:]:[^:].*$', line): return # Look for the next opening parenthesis. This is the start of the # parameter list (possibly on the next line shortly after virtual). # TODO(unknown): doesn't work if there are virtual functions with # decltype() or other things that use parentheses, but csearch suggests # that this is rare. end_col = -1 end_line = -1 start_col = len(virtual.group(2)) for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): line = clean_lines.elided[start_line][start_col:] parameter_list = Match(r'^([^(]*)\(', line) if parameter_list: # Match parentheses to find the end of the parameter list (_, end_line, end_col) = CloseExpression( clean_lines, start_line, start_col + len(parameter_list.group(1))) break start_col = 0 if end_col < 0: return # Couldn't find end of parameter list, give up # Look for "override" or "final" after the parameter list # (possibly on the next few lines). for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): line = clean_lines.elided[i][end_col:] match = Search(r'\b(override|final)\b', line) if match: error(filename, linenum, 'readability/inheritance', 4, ('"virtual" is redundant since function is ' 'already declared as "%s"' % match.group(1))) # Set end_col to check whole lines after we are done with the # first line. end_col = 0 if Search(r'[^\w]\s*$', line): break
[ "def", "CheckRedundantVirtual", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Look for \"virtual\" on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "virtual", "=", "Match", "(", "r'^(.*)(\\bvirtual\...
https://github.com/gwaldron/osgearth/blob/4c521857d59a69743e4a9cedba00afe570f984e8/src/third_party/tinygltf/deps/cpplint.py#L5747-L5808
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Text.compare
(self, index1, op, index2)
return self.tk.getboolean(self.tk.call( self._w, 'compare', index1, op, index2))
Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.
Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.
[ "Return", "whether", "between", "index", "INDEX1", "and", "index", "INDEX2", "the", "relation", "OP", "is", "satisfied", ".", "OP", "is", "one", "of", "<", "<", "=", "==", ">", "=", ">", "or", "!", "=", "." ]
def compare(self, index1, op, index2): """Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.""" return self.tk.getboolean(self.tk.call( self._w, 'compare', index1, op, index2))
[ "def", "compare", "(", "self", ",", "index1", ",", "op", ",", "index2", ")", ":", "return", "self", ".", "tk", ".", "getboolean", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'compare'", ",", "index1", ",", "op", ",", "index...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2903-L2907
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
GraphicsPath.AddCurveToPoint
(*args)
return _gdi_.GraphicsPath_AddCurveToPoint(*args)
AddCurveToPoint(self, Double cx1, Double cy1, Double cx2, Double cy2, Double x, Double y) AddCurveToPoint(self, Point2D c1, Point2D c2, Point2D e) Adds a cubic Bezier curve from the current point, using two control points and an end point
AddCurveToPoint(self, Double cx1, Double cy1, Double cx2, Double cy2, Double x, Double y) AddCurveToPoint(self, Point2D c1, Point2D c2, Point2D e)
[ "AddCurveToPoint", "(", "self", "Double", "cx1", "Double", "cy1", "Double", "cx2", "Double", "cy2", "Double", "x", "Double", "y", ")", "AddCurveToPoint", "(", "self", "Point2D", "c1", "Point2D", "c2", "Point2D", "e", ")" ]
def AddCurveToPoint(*args): """ AddCurveToPoint(self, Double cx1, Double cy1, Double cx2, Double cy2, Double x, Double y) AddCurveToPoint(self, Point2D c1, Point2D c2, Point2D e) Adds a cubic Bezier curve from the current point, using two control points and an end point """ return _gdi_.GraphicsPath_AddCurveToPoint(*args)
[ "def", "AddCurveToPoint", "(", "*", "args", ")", ":", "return", "_gdi_", ".", "GraphicsPath_AddCurveToPoint", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L5714-L5723
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/aepack.py
python
coerce
(data, egdata)
return unpack(pdata)
Coerce a python object to another type using the AE coercers
Coerce a python object to another type using the AE coercers
[ "Coerce", "a", "python", "object", "to", "another", "type", "using", "the", "AE", "coercers" ]
def coerce(data, egdata): """Coerce a python object to another type using the AE coercers""" pdata = pack(data) pegdata = pack(egdata) pdata = pdata.AECoerceDesc(pegdata.type) return unpack(pdata)
[ "def", "coerce", "(", "data", ",", "egdata", ")", ":", "pdata", "=", "pack", "(", "data", ")", "pegdata", "=", "pack", "(", "egdata", ")", "pdata", "=", "pdata", ".", "AECoerceDesc", "(", "pegdata", ".", "type", ")", "return", "unpack", "(", "pdata",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/aepack.py#L255-L260
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/buttonpanel.py
python
ButtonInfo.SetText
(self, text="")
Sets the button label text. :param string `text`: the button label string.
Sets the button label text.
[ "Sets", "the", "button", "label", "text", "." ]
def SetText(self, text=""): """ Sets the button label text. :param string `text`: the button label string. """ self._text = text
[ "def", "SetText", "(", "self", ",", "text", "=", "\"\"", ")", ":", "self", ".", "_text", "=", "text" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L1688-L1695
sfzhang15/FaceBoxes
b52cc92f9362d3adc08d54666aeb9ebb62fdb7da
scripts/cpp_lint.py
python
CheckForIncludeWhatYouUse
(filename, clean_lines, include_state, error, io=codecs)
Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection.
Reports for missing stl includes.
[ "Reports", "for", "missing", "stl", "includes", "." ]
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's copy the include_state so it is only messed up within this function. include_state = include_state.copy() # Did we find the header for this file (if any) and succesfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_state is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_state.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_state, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_state: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template)
[ "def", "CheckForIncludeWhatYouUse", "(", "filename", ",", "clean_lines", ",", "include_state", ",", "error", ",", "io", "=", "codecs", ")", ":", "required", "=", "{", "}", "# A map of header name to linenumber and the template entity.", "# Example of required: { '<functiona...
https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/scripts/cpp_lint.py#L4487-L4577
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/xlsgrid.py
python
XLSText.SetupHyperlink
(self, hyperlink)
Sets up the cell text value in case it represents a hyperlink. :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`. :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink* parameter will always be ``None`` as this feature is available only in `xlrd` 0.7.2 (SVN).
Sets up the cell text value in case it represents a hyperlink.
[ "Sets", "up", "the", "cell", "text", "value", "in", "case", "it", "represents", "a", "hyperlink", "." ]
def SetupHyperlink(self, hyperlink): """ Sets up the cell text value in case it represents a hyperlink. :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`. :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink* parameter will always be ``None`` as this feature is available only in `xlrd` 0.7.2 (SVN). """ url = (hyperlink.url_or_path and [hyperlink.url_or_path] or [hyperlink.textmark])[0] self.tooltip = url
[ "def", "SetupHyperlink", "(", "self", ",", "hyperlink", ")", ":", "url", "=", "(", "hyperlink", ".", "url_or_path", "and", "[", "hyperlink", ".", "url_or_path", "]", "or", "[", "hyperlink", ".", "textmark", "]", ")", "[", "0", "]", "self", ".", "toolti...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/xlsgrid.py#L856-L868
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/errors.py
python
AlreadyExistsError.__init__
(self, node_def, op, message)
Creates an `AlreadyExistsError`.
Creates an `AlreadyExistsError`.
[ "Creates", "an", "AlreadyExistsError", "." ]
def __init__(self, node_def, op, message): """Creates an `AlreadyExistsError`.""" super(AlreadyExistsError, self).__init__(node_def, op, message, ALREADY_EXISTS)
[ "def", "__init__", "(", "self", ",", "node_def", ",", "op", ",", "message", ")", ":", "super", "(", "AlreadyExistsError", ",", "self", ")", ".", "__init__", "(", "node_def", ",", "op", ",", "message", ",", "ALREADY_EXISTS", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/errors.py#L250-L253
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
source/data/data_board.py
python
ArrayManager.keltner
(self, n, dev, array=False)
return up, down
Keltner Channel.
Keltner Channel.
[ "Keltner", "Channel", "." ]
def keltner(self, n, dev, array=False): """ Keltner Channel. """ mid = self.sma(n, array) atr = self.atr(n, array) up = mid + atr * dev down = mid - atr * dev return up, down
[ "def", "keltner", "(", "self", ",", "n", ",", "dev", ",", "array", "=", "False", ")", ":", "mid", "=", "self", ".", "sma", "(", "n", ",", "array", ")", "atr", "=", "self", ".", "atr", "(", "n", ",", "array", ")", "up", "=", "mid", "+", "atr...
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/source/data/data_board.py#L322-L332
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/onnx/helper.py
python
benchmark_pytorch_model
(model, inputs, training=False, warmup_iters=3, main_iters=10, verbose=False)
return total_pytorch_time * 1000 / main_iters
Run the model several times, and measure the execution time. Return the execution time per iteration (millisecond).
Run the model several times, and measure the execution time. Return the execution time per iteration (millisecond).
[ "Run", "the", "model", "several", "times", "and", "measure", "the", "execution", "time", ".", "Return", "the", "execution", "time", "per", "iteration", "(", "millisecond", ")", "." ]
def benchmark_pytorch_model(model, inputs, training=False, warmup_iters=3, main_iters=10, verbose=False): ''' Run the model several times, and measure the execution time. Return the execution time per iteration (millisecond). ''' for _i in range(warmup_iters): model(*inputs) total_pytorch_time = 0.0 for _i in range(main_iters): ts = time.time() model(*inputs) te = time.time() total_pytorch_time += te - ts log.info("The PyTorch model execution time per iter is {} milliseconds, " "{} iters per second.".format(total_pytorch_time / main_iters * 1000, main_iters / total_pytorch_time)) return total_pytorch_time * 1000 / main_iters
[ "def", "benchmark_pytorch_model", "(", "model", ",", "inputs", ",", "training", "=", "False", ",", "warmup_iters", "=", "3", ",", "main_iters", "=", "10", ",", "verbose", "=", "False", ")", ":", "for", "_i", "in", "range", "(", "warmup_iters", ")", ":", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/onnx/helper.py#L103-L120
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/basic_fitting_context.py
python
BasicFittingContext.plot_guess_type
(self)
return self._plot_guess_type
Returns the guess plot range type.
Returns the guess plot range type.
[ "Returns", "the", "guess", "plot", "range", "type", "." ]
def plot_guess_type(self) -> str: """Returns the guess plot range type.""" return self._plot_guess_type
[ "def", "plot_guess_type", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_plot_guess_type" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/basic_fitting_context.py#L217-L219
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py
python
normalize_path
(filename)
return os.path.normcase(os.path.realpath(filename))
Normalize a file/dir name for comparison purposes
Normalize a file/dir name for comparison purposes
[ "Normalize", "a", "file", "/", "dir", "name", "for", "comparison", "purposes" ]
def normalize_path(filename): """Normalize a file/dir name for comparison purposes""" return os.path.normcase(os.path.realpath(filename))
[ "def", "normalize_path", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "realpath", "(", "filename", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py#L1982-L1984
HerculesWS/Hercules
75bfe797ace4da8638b67a3b28e9f0de78dc40d8
tools/utils/libconf.py
python
TokenStream.peek
(self)
return self.tokens[self.position]
Return (but do not consume) the next token At the end of input, ``None`` is returned.
Return (but do not consume) the next token
[ "Return", "(", "but", "do", "not", "consume", ")", "the", "next", "token" ]
def peek(self): '''Return (but do not consume) the next token At the end of input, ``None`` is returned. ''' if self.position >= len(self.tokens): return None return self.tokens[self.position]
[ "def", "peek", "(", "self", ")", ":", "if", "self", ".", "position", ">=", "len", "(", "self", ".", "tokens", ")", ":", "return", "None", "return", "self", ".", "tokens", "[", "self", ".", "position", "]" ]
https://github.com/HerculesWS/Hercules/blob/75bfe797ace4da8638b67a3b28e9f0de78dc40d8/tools/utils/libconf.py#L320-L329
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/default_settings.py
python
hint_specs_to_include_in_project_generation
(ctx, section_name, option_name, value)
return (spec_list, spec_list, desc_list, "multi")
Hint list of specs for projection generation
Hint list of specs for projection generation
[ "Hint", "list", "of", "specs", "for", "projection", "generation" ]
def hint_specs_to_include_in_project_generation(ctx, section_name, option_name, value): """ Hint list of specs for projection generation """ spec_list = sorted(ctx.loaded_specs()) desc_list = [] for spec in spec_list: desc_list.append(ctx.spec_description(spec)) return (spec_list, spec_list, desc_list, "multi")
[ "def", "hint_specs_to_include_in_project_generation", "(", "ctx", ",", "section_name", ",", "option_name", ",", "value", ")", ":", "spec_list", "=", "sorted", "(", "ctx", ".", "loaded_specs", "(", ")", ")", "desc_list", "=", "[", "]", "for", "spec", "in", "s...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/default_settings.py#L474-L482
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/jinja2/compiler.py
python
Frame.copy
(self)
return rv
Create a copy of the current one.
Create a copy of the current one.
[ "Create", "a", "copy", "of", "the", "current", "one", "." ]
def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) return rv
[ "def", "copy", "(", "self", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "identifiers", "=", "object", ".", "__new__", "(", "s...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/compiler.py#L186-L192
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/jinja2/compiler.py
python
CodeGenerator.return_buffer_contents
(self, frame)
Return the buffer contents of the frame.
Return the buffer contents of the frame.
[ "Return", "the", "buffer", "contents", "of", "the", "frame", "." ]
def return_buffer_contents(self, frame): """Return the buffer contents of the frame.""" if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline('return concat(%s)' % frame.buffer) self.outdent() elif frame.eval_ctx.autoescape: self.writeline('return Markup(concat(%s))' % frame.buffer) else: self.writeline('return concat(%s)' % frame.buffer)
[ "def", "return_buffer_contents", "(", "self", ",", "frame", ")", ":", "if", "frame", ".", "eval_ctx", ".", "volatile", ":", "self", ".", "writeline", "(", "'if context.eval_ctx.autoescape:'", ")", "self", ".", "indent", "(", ")", "self", ".", "writeline", "(...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/compiler.py#L437-L451
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py
python
_GMMBase.bic
(self, X)
return (-2 * self.score(X).sum() + self._n_parameters() * np.log(X.shape[0]))
Bayesian information criterion for the current model fit and the proposed data. Parameters ---------- X : array of shape(n_samples, n_dimensions) Returns ------- bic: float (the lower the better)
Bayesian information criterion for the current model fit and the proposed data.
[ "Bayesian", "information", "criterion", "for", "the", "current", "model", "fit", "and", "the", "proposed", "data", "." ]
def bic(self, X): """Bayesian information criterion for the current model fit and the proposed data. Parameters ---------- X : array of shape(n_samples, n_dimensions) Returns ------- bic: float (the lower the better) """ return (-2 * self.score(X).sum() + self._n_parameters() * np.log(X.shape[0]))
[ "def", "bic", "(", "self", ",", "X", ")", ":", "return", "(", "-", "2", "*", "self", ".", "score", "(", "X", ")", ".", "sum", "(", ")", "+", "self", ".", "_n_parameters", "(", ")", "*", "np", ".", "log", "(", "X", ".", "shape", "[", "0", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py#L632-L645
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py
python
filter_except
(validator, iterable, *exceptions)
Yield the items from *iterable* for which the *validator* function does not raise one of the specified *exceptions*. *validator* is called for each item in *iterable*. It should be a function that accepts one argument and raises an exception if that item is not valid. >>> iterable = ['1', '2', 'three', '4', None] >>> list(filter_except(int, iterable, ValueError, TypeError)) ['1', '2', '4'] If an exception other than one given by *exceptions* is raised by *validator*, it is raised like normal.
Yield the items from *iterable* for which the *validator* function does not raise one of the specified *exceptions*.
[ "Yield", "the", "items", "from", "*", "iterable", "*", "for", "which", "the", "*", "validator", "*", "function", "does", "not", "raise", "one", "of", "the", "specified", "*", "exceptions", "*", "." ]
def filter_except(validator, iterable, *exceptions): """Yield the items from *iterable* for which the *validator* function does not raise one of the specified *exceptions*. *validator* is called for each item in *iterable*. It should be a function that accepts one argument and raises an exception if that item is not valid. >>> iterable = ['1', '2', 'three', '4', None] >>> list(filter_except(int, iterable, ValueError, TypeError)) ['1', '2', '4'] If an exception other than one given by *exceptions* is raised by *validator*, it is raised like normal. """ for item in iterable: try: validator(item) except exceptions: pass else: yield item
[ "def", "filter_except", "(", "validator", ",", "iterable", ",", "*", "exceptions", ")", ":", "for", "item", "in", "iterable", ":", "try", ":", "validator", "(", "item", ")", "except", "exceptions", ":", "pass", "else", ":", "yield", "item" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py#L3235-L3256
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/workspacedisplay/table/presenter_base.py
python
TableWorkspaceDataPresenterBase.__init__
(self, model=None, view=None)
:param model: A reference to the model holding the table data :param view: A reference to the view that is displayed to the user
:param model: A reference to the model holding the table data :param view: A reference to the view that is displayed to the user
[ ":", "param", "model", ":", "A", "reference", "to", "the", "model", "holding", "the", "table", "data", ":", "param", "view", ":", "A", "reference", "to", "the", "view", "that", "is", "displayed", "to", "the", "user" ]
def __init__(self, model=None, view=None): """ :param model: A reference to the model holding the table data :param view: A reference to the view that is displayed to the user """ self.model = model self.view = view
[ "def", "__init__", "(", "self", ",", "model", "=", "None", ",", "view", "=", "None", ")", ":", "self", ".", "model", "=", "model", "self", ".", "view", "=", "view" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/workspacedisplay/table/presenter_base.py#L19-L25
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Configuration/DataProcessing/python/Reco.py
python
Reco.dqmHarvesting
(self, datasetName, runNumber, globalTag, **args)
return process
_dqmHarvesting_ Proton collisions data taking DQM Harvesting
_dqmHarvesting_
[ "_dqmHarvesting_" ]
def dqmHarvesting(self, datasetName, runNumber, globalTag, **args): """ _dqmHarvesting_ Proton collisions data taking DQM Harvesting """ options = defaultOptions options.scenario = self.cbSc options.step = "HARVESTING"+dqmSeq(args,':dqmHarvesting') options.name = "EDMtoMEConvert" options.conditions = gtNameAndConnect(globalTag, args) process = cms.Process("HARVESTING", self.eras) process.source = dqmIOSource(args) if 'customs' in args: options.customisation_file=args['customs'] configBuilder = ConfigBuilder(options, process = process) configBuilder.prepare() harvestingMode(process,datasetName,args,rANDl=False) return process
[ "def", "dqmHarvesting", "(", "self", ",", "datasetName", ",", "runNumber", ",", "globalTag", ",", "*", "*", "args", ")", ":", "options", "=", "defaultOptions", "options", ".", "scenario", "=", "self", ".", "cbSc", "options", ".", "step", "=", "\"HARVESTING...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Configuration/DataProcessing/python/Reco.py#L252-L275