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
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/gem5/components/boards/mem_mode.py
python
mem_mode_to_string
(mem_mode: MemMode)
Returns the string form of the mem_mode, compatible with the gem5 simulator. :returns: The string form of the mem_mode
Returns the string form of the mem_mode, compatible with the gem5 simulator.
[ "Returns", "the", "string", "form", "of", "the", "mem_mode", "compatible", "with", "the", "gem5", "simulator", "." ]
def mem_mode_to_string(mem_mode: MemMode) -> str: """ Returns the string form of the mem_mode, compatible with the gem5 simulator. :returns: The string form of the mem_mode """ if mem_mode == MemMode.TIMING: return "timing" elif mem_mode == MemMode.ATOMIC: return "atomic" elif mem_mode == MemMode.ATOMIC_NONCACHING: return "atomic_noncaching" else: return NotImplementedError
[ "def", "mem_mode_to_string", "(", "mem_mode", ":", "MemMode", ")", "->", "str", ":", "if", "mem_mode", "==", "MemMode", ".", "TIMING", ":", "return", "\"timing\"", "elif", "mem_mode", "==", "MemMode", ".", "ATOMIC", ":", "return", "\"atomic\"", "elif", "mem_...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/gem5/components/boards/mem_mode.py#L39-L53
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py
python
Replay
(*args)
Put mocks into Replay mode. Args: # args is any number of mocks to put into replay mode.
Put mocks into Replay mode.
[ "Put", "mocks", "into", "Replay", "mode", "." ]
def Replay(*args): """Put mocks into Replay mode. Args: # args is any number of mocks to put into replay mode. """ for mock in args: mock._Replay()
[ "def", "Replay", "(", "*", "args", ")", ":", "for", "mock", "in", "args", ":", "mock", ".", "_Replay", "(", ")" ]
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py#L235-L243
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/install.py
python
install.finalize_other
(self)
Finalizes options for non-posix platforms
Finalizes options for non-posix platforms
[ "Finalizes", "options", "for", "non", "-", "posix", "platforms" ]
def finalize_other(self): """Finalizes options for non-posix platforms""" if self.user: if self.install_userbase is None: raise DistutilsPlatformError( "User base directory is not specified") self.install_base = self.install_platbase = self.install_userbase self.select_scheme(os.name + "_user") elif self.home is not None: self.install_base = self.install_platbase = self.home self.select_scheme("unix_home") else: if self.prefix is None: self.prefix = os.path.normpath(sys.prefix) self.install_base = self.install_platbase = self.prefix try: self.select_scheme(os.name) except KeyError: raise DistutilsPlatformError( "I don't know how to install stuff on '%s'" % os.name)
[ "def", "finalize_other", "(", "self", ")", ":", "if", "self", ".", "user", ":", "if", "self", ".", "install_userbase", "is", "None", ":", "raise", "DistutilsPlatformError", "(", "\"User base directory is not specified\"", ")", "self", ".", "install_base", "=", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/install.py#L432-L452
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Utilities/Scripts/SlicerWizard/Utilities.py
python
haveGit
()
return _haveGit
Return True if git is available. A side effect of `import git` is that it shows a popup window on MacOSX, asking the user to install XCode (if git is not installed already), therefore this method should only be called if git is actually needed.
Return True if git is available.
[ "Return", "True", "if", "git", "is", "available", "." ]
def haveGit(): """Return True if git is available. A side effect of `import git` is that it shows a popup window on MacOSX, asking the user to install XCode (if git is not installed already), therefore this method should only be called if git is actually needed. """ try: import git _haveGit = True except ImportError: _haveGit = False return _haveGit
[ "def", "haveGit", "(", ")", ":", "try", ":", "import", "git", "_haveGit", "=", "True", "except", "ImportError", ":", "_haveGit", "=", "False", "return", "_haveGit" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Utilities/Scripts/SlicerWizard/Utilities.py#L10-L25
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/elastic_average_optimizer.py
python
ElasticAverageCustomGetter.__init__
(self, worker_device)
Create a new `ElasticAverageCustomGetter`. Args: worker_device: String. Name of the `worker` job.
Create a new `ElasticAverageCustomGetter`.
[ "Create", "a", "new", "ElasticAverageCustomGetter", "." ]
def __init__(self, worker_device): """Create a new `ElasticAverageCustomGetter`. Args: worker_device: String. Name of the `worker` job. """ self._worker_device = worker_device self._local_map = {} self._global_map = {}
[ "def", "__init__", "(", "self", ",", "worker_device", ")", ":", "self", ".", "_worker_device", "=", "worker_device", "self", ".", "_local_map", "=", "{", "}", "self", ".", "_global_map", "=", "{", "}" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/elastic_average_optimizer.py#L87-L95
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/datasets/imagenet.py
python
imagenet.gt_roidb
(self)
return gt_roidb
Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls.
Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls.
[ "Return", "the", "database", "of", "ground", "-", "truth", "regions", "of", "interest", ".", "This", "function", "loads", "/", "saves", "from", "/", "to", "a", "cache", "file", "to", "speed", "up", "future", "calls", "." ]
def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_imagenet_annotation(index) for index in self.image_index] with open(cache_file, 'wb') as fid: cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb
[ "def", "gt_roidb", "(", "self", ")", ":", "cache_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache_path", ",", "self", ".", "name", "+", "'_gt_roidb.pkl'", ")", "if", "os", ".", "path", ".", "exists", "(", "cache_file", ")", ":", ...
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/datasets/imagenet.py#L144-L162
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/packaging/ipk.py
python
build_specfiles
(source, target, env)
return 0
Filter the targets for the needed files and use the variables in env to create the specfile.
Filter the targets for the needed files and use the variables in env to create the specfile.
[ "Filter", "the", "targets", "for", "the", "needed", "files", "and", "use", "the", "variables", "in", "env", "to", "create", "the", "specfile", "." ]
def build_specfiles(source, target, env): """ Filter the targets for the needed files and use the variables in env to create the specfile. """ # # At first we care for the CONTROL/control file, which is the main file for ipk. # # For this we need to open multiple files in random order, so we store into # a dict so they can be easily accessed. # # opened_files={} def open_file(needle, haystack): try: return opened_files[needle] except KeyError: file=filter(lambda x: x.get_path().rfind(needle)!=-1, haystack)[0] opened_files[needle]=open(file.get_abspath(), 'w') return opened_files[needle] control_file=open_file('control', target) if 'X_IPK_DESCRIPTION' not in env: env['X_IPK_DESCRIPTION']="%s\n %s"%(env['SUMMARY'], env['DESCRIPTION'].replace('\n', '\n ')) content = """ Package: $NAME Version: $VERSION Priority: $X_IPK_PRIORITY Section: $X_IPK_SECTION Source: $SOURCE_URL Architecture: $ARCHITECTURE Maintainer: $X_IPK_MAINTAINER Depends: $X_IPK_DEPENDS Description: $X_IPK_DESCRIPTION """ control_file.write(env.subst(content)) # # now handle the various other files, which purpose it is to set post-, # pre-scripts and mark files as config files. # # We do so by filtering the source files for files which are marked with # the "config" tag and afterwards we do the same for x_ipk_postrm, # x_ipk_prerm, x_ipk_postinst and x_ipk_preinst tags. # # The first one will write the name of the file into the file # CONTROL/configfiles, the latter add the content of the x_ipk_* variable # into the same named file. # for f in [x for x in source if 'PACKAGING_CONFIG' in dir(x)]: config=open_file('conffiles') config.write(f.PACKAGING_INSTALL_LOCATION) config.write('\n') for str in 'POSTRM PRERM POSTINST PREINST'.split(): name="PACKAGING_X_IPK_%s"%str for f in [x for x in source if name in dir(x)]: file=open_file(name) file.write(env[str]) # # close all opened files for f in list(opened_files.values()): f.close() # call a user specified function if 'CHANGE_SPECFILE' in env: content += env['CHANGE_SPECFILE'](target) return 0
[ "def", "build_specfiles", "(", "source", ",", "target", ",", "env", ")", ":", "#", "# At first we care for the CONTROL/control file, which is the main file for ipk.", "#", "# For this we need to open multiple files in random order, so we store into", "# a dict so they can be easily acces...
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/packaging/ipk.py#L106-L179
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/cauchy.py
python
Cauchy._cross_entropy
(self, dist, loc_b, scale_b, loc_a=None, scale_a=None)
return self._entropy(loc_a, scale_a) + self._kl_loss(dist, loc_b, scale_b, loc_a, scale_a)
r""" Evaluate cross entropy between Cauchy distributions. Args: dist (str): The type of the distributions. Should be "Cauchy" in this case. loc_b (Tensor): The loc of distribution b. scale_b (Tensor): The scale of distribution b. loc (Tensor): The loc of distribution a. Default: self.loc. scale (Tensor): The scale of distribution a. Default: self.scale.
r""" Evaluate cross entropy between Cauchy distributions.
[ "r", "Evaluate", "cross", "entropy", "between", "Cauchy", "distributions", "." ]
def _cross_entropy(self, dist, loc_b, scale_b, loc_a=None, scale_a=None): r""" Evaluate cross entropy between Cauchy distributions. Args: dist (str): The type of the distributions. Should be "Cauchy" in this case. loc_b (Tensor): The loc of distribution b. scale_b (Tensor): The scale of distribution b. loc (Tensor): The loc of distribution a. Default: self.loc. scale (Tensor): The scale of distribution a. Default: self.scale. """ check_distribution_name(dist, 'Cauchy') return self._entropy(loc_a, scale_a) + self._kl_loss(dist, loc_b, scale_b, loc_a, scale_a)
[ "def", "_cross_entropy", "(", "self", ",", "dist", ",", "loc_b", ",", "scale_b", ",", "loc_a", "=", "None", ",", "scale_a", "=", "None", ")", ":", "check_distribution_name", "(", "dist", ",", "'Cauchy'", ")", "return", "self", ".", "_entropy", "(", "loc_...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/cauchy.py#L355-L367
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/fpformat.py
python
sci
(x, digs)
return s + 'e' + e
Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed.
Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed.
[ "Format", "x", "as", "[", "-", "]", "d", ".", "dddE", "[", "+", "-", "]", "ddd", "with", "digs", "digits", "after", "the", "point", "and", "exactly", "one", "digit", "before", ".", "If", "digs", "is", "<", "=", "0", "one", "digit", "is", "kept", ...
def sci(x, digs): """Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed.""" if type(x) != type(''): x = repr(x) sign, intpart, fraction, expo = extract(x) if not intpart: while fraction and fraction[0] == '0': fraction = fraction[1:] expo = expo - 1 if fraction: intpart, fraction = fraction[0], fraction[1:] expo = expo - 1 else: intpart = '0' else: expo = expo + len(intpart) - 1 intpart, fraction = intpart[0], intpart[1:] + fraction digs = max(0, digs) intpart, fraction = roundfrac(intpart, fraction, digs) if len(intpart) > 1: intpart, fraction, expo = \ intpart[0], intpart[1:] + fraction[:-1], \ expo + len(intpart) - 1 s = sign + intpart if digs > 0: s = s + '.' + fraction e = repr(abs(expo)) e = '0'*(3-len(e)) + e if expo < 0: e = '-' + e else: e = '+' + e return s + 'e' + e
[ "def", "sci", "(", "x", ",", "digs", ")", ":", "if", "type", "(", "x", ")", "!=", "type", "(", "''", ")", ":", "x", "=", "repr", "(", "x", ")", "sign", ",", "intpart", ",", "fraction", ",", "expo", "=", "extract", "(", "x", ")", "if", "not"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/fpformat.py#L107-L137
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/keras/python/keras/utils/conv_utils.py
python
conv_output_length
(input_length, filter_size, padding, stride, dilation=1)
return (output_length + stride - 1) // stride
Determines output length of a convolution given input length. Arguments: input_length: integer. filter_size: integer. padding: one of "same", "valid", "full". stride: integer. dilation: dilation rate, integer. Returns: The output length (integer).
Determines output length of a convolution given input length.
[ "Determines", "output", "length", "of", "a", "convolution", "given", "input", "length", "." ]
def conv_output_length(input_length, filter_size, padding, stride, dilation=1): """Determines output length of a convolution given input length. Arguments: input_length: integer. filter_size: integer. padding: one of "same", "valid", "full". stride: integer. dilation: dilation rate, integer. Returns: The output length (integer). """ if input_length is None: return None assert padding in {'same', 'valid', 'full', 'causal'} dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1) if padding == 'same': output_length = input_length elif padding == 'valid': output_length = input_length - dilated_filter_size + 1 elif padding == 'full': output_length = input_length + dilated_filter_size - 1 elif padding == 'causal': output_length = input_length return (output_length + stride - 1) // stride
[ "def", "conv_output_length", "(", "input_length", ",", "filter_size", ",", "padding", ",", "stride", ",", "dilation", "=", "1", ")", ":", "if", "input_length", "is", "None", ":", "return", "None", "assert", "padding", "in", "{", "'same'", ",", "'valid'", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/utils/conv_utils.py#L109-L134
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/cat_helper.py
python
CatHelper.__init__
(self, command_obj)
Initializes the helper object. Args: command_obj: gsutil command instance of calling command.
Initializes the helper object.
[ "Initializes", "the", "helper", "object", "." ]
def __init__(self, command_obj): """Initializes the helper object. Args: command_obj: gsutil command instance of calling command. """ self.command_obj = command_obj
[ "def", "__init__", "(", "self", ",", "command_obj", ")", ":", "self", ".", "command_obj", "=", "command_obj" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/cat_helper.py#L27-L33
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/ValidationKit/common/utils.py
python
timestampMilli
()
return long(time.time() * 1000)
Gets a millisecond timestamp.
Gets a millisecond timestamp.
[ "Gets", "a", "millisecond", "timestamp", "." ]
def timestampMilli(): """ Gets a millisecond timestamp. """ if g_fWinUseWinPerfCounter is True: return long(_winFloatTime() * 1000); return long(time.time() * 1000);
[ "def", "timestampMilli", "(", ")", ":", "if", "g_fWinUseWinPerfCounter", "is", "True", ":", "return", "long", "(", "_winFloatTime", "(", ")", "*", "1000", ")", "return", "long", "(", "time", ".", "time", "(", ")", "*", "1000", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/utils.py#L1279-L1285
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/mox.py
python
MockMethod.__eq__
(self, rhs)
return (isinstance(rhs, MockMethod) and self._name == rhs._name and self._params == rhs._params and self._named_params == rhs._named_params)
Test whether this MockMethod is equivalent to another MockMethod. Args: # rhs: the right hand side of the test rhs: MockMethod
Test whether this MockMethod is equivalent to another MockMethod.
[ "Test", "whether", "this", "MockMethod", "is", "equivalent", "to", "another", "MockMethod", "." ]
def __eq__(self, rhs): """Test whether this MockMethod is equivalent to another MockMethod. Args: # rhs: the right hand side of the test rhs: MockMethod """ return (isinstance(rhs, MockMethod) and self._name == rhs._name and self._params == rhs._params and self._named_params == rhs._named_params)
[ "def", "__eq__", "(", "self", ",", "rhs", ")", ":", "return", "(", "isinstance", "(", "rhs", ",", "MockMethod", ")", "and", "self", ".", "_name", "==", "rhs", ".", "_name", "and", "self", ".", "_params", "==", "rhs", ".", "_params", "and", "self", ...
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/mox.py#L622-L633
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py
python
ParserElement.transformString
( self, instring )
Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
[ "Extension", "to", "C", "{", "L", "{", "scanString", "}}", "to", "modify", "matching", "text", "with", "modified", "tokens", "that", "may", "be", "returned", "from", "a", "parse", "action", ".", "To", "use", "C", "{", "transformString", "}", "define", "a...
def transformString( self, instring ): """ Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. """ out = [] lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to # keep string locs straight between transformString and scanString self.keepTabs = True try: for t,s,e in self.scanString( instring ): out.append( instring[lastE:s] ) if t: if isinstance(t,ParseResults): out += t.asList() elif isinstance(t,list): out += t else: out.append(t) lastE = e out.append(instring[lastE:]) out = [o for o in out if o] return "".join(map(_ustr,_flatten(out))) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
[ "def", "transformString", "(", "self", ",", "instring", ")", ":", "out", "=", "[", "]", "lastE", "=", "0", "# force preservation of <TAB>s, to minimize unwanted transformation of string, and to", "# keep string locs straight between transformString and scanString", "self", ".", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L1729-L1770
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/style/cpplint.py
python
CleanseComments
(line)
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed.
Removes //-comments and single-line C-style /* */ comments.
[ "Removes", "//", "-", "comments", "and", "single", "-", "line", "C", "-", "style", "/", "*", "*", "/", "comments", "." ]
def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
[ "def", "CleanseComments", "(", "line", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", "and", "not", "IsCppString", "(", "line", "[", ":", "commentpos", "]", ")", ":", "line", "=", "line", "[", ...
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L1639-L1652
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/operator.py
python
PythonOp.forward
(self, in_data, out_data)
Forward interface. Override to create new operators. Parameters ---------- in_data, out_data: list input and output for forward. See document for corresponding arguments of Operator::Forward
Forward interface. Override to create new operators.
[ "Forward", "interface", ".", "Override", "to", "create", "new", "operators", "." ]
def forward(self, in_data, out_data): """Forward interface. Override to create new operators. Parameters ---------- in_data, out_data: list input and output for forward. See document for corresponding arguments of Operator::Forward """ out_data[0][:] = in_data[0]
[ "def", "forward", "(", "self", ",", "in_data", ",", "out_data", ")", ":", "out_data", "[", "0", "]", "[", ":", "]", "=", "in_data", "[", "0", "]" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/operator.py#L76-L85
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/tensor.py
python
add_column
(alpha, v, beta, M)
return M
Add v to each column of M. Denote each column of M as m, m = alpha * v + beta * m Args: alpha (float): scalar factor v (Tensor): a tensor beta (float): scalar factor M (Tensor): 2d tensor Returns: Resulted tensor M
Add v to each column of M.
[ "Add", "v", "to", "each", "column", "of", "M", "." ]
def add_column(alpha, v, beta, M): '''Add v to each column of M. Denote each column of M as m, m = alpha * v + beta * m Args: alpha (float): scalar factor v (Tensor): a tensor beta (float): scalar factor M (Tensor): 2d tensor Returns: Resulted tensor M ''' singa.AddColumnWithScale(float(alpha), float(beta), v.data, M.data) return M
[ "def", "add_column", "(", "alpha", ",", "v", ",", "beta", ",", "M", ")", ":", "singa", ".", "AddColumnWithScale", "(", "float", "(", "alpha", ")", ",", "float", "(", "beta", ")", ",", "v", ".", "data", ",", "M", ".", "data", ")", "return", "M" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/tensor.py#L1687-L1702
VowpalWabbit/vowpal_wabbit
866b8fa88ff85a957c7eb72065ea44518b9ba416
python/vowpalwabbit/sklearn.py
python
VW.fit
(self, X=None, y=None, sample_weight=None)
return self
Fit the model according to the given training data TODO: For first pass create and store example objects. For N-1 passes use example objects directly (simulate cache file...but in memory for faster processing) Args: X : {array-like, sparse matrix}, shape (n_samples, n_features or 1 if not convert_to_vw) or Training vector, where n_samples in the number of samples and n_features is the number of features. if not using convert_to_vw, X is expected to be a list of vw formatted feature vector strings with labels y : array-like, shape (n_samples,), optional if not convert_to_vw Target vector relative to X. sample_weight : array-like, shape (n_samples,) sample weight vector relative to X. Returns: self
Fit the model according to the given training data
[ "Fit", "the", "model", "according", "to", "the", "given", "training", "data" ]
def fit(self, X=None, y=None, sample_weight=None): """Fit the model according to the given training data TODO: For first pass create and store example objects. For N-1 passes use example objects directly (simulate cache file...but in memory for faster processing) Args: X : {array-like, sparse matrix}, shape (n_samples, n_features or 1 if not convert_to_vw) or Training vector, where n_samples in the number of samples and n_features is the number of features. if not using convert_to_vw, X is expected to be a list of vw formatted feature vector strings with labels y : array-like, shape (n_samples,), optional if not convert_to_vw Target vector relative to X. sample_weight : array-like, shape (n_samples,) sample weight vector relative to X. Returns: self """ params = {k: v for k, v in self.get_params().items() if v is not None} passes = 1 use_data_file = params.get("data", params.get("d", False)) if not use_data_file: # remove passes from vw params since we're feeding in the data manually passes = params.pop("passes", passes) if params.get("bfgs", False): raise RuntimeError( "An external data file must be used to fit models using the bfgs option" ) # remove estimator attributes from vw params for key in self._get_est_params(): params.pop(key, None) # add vw attributes params.update(self._get_vw_params()) self.vw_ = Workspace(**params) if X is not None: if self.convert_to_vw: X = tovw( x=X, y=y, sample_weight=sample_weight, convert_labels=self.convert_labels, ) # add examples to model for n in range(passes): if n >= 1: examples = shuffle(X) else: examples = X for idx, example in enumerate(examples): self.vw_.learn(example) return self
[ "def", "fit", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ",", "sample_weight", "=", "None", ")", ":", "params", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "get_params", "(", ")", ".", "items", "(", ")", ...
https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/sklearn.py#L304-L364
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
TreeCtrl.EditLabel
(*args, **kwargs)
return _controls_.TreeCtrl_EditLabel(*args, **kwargs)
EditLabel(self, TreeItemId item)
EditLabel(self, TreeItemId item)
[ "EditLabel", "(", "self", "TreeItemId", "item", ")" ]
def EditLabel(*args, **kwargs): """EditLabel(self, TreeItemId item)""" return _controls_.TreeCtrl_EditLabel(*args, **kwargs)
[ "def", "EditLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_EditLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5527-L5529
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_printer.py
python
dump_declarations
(declarations, file_path)
Dump declarations tree rooted at each of the included nodes to the file :param declarations: either a single :class:declaration_t object or a list of :class:declaration_t objects :param file_path: path to a file
Dump declarations tree rooted at each of the included nodes to the file
[ "Dump", "declarations", "tree", "rooted", "at", "each", "of", "the", "included", "nodes", "to", "the", "file" ]
def dump_declarations(declarations, file_path): """ Dump declarations tree rooted at each of the included nodes to the file :param declarations: either a single :class:declaration_t object or a list of :class:declaration_t objects :param file_path: path to a file """ with open(file_path, "w+") as f: print_declarations(declarations, writer=f.write)
[ "def", "dump_declarations", "(", "declarations", ",", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "\"w+\"", ")", "as", "f", ":", "print_declarations", "(", "declarations", ",", "writer", "=", "f", ".", "write", ")" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_printer.py#L455-L466
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/Queue.py
python
Queue.get
(self, block=True, timeout=None)
Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case).
Remove and return an item from the queue.
[ "Remove", "and", "return", "an", "item", "from", "the", "queue", "." ]
def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). """ self.not_empty.acquire() try: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a positive number") else: endtime = _time() + timeout while not self._qsize(): remaining = endtime - _time() if remaining <= 0.0: raise Empty self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item finally: self.not_empty.release()
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "not_empty", ".", "acquire", "(", ")", "try", ":", "if", "not", "block", ":", "if", "not", "self", ".", "_qsize", "(", ")", ":", "raise", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/Queue.py#L150-L182
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/nn.py
python
logical_not
(x, out=None, name=None)
return _logical_op( op_name="logical_not", x=x, y=None, name=name, out=out, binary_op=False)
``logical_not`` operator computes element-wise logical NOT on ``x``, and returns ``out``. ``out`` is N-dim boolean ``Variable``. Each element of ``out`` is calculated by .. math:: out = !x Args: x(Tensor): Operand of logical_not operator. Must be a Tensor of type bool, int8, int16, in32, in64, float32, or float64. out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor` will be created to save the output. name(str|None): The default value is None. Normally there is no need for users to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: ${out_comment} Examples: .. code-block:: python import paddle x = paddle.to_tensor([True, False, True, False]) res = paddle.logical_not(x) print(res) # [False True False True]
[]
def logical_not(x, out=None, name=None): """ ``logical_not`` operator computes element-wise logical NOT on ``x``, and returns ``out``. ``out`` is N-dim boolean ``Variable``. Each element of ``out`` is calculated by .. math:: out = !x Args: x(Tensor): Operand of logical_not operator. Must be a Tensor of type bool, int8, int16, in32, in64, float32, or float64. out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor` will be created to save the output. name(str|None): The default value is None. Normally there is no need for users to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: ${out_comment} Examples: .. code-block:: python import paddle x = paddle.to_tensor([True, False, True, False]) res = paddle.logical_not(x) print(res) # [False True False True] """ return _logical_op( op_name="logical_not", x=x, y=None, name=name, out=out, binary_op=False)
[ "def", "logical_not", "(", "x", ",", "out", "=", "None", ",", "name", "=", "None", ")", ":", "return", "_logical_op", "(", "op_name", "=", "\"logical_not\"", ",", "x", "=", "x", ",", "y", "=", "None", ",", "name", "=", "name", ",", "out", "=", "o...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/nn.py#L12505-L12534
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/ltisys.py
python
_KNV0
(B, ker_pole, transfer_matrix, j, poles)
Algorithm "KNV0" Kautsky et Al. Robust pole assignment in linear state feedback, Int journal of Control 1985, vol 41 p 1129->1155 https://la.epfl.ch/files/content/sites/la/files/ users/105941/public/KautskyNicholsDooren
Algorithm "KNV0" Kautsky et Al. Robust pole assignment in linear state feedback, Int journal of Control 1985, vol 41 p 1129->1155 https://la.epfl.ch/files/content/sites/la/files/ users/105941/public/KautskyNicholsDooren
[ "Algorithm", "KNV0", "Kautsky", "et", "Al", ".", "Robust", "pole", "assignment", "in", "linear", "state", "feedback", "Int", "journal", "of", "Control", "1985", "vol", "41", "p", "1129", "-", ">", "1155", "https", ":", "//", "la", ".", "epfl", ".", "ch...
def _KNV0(B, ker_pole, transfer_matrix, j, poles): """ Algorithm "KNV0" Kautsky et Al. Robust pole assignment in linear state feedback, Int journal of Control 1985, vol 41 p 1129->1155 https://la.epfl.ch/files/content/sites/la/files/ users/105941/public/KautskyNicholsDooren """ # Remove xj form the base transfer_matrix_not_j = np.delete(transfer_matrix, j, axis=1) # If we QR this matrix in full mode Q=Q0|Q1 # then Q1 will be a single column orthogonnal to # Q0, that's what we are looking for ! # After merge of gh-4249 great speed improvements could be achieved # using QR updates instead of full QR in the line below # To debug with numpy qr uncomment the line below # Q, R = np.linalg.qr(transfer_matrix_not_j, mode="complete") Q, R = s_qr(transfer_matrix_not_j, mode="full") mat_ker_pj = np.dot(ker_pole[j], ker_pole[j].T) yj = np.dot(mat_ker_pj, Q[:, -1]) # If Q[:, -1] is "almost" orthogonal to ker_pole[j] its # projection into ker_pole[j] will yield a vector # close to 0. As we are looking for a vector in ker_pole[j] # simply stick with transfer_matrix[:, j] (unless someone provides me with # a better choice ?) if not np.allclose(yj, 0): xj = yj/np.linalg.norm(yj) transfer_matrix[:, j] = xj
[ "def", "_KNV0", "(", "B", ",", "ker_pole", ",", "transfer_matrix", ",", "j", ",", "poles", ")", ":", "# Remove xj form the base", "transfer_matrix_not_j", "=", "np", ".", "delete", "(", "transfer_matrix", ",", "j", ",", "axis", "=", "1", ")", "# If we QR thi...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L2568-L2601
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.SetPositionCacheSize
(*args, **kwargs)
return _stc.StyledTextCtrl_SetPositionCacheSize(*args, **kwargs)
SetPositionCacheSize(self, int size) Set number of entries in position cache
SetPositionCacheSize(self, int size)
[ "SetPositionCacheSize", "(", "self", "int", "size", ")" ]
def SetPositionCacheSize(*args, **kwargs): """ SetPositionCacheSize(self, int size) Set number of entries in position cache """ return _stc.StyledTextCtrl_SetPositionCacheSize(*args, **kwargs)
[ "def", "SetPositionCacheSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetPositionCacheSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L5727-L5733
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/keystone.py
python
dict_to_args
(specials, items)
return args
Transform [(key1, val1), (special, val_special), (key3, val3) ] into: [ '--key1', 'val1', '--key3', 'val3', 'val_special' ]
Transform [(key1, val1), (special, val_special), (key3, val3) ] into: [ '--key1', 'val1', '--key3', 'val3', 'val_special' ]
[ "Transform", "[", "(", "key1", "val1", ")", "(", "special", "val_special", ")", "(", "key3", "val3", ")", "]", "into", ":", "[", "--", "key1", "val1", "--", "key3", "val3", "val_special", "]" ]
def dict_to_args(specials, items): """ Transform [(key1, val1), (special, val_special), (key3, val3) ] into: [ '--key1', 'val1', '--key3', 'val3', 'val_special' ] """ args = [] special_vals = OrderedDict((k, '') for k in specials.split(',')) for (k, v) in items: if k in special_vals: special_vals[k] = v else: args.append('--{k}'.format(k=k)) args.append(v) args.extend(arg for arg in special_vals.values() if arg) return args
[ "def", "dict_to_args", "(", "specials", ",", "items", ")", ":", "args", "=", "[", "]", "special_vals", "=", "OrderedDict", "(", "(", "k", ",", "''", ")", "for", "k", "in", "specials", ".", "split", "(", "','", ")", ")", "for", "(", "k", ",", "v",...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/keystone.py#L288-L304
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/csv.py
python
Sniffer._guess_delimiter
(self, data, delimiters)
return (delim, skipinitialspace)
The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1) build a table of the frequency of each character on every line. 2) build a table of frequencies of this frequency (meta-frequency?), e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows, 7 times in 2 rows' 3) use the mode of the meta-frequency to determine the /expected/ frequency for that character 4) find out how often the character actually meets that goal 5) the character that best meets its goal is the delimiter For performance reasons, the data is evaluated in chunks, so it can try and evaluate the smallest portion of the data possible, evaluating additional chunks as necessary.
The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1) build a table of the frequency of each character on every line. 2) build a table of frequencies of this frequency (meta-frequency?), e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows, 7 times in 2 rows' 3) use the mode of the meta-frequency to determine the /expected/ frequency for that character 4) find out how often the character actually meets that goal 5) the character that best meets its goal is the delimiter For performance reasons, the data is evaluated in chunks, so it can try and evaluate the smallest portion of the data possible, evaluating additional chunks as necessary.
[ "The", "delimiter", "/", "should", "/", "occur", "the", "same", "number", "of", "times", "on", "each", "row", ".", "However", "due", "to", "malformed", "data", "it", "may", "not", ".", "We", "don", "t", "want", "an", "all", "or", "nothing", "approach",...
def _guess_delimiter(self, data, delimiters): """ The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1) build a table of the frequency of each character on every line. 2) build a table of frequencies of this frequency (meta-frequency?), e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows, 7 times in 2 rows' 3) use the mode of the meta-frequency to determine the /expected/ frequency for that character 4) find out how often the character actually meets that goal 5) the character that best meets its goal is the delimiter For performance reasons, the data is evaluated in chunks, so it can try and evaluate the smallest portion of the data possible, evaluating additional chunks as necessary. """ data = filter(None, data.split('\n')) ascii = [chr(c) for c in range(127)] # 7-bit ASCII # build frequency tables chunkLength = min(10, len(data)) iteration = 0 charFrequency = {} modes = {} delims = {} start, end = 0, min(chunkLength, len(data)) while start < len(data): iteration += 1 for line in data[start:end]: for char in ascii: metaFrequency = charFrequency.get(char, {}) # must count even if frequency is 0 freq = line.count(char) # value is the mode metaFrequency[freq] = metaFrequency.get(freq, 0) + 1 charFrequency[char] = metaFrequency for char in charFrequency.keys(): items = charFrequency[char].items() if len(items) == 1 and items[0][0] == 0: continue # get the mode of the frequencies if len(items) > 1: modes[char] = reduce(lambda a, b: a[1] > b[1] and a or b, items) # adjust the mode - subtract the sum of all # other frequencies items.remove(modes[char]) modes[char] = (modes[char][0], modes[char][1] - reduce(lambda a, b: (0, a[1] + b[1]), items)[1]) else: modes[char] = items[0] # build a list of possible delimiters modeList = modes.items() total = float(chunkLength * iteration) # (rows of consistent data) / (number of rows) = 100% consistency = 1.0 # minimum consistency threshold threshold = 0.9 while len(delims) == 0 and consistency >= threshold: for k, v in modeList: if v[0] > 0 and v[1] > 0: if ((v[1]/total) >= consistency and (delimiters is None or k in delimiters)): delims[k] = v consistency -= 0.01 if len(delims) == 1: delim = delims.keys()[0] skipinitialspace = (data[0].count(delim) == data[0].count("%c " % delim)) return (delim, skipinitialspace) # analyze another chunkLength lines start = end end += chunkLength if not delims: return ('', 0) # if there's more than one, fall back to a 'preferred' list if len(delims) > 1: for d in self.preferred: if d in delims.keys(): skipinitialspace = (data[0].count(d) == data[0].count("%c " % d)) return (d, skipinitialspace) # nothing else indicates a preference, pick the character that # dominates(?) items = [(v,k) for (k,v) in delims.items()] items.sort() delim = items[-1][1] skipinitialspace = (data[0].count(delim) == data[0].count("%c " % delim)) return (delim, skipinitialspace)
[ "def", "_guess_delimiter", "(", "self", ",", "data", ",", "delimiters", ")", ":", "data", "=", "filter", "(", "None", ",", "data", ".", "split", "(", "'\\n'", ")", ")", "ascii", "=", "[", "chr", "(", "c", ")", "for", "c", "in", "range", "(", "127...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/csv.py#L277-L379
twtygqyy/caffe-augmentation
c76600d247e5132fa5bd89d87bb5df458341fa84
scripts/cpp_lint.py
python
_FunctionState.Check
(self, error, filename, linenum)
Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check.
Report if too many lines in function body.
[ "Report", "if", "too", "many", "lines", "in", "function", "body", "." ]
def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger))
[ "def", "Check", "(", "self", ",", "error", ",", "filename", ",", "linenum", ")", ":", "if", "Match", "(", "r'T(EST|est)'", ",", "self", ".", "current_function", ")", ":", "base_trigger", "=", "self", ".", "_TEST_TRIGGER", "else", ":", "base_trigger", "=", ...
https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L840-L863
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py
python
_MaskedBinaryOperation.accumulate
(self, target, axis=0)
return masked_result
Accumulate `target` along `axis` after filling with y fill value.
Accumulate `target` along `axis` after filling with y fill value.
[ "Accumulate", "target", "along", "axis", "after", "filling", "with", "y", "fill", "value", "." ]
def accumulate(self, target, axis=0): """Accumulate `target` along `axis` after filling with y fill value. """ tclass = get_masked_subclass(target) t = filled(target, self.filly) result = self.f.accumulate(t, axis) masked_result = result.view(tclass) return masked_result
[ "def", "accumulate", "(", "self", ",", "target", ",", "axis", "=", "0", ")", ":", "tclass", "=", "get_masked_subclass", "(", "target", ")", "t", "=", "filled", "(", "target", ",", "self", ".", "filly", ")", "result", "=", "self", ".", "f", ".", "ac...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L1118-L1127
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py
python
_path_isfile
(path)
return _path_is_mode_type(path, 0o100000)
Replacement for os.path.isfile.
Replacement for os.path.isfile.
[ "Replacement", "for", "os", ".", "path", ".", "isfile", "." ]
def _path_isfile(path): """Replacement for os.path.isfile.""" return _path_is_mode_type(path, 0o100000)
[ "def", "_path_isfile", "(", "path", ")", ":", "return", "_path_is_mode_type", "(", "path", ",", "0o100000", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py#L93-L95
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/environment.py
python
Environment.call_test
(self, name, value, args=None, kwargs=None)
return func(value, *(args or ()), **(kwargs or {}))
Invokes a test on a value the same way the compiler does it. .. versionadded:: 2.7
Invokes a test on a value the same way the compiler does it.
[ "Invokes", "a", "test", "on", "a", "value", "the", "same", "way", "the", "compiler", "does", "it", "." ]
def call_test(self, name, value, args=None, kwargs=None): """Invokes a test on a value the same way the compiler does it. .. versionadded:: 2.7 """ func = self.tests.get(name) if func is None: fail_for_missing_callable('no test named %r', name) return func(value, *(args or ()), **(kwargs or {}))
[ "def", "call_test", "(", "self", ",", "name", ",", "value", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "func", "=", "self", ".", "tests", ".", "get", "(", "name", ")", "if", "func", "is", "None", ":", "fail_for_missing_callable",...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/environment.py#L469-L477
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/util.py
python
grok_environment_error
(exc, prefix="error: ")
return error
Generate a useful error message from an EnvironmentError (IOError or OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and does what it can to deal with exception objects that don't have a filename (which happens when the error is due to a two-file operation, such as 'rename()' or 'link()'. Returns the error message as a string prefixed with 'prefix'.
Generate a useful error message from an EnvironmentError (IOError or OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and does what it can to deal with exception objects that don't have a filename (which happens when the error is due to a two-file operation, such as 'rename()' or 'link()'. Returns the error message as a string prefixed with 'prefix'.
[ "Generate", "a", "useful", "error", "message", "from", "an", "EnvironmentError", "(", "IOError", "or", "OSError", ")", "exception", "object", ".", "Handles", "Python", "1", ".", "5", ".", "1", "and", "1", ".", "5", ".", "2", "styles", "and", "does", "w...
def grok_environment_error (exc, prefix="error: "): """Generate a useful error message from an EnvironmentError (IOError or OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and does what it can to deal with exception objects that don't have a filename (which happens when the error is due to a two-file operation, such as 'rename()' or 'link()'. Returns the error message as a string prefixed with 'prefix'. """ # check for Python 1.5.2-style {IO,OS}Error exception objects if hasattr(exc, 'filename') and hasattr(exc, 'strerror'): if exc.filename: error = prefix + "%s: %s" % (exc.filename, exc.strerror) else: # two-argument functions in posix module don't # include the filename in the exception object! error = prefix + "%s" % exc.strerror else: error = prefix + str(exc[-1]) return error
[ "def", "grok_environment_error", "(", "exc", ",", "prefix", "=", "\"error: \"", ")", ":", "# check for Python 1.5.2-style {IO,OS}Error exception objects", "if", "hasattr", "(", "exc", ",", "'filename'", ")", "and", "hasattr", "(", "exc", ",", "'strerror'", ")", ":",...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/util.py#L215-L234
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distribution/distribution.py
python
Distribution.event_shape
(self)
return self._event_shape
Returns event shape of distribution Returns: Sequence[int]: event shape
Returns event shape of distribution
[ "Returns", "event", "shape", "of", "distribution" ]
def event_shape(self): """Returns event shape of distribution Returns: Sequence[int]: event shape """ return self._event_shape
[ "def", "event_shape", "(", "self", ")", ":", "return", "self", ".", "_event_shape" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distribution/distribution.py#L73-L79
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/linalg/linear_operator_addition.py
python
_Adder.can_add
(self, op1, op2)
Returns `True` if this `Adder` can add `op1` and `op2`. Else `False`.
Returns `True` if this `Adder` can add `op1` and `op2`. Else `False`.
[ "Returns", "True", "if", "this", "Adder", "can", "add", "op1", "and", "op2", ".", "Else", "False", "." ]
def can_add(self, op1, op2): """Returns `True` if this `Adder` can add `op1` and `op2`. Else `False`.""" pass
[ "def", "can_add", "(", "self", ",", "op1", ",", "op2", ")", ":", "pass" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg/linear_operator_addition.py#L249-L251
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/profiler/profile_context.py
python
_profiled_run
(self, fetches, feed_dict=None, options=None, run_metadata=None)
return self._profiler_run_internal( fetches, feed_dict, options, run_metadata)
Overwrites the session.run().
Overwrites the session.run().
[ "Overwrites", "the", "session", ".", "run", "()", "." ]
def _profiled_run(self, fetches, feed_dict=None, options=None, run_metadata=None): """Overwrites the session.run().""" # pylint: disable=protected-access # Count the session steps. with self.profile_context._new_step() as state: step, locked = state # Fast path if no need for profiling. if locked and not self.profile_context._is_fast_path(step): # Maybe trace this step. if self.profile_context._should_trace(step, self.graph, fetches): if self.profile_context._debug: sys.stderr.write('debug: tracing step: %d\n' % step) # Enable tracing, perform auto profiling or auto dump. if not run_metadata: run_metadata = config_pb2.RunMetadata() if not options: options = config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE) old_trace_level = options.trace_level else: old_trace_level = options.trace_level options.trace_level = config_pb2.RunOptions.FULL_TRACE ret = self._profiler_run_internal( fetches, feed_dict, options, run_metadata) if self.profile_context._debug: self.profile_context._dump_file(run_metadata, 'run_meta_%d' % step) self.profile_context.profiler._graph = self.graph self.profile_context.profiler.add_step(step, run_metadata) options.trace_level = old_trace_level else: ret = self._profiler_run_internal(fetches, feed_dict, options) # Maybe dump profile. self.profile_context._maybe_dump(step) # Maybe profile: to_profiles = self.profile_context._profile_candidates() for to_prof in to_profiles: cmd, opts, _ = to_prof saved_views = self.profile_context._views.setdefault(cmd, {}) if self.profile_context._debug: sys.stderr.write('debug: profiling %s step: %d\n' % (cmd, step)) if cmd == 'graph': saved_views[step] = self.profile_context.profiler.profile_graph(opts) elif cmd == 'scope': saved_views[step] = self.profile_context.profiler.profile_name_scope( opts) elif cmd == 'op': saved_views[step] = self.profile_context.profiler.profile_operations( opts) elif cmd == 'code': saved_views[step] = self.profile_context.profiler.profile_python(opts) else: raise ValueError('Unknown cmd: %s\n' % cmd) return ret # Fast no lock path. return self._profiler_run_internal( fetches, feed_dict, options, run_metadata)
[ "def", "_profiled_run", "(", "self", ",", "fetches", ",", "feed_dict", "=", "None", ",", "options", "=", "None", ",", "run_metadata", "=", "None", ")", ":", "# pylint: disable=protected-access", "# Count the session steps.", "with", "self", ".", "profile_context", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/profiler/profile_context.py#L45-L109
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
Geometry3D.saveFile
(self, fn)
return _robotsim.Geometry3D_saveFile(self, fn)
saveFile(Geometry3D self, char const * fn) -> bool Saves to file. Standard mesh types, PCD files, and .geom files are supported.
saveFile(Geometry3D self, char const * fn) -> bool
[ "saveFile", "(", "Geometry3D", "self", "char", "const", "*", "fn", ")", "-", ">", "bool" ]
def saveFile(self, fn): """ saveFile(Geometry3D self, char const * fn) -> bool Saves to file. Standard mesh types, PCD files, and .geom files are supported. """ return _robotsim.Geometry3D_saveFile(self, fn)
[ "def", "saveFile", "(", "self", ",", "fn", ")", ":", "return", "_robotsim", ".", "Geometry3D_saveFile", "(", "self", ",", "fn", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L2134-L2143
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/encodings/__init__.py
python
normalize_encoding
(encoding)
return '_'.join(encoding.translate(_norm_encoding_map).split())
Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are collapsed and replaced with a single underscore, e.g. ' -;#' becomes '_'. Leading and trailing underscores are removed. Note that encoding names should be ASCII only; if they do use non-ASCII characters, these must be Latin-1 compatible.
Normalize an encoding name.
[ "Normalize", "an", "encoding", "name", "." ]
def normalize_encoding(encoding): """ Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are collapsed and replaced with a single underscore, e.g. ' -;#' becomes '_'. Leading and trailing underscores are removed. Note that encoding names should be ASCII only; if they do use non-ASCII characters, these must be Latin-1 compatible. """ # Make sure we have an 8-bit string, because .translate() works # differently for Unicode strings. if hasattr(__builtin__, "unicode") and isinstance(encoding, unicode): # Note that .encode('latin-1') does *not* use the codec # registry, so this call doesn't recurse. (See unicodeobject.c # PyUnicode_AsEncodedString() for details) encoding = encoding.encode('latin-1') return '_'.join(encoding.translate(_norm_encoding_map).split())
[ "def", "normalize_encoding", "(", "encoding", ")", ":", "# Make sure we have an 8-bit string, because .translate() works", "# differently for Unicode strings.", "if", "hasattr", "(", "__builtin__", ",", "\"unicode\"", ")", "and", "isinstance", "(", "encoding", ",", "unicode",...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/encodings/__init__.py#L49-L69
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TextAttr.Apply
(*args, **kwargs)
return _controls_.TextAttr_Apply(*args, **kwargs)
Apply(self, TextAttr style, TextAttr compareWith=None) -> bool
Apply(self, TextAttr style, TextAttr compareWith=None) -> bool
[ "Apply", "(", "self", "TextAttr", "style", "TextAttr", "compareWith", "=", "None", ")", "-", ">", "bool" ]
def Apply(*args, **kwargs): """Apply(self, TextAttr style, TextAttr compareWith=None) -> bool""" return _controls_.TextAttr_Apply(*args, **kwargs)
[ "def", "Apply", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_Apply", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L1912-L1914
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/reinforcement-learning/a3c/launcher.py
python
exec_cmd
(cmd, role, taskid, pass_env)
Execute the command line command.
Execute the command line command.
[ "Execute", "the", "command", "line", "command", "." ]
def exec_cmd(cmd, role, taskid, pass_env): """Execute the command line command.""" if cmd[0].find('/') == -1 and os.path.exists(cmd[0]) and os.name != 'nt': cmd[0] = './' + cmd[0] cmd = ' '.join(cmd) env = os.environ.copy() for k, v in pass_env.items(): env[k] = str(v) env['DMLC_TASK_ID'] = str(taskid) env['DMLC_ROLE'] = role env['DMLC_JOB_CLUSTER'] = 'local' ntrial = 0 while True: if os.name == 'nt': env['DMLC_NUM_ATTEMPT'] = str(ntrial) ret = subprocess.call(cmd, shell=True, env=env) if ret != 0: ntrial += 1 continue else: bash = cmd ret = subprocess.call(bash, shell=True, executable='bash', env=env) if ret == 0: logging.debug('Thread %d exit with 0', taskid) return else: if os.name == 'nt': sys.exit(-1) else: raise RuntimeError('Get nonzero return code=%d' % ret)
[ "def", "exec_cmd", "(", "cmd", ",", "role", ",", "taskid", ",", "pass_env", ")", ":", "if", "cmd", "[", "0", "]", ".", "find", "(", "'/'", ")", "==", "-", "1", "and", "os", ".", "path", ".", "exists", "(", "cmd", "[", "0", "]", ")", "and", ...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/reinforcement-learning/a3c/launcher.py#L46-L77
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
third_party/gpus/find_cuda_config.py
python
_find_library
(base_paths, library_name, required_version)
return _find_file(base_paths, _library_paths(), filepattern)
Returns first valid path to the requested library.
Returns first valid path to the requested library.
[ "Returns", "first", "valid", "path", "to", "the", "requested", "library", "." ]
def _find_library(base_paths, library_name, required_version): """Returns first valid path to the requested library.""" if _is_windows(): filepattern = library_name + ".lib" elif _is_macos(): filepattern = "%s*.dylib" % (".".join(["lib" + library_name] + required_version.split(".")[:1])) else: filepattern = ".".join(["lib" + library_name, "so"] + required_version.split(".")[:1]) + "*" return _find_file(base_paths, _library_paths(), filepattern)
[ "def", "_find_library", "(", "base_paths", ",", "library_name", ",", "required_version", ")", ":", "if", "_is_windows", "(", ")", ":", "filepattern", "=", "library_name", "+", "\".lib\"", "elif", "_is_macos", "(", ")", ":", "filepattern", "=", "\"%s*.dylib\"", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/third_party/gpus/find_cuda_config.py#L212-L222
wheybags/freeablo
921ac20be95828460ccc184a9de11eca5c7c0519
extern/SDL_image/external/libwebp-0.3.0/swig/libwebp.py
python
WebPDecodeRGBA
(*args)
return _libwebp.WebPDecodeRGBA(*args)
WebPDecodeRGBA(uint8_t data) -> (rgb, width, height)
WebPDecodeRGBA(uint8_t data) -> (rgb, width, height)
[ "WebPDecodeRGBA", "(", "uint8_t", "data", ")", "-", ">", "(", "rgb", "width", "height", ")" ]
def WebPDecodeRGBA(*args): """WebPDecodeRGBA(uint8_t data) -> (rgb, width, height)""" return _libwebp.WebPDecodeRGBA(*args)
[ "def", "WebPDecodeRGBA", "(", "*", "args", ")", ":", "return", "_libwebp", ".", "WebPDecodeRGBA", "(", "*", "args", ")" ]
https://github.com/wheybags/freeablo/blob/921ac20be95828460ccc184a9de11eca5c7c0519/extern/SDL_image/external/libwebp-0.3.0/swig/libwebp.py#L83-L85
jsupancic/deep_hand_pose
22cbeae1a8410ff5d37c060c7315719d0a5d608f
python/caffe/io.py
python
Transformer.set_mean
(self, in_, mean)
Set the mean to subtract for centering the data. Parameters ---------- in_ : which input to assign this mean. mean : mean ndarray (input dimensional or broadcastable)
Set the mean to subtract for centering the data.
[ "Set", "the", "mean", "to", "subtract", "for", "centering", "the", "data", "." ]
def set_mean(self, in_, mean): """ Set the mean to subtract for centering the data. Parameters ---------- in_ : which input to assign this mean. mean : mean ndarray (input dimensional or broadcastable) """ self.__check_input(in_) ms = mean.shape if mean.ndim == 1: # broadcast channels if ms[0] != self.inputs[in_][1]: raise ValueError('Mean channels incompatible with input.') mean = mean[:, np.newaxis, np.newaxis] else: # elementwise mean if len(ms) == 2: ms = (1,) + ms if len(ms) != 3: raise ValueError('Mean shape invalid') if ms != self.inputs[in_][1:]: raise ValueError('Mean shape incompatible with input shape.') self.mean[in_] = mean
[ "def", "set_mean", "(", "self", ",", "in_", ",", "mean", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "ms", "=", "mean", ".", "shape", "if", "mean", ".", "ndim", "==", "1", ":", "# broadcast channels", "if", "ms", "[", "0", "]", "!=", ...
https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/python/caffe/io.py#L232-L256
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/minimum-operations-to-make-a-subsequence.py
python
Solution.minOperations
(self, target, arr)
return len(target)-len(lis)
:type target: List[int] :type arr: List[int] :rtype: int
:type target: List[int] :type arr: List[int] :rtype: int
[ ":", "type", "target", ":", "List", "[", "int", "]", ":", "type", "arr", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def minOperations(self, target, arr): """ :type target: List[int] :type arr: List[int] :rtype: int """ lookup = {x:i for i, x in enumerate(target)} lis = [] for x in arr: if x not in lookup: continue i = bisect.bisect_left(lis, lookup[x]) if i == len(lis): lis.append(lookup[x]) else: lis[i] = lookup[x] return len(target)-len(lis)
[ "def", "minOperations", "(", "self", ",", "target", ",", "arr", ")", ":", "lookup", "=", "{", "x", ":", "i", "for", "i", ",", "x", "in", "enumerate", "(", "target", ")", "}", "lis", "=", "[", "]", "for", "x", "in", "arr", ":", "if", "x", "not...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/minimum-operations-to-make-a-subsequence.py#L8-L24
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/panel.py
python
panel_index
(time, panels, names=None)
return MultiIndex.from_arrays([time, panels], sortorder=None, names=names)
Returns a multi-index suitable for a panel-like DataFrame. Parameters ---------- time : array-like Time index, does not have to repeat panels : array-like Panel index, does not have to repeat names : list, optional List containing the names of the indices Returns ------- multi_index : MultiIndex Time index is the first level, the panels are the second level. Examples -------- >>> years = range(1960,1963) >>> panels = ['A', 'B', 'C'] >>> panel_idx = panel_index(years, panels) >>> panel_idx MultiIndex([(1960, 'A'), (1961, 'A'), (1962, 'A'), (1960, 'B'), (1961, 'B'), (1962, 'B'), (1960, 'C'), (1961, 'C'), (1962, 'C')], dtype=object) or >>> years = np.repeat(range(1960,1963), 3) >>> panels = np.tile(['A', 'B', 'C'], 3) >>> panel_idx = panel_index(years, panels) >>> panel_idx MultiIndex([(1960, 'A'), (1960, 'B'), (1960, 'C'), (1961, 'A'), (1961, 'B'), (1961, 'C'), (1962, 'A'), (1962, 'B'), (1962, 'C')], dtype=object)
Returns a multi-index suitable for a panel-like DataFrame.
[ "Returns", "a", "multi", "-", "index", "suitable", "for", "a", "panel", "-", "like", "DataFrame", "." ]
def panel_index(time, panels, names=None): """ Returns a multi-index suitable for a panel-like DataFrame. Parameters ---------- time : array-like Time index, does not have to repeat panels : array-like Panel index, does not have to repeat names : list, optional List containing the names of the indices Returns ------- multi_index : MultiIndex Time index is the first level, the panels are the second level. Examples -------- >>> years = range(1960,1963) >>> panels = ['A', 'B', 'C'] >>> panel_idx = panel_index(years, panels) >>> panel_idx MultiIndex([(1960, 'A'), (1961, 'A'), (1962, 'A'), (1960, 'B'), (1961, 'B'), (1962, 'B'), (1960, 'C'), (1961, 'C'), (1962, 'C')], dtype=object) or >>> years = np.repeat(range(1960,1963), 3) >>> panels = np.tile(['A', 'B', 'C'], 3) >>> panel_idx = panel_index(years, panels) >>> panel_idx MultiIndex([(1960, 'A'), (1960, 'B'), (1960, 'C'), (1961, 'A'), (1961, 'B'), (1961, 'C'), (1962, 'A'), (1962, 'B'), (1962, 'C')], dtype=object) """ if names is None: names = ['time', 'panel'] time, panels = _ensure_like_indices(time, panels) return MultiIndex.from_arrays([time, panels], sortorder=None, names=names)
[ "def", "panel_index", "(", "time", ",", "panels", ",", "names", "=", "None", ")", ":", "if", "names", "is", "None", ":", "names", "=", "[", "'time'", ",", "'panel'", "]", "time", ",", "panels", "=", "_ensure_like_indices", "(", "time", ",", "panels", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/panel.py#L64-L105
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/SANSUtility.py
python
convert_to_string_list
(to_convert)
return output_string
Convert a comma-separted string to a Python string list in a string form "file1.xml, file2.xml" -> "['file1.xml','file2.xml']" :param to_convert :: a comma-spearated string
Convert a comma-separted string to a Python string list in a string form "file1.xml, file2.xml" -> "['file1.xml','file2.xml']" :param to_convert :: a comma-spearated string
[ "Convert", "a", "comma", "-", "separted", "string", "to", "a", "Python", "string", "list", "in", "a", "string", "form", "file1", ".", "xml", "file2", ".", "xml", "-", ">", "[", "file1", ".", "xml", "file2", ".", "xml", "]", ":", "param", "to_convert"...
def convert_to_string_list(to_convert): """ Convert a comma-separted string to a Python string list in a string form "file1.xml, file2.xml" -> "['file1.xml','file2.xml']" :param to_convert :: a comma-spearated string """ string_list = to_convert.replace(" ", "").split(",") output_string = "[" + ','.join("'"+element+"'" for element in string_list) + "]" return output_string
[ "def", "convert_to_string_list", "(", "to_convert", ")", ":", "string_list", "=", "to_convert", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ".", "split", "(", "\",\"", ")", "output_string", "=", "\"[\"", "+", "','", ".", "join", "(", "\"'\"", "+", "e...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/SANSUtility.py#L1578-L1586
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/utils.py
python
LRUCache.values
(self)
return [x[1] for x in self.items()]
Return a list of all values.
Return a list of all values.
[ "Return", "a", "list", "of", "all", "values", "." ]
def values(self): """Return a list of all values.""" return [x[1] for x in self.items()]
[ "def", "values", "(", "self", ")", ":", "return", "[", "x", "[", "1", "]", "for", "x", "in", "self", ".", "items", "(", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/utils.py#L487-L489
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/saving/utils_v1/export_utils.py
python
_maybe_add_default_serving_output
(export_outputs)
return export_outputs
Add a default serving output to the export_outputs if not present. Args: export_outputs: Describes the output signatures to be exported to `SavedModel` and used during serving. Should be a dict. Returns: export_outputs dict with default serving signature added if necessary Raises: ValueError: if multiple export_outputs were provided without a default serving key.
Add a default serving output to the export_outputs if not present.
[ "Add", "a", "default", "serving", "output", "to", "the", "export_outputs", "if", "not", "present", "." ]
def _maybe_add_default_serving_output(export_outputs): """Add a default serving output to the export_outputs if not present. Args: export_outputs: Describes the output signatures to be exported to `SavedModel` and used during serving. Should be a dict. Returns: export_outputs dict with default serving signature added if necessary Raises: ValueError: if multiple export_outputs were provided without a default serving key. """ if len(export_outputs) == 1: (key, value), = export_outputs.items() if key != signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: export_outputs[ signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = value if len(export_outputs) > 1: if (signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY not in export_outputs): raise ValueError( 'Multiple export_outputs were provided, but none of them is ' 'specified as the default. Do this by naming one of them with ' 'signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY.') return export_outputs
[ "def", "_maybe_add_default_serving_output", "(", "export_outputs", ")", ":", "if", "len", "(", "export_outputs", ")", "==", "1", ":", "(", "key", ",", "value", ")", ",", "=", "export_outputs", ".", "items", "(", ")", "if", "key", "!=", "signature_constants",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/saving/utils_v1/export_utils.py#L330-L357
yushroom/FishEngine
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
Script/reflect/clang/cindex.py
python
Cursor.get_field_offsetof
(self)
return conf.lib.clang_Cursor_getOffsetOfField(self)
Returns the offsetof the FIELD_DECL pointed by this Cursor.
Returns the offsetof the FIELD_DECL pointed by this Cursor.
[ "Returns", "the", "offsetof", "the", "FIELD_DECL", "pointed", "by", "this", "Cursor", "." ]
def get_field_offsetof(self): """Returns the offsetof the FIELD_DECL pointed by this Cursor.""" return conf.lib.clang_Cursor_getOffsetOfField(self)
[ "def", "get_field_offsetof", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_Cursor_getOffsetOfField", "(", "self", ")" ]
https://github.com/yushroom/FishEngine/blob/a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9/Script/reflect/clang/cindex.py#L1710-L1712
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/ndimage/morphology.py
python
morphological_gradient
(input, size=None, footprint=None, structure=None, output=None, mode="reflect", cval=0.0, origin=0)
Multi-dimensional morphological gradient. The morphological gradient is calculated as the difference between a dilation and an erosion of the input with a given structuring element. Parameters ---------- input : array_like Array over which to compute the morphlogical gradient. size : tuple of ints Shape of a flat and full structuring element used for the mathematical morphology operations. Optional if `footprint` or `structure` is provided. A larger `size` yields a more blurred gradient. footprint : array of ints, optional Positions of non-infinite elements of a flat structuring element used for the morphology operations. Larger footprints give a more blurred morphological gradient. structure : array of ints, optional Structuring element used for the morphology operations. `structure` may be a non-flat structuring element. output : array, optional An array used for storing the output of the morphological gradient may be provided. mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional The `mode` parameter determines how the array borders are handled, where `cval` is the value when mode is equal to 'constant'. Default is 'reflect' cval : scalar, optional Value to fill past edges of input if `mode` is 'constant'. Default is 0.0. origin : scalar, optional The `origin` parameter controls the placement of the filter. Default 0 Returns ------- morphological_gradient : ndarray Morphological gradient of `input`. See also -------- grey_dilation, grey_erosion, ndimage.gaussian_gradient_magnitude Notes ----- For a flat structuring element, the morphological gradient computed at a given point corresponds to the maximal difference between elements of the input among the elements covered by the structuring element centered on the point. References ---------- .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology Examples -------- >>> from scipy import ndimage >>> a = np.zeros((7,7), dtype=int) >>> a[2:5, 2:5] = 1 >>> ndimage.morphological_gradient(a, size=(3,3)) array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> # The morphological gradient is computed as the difference >>> # between a dilation and an erosion >>> ndimage.grey_dilation(a, size=(3,3)) -\\ ... ndimage.grey_erosion(a, size=(3,3)) array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> a = np.zeros((7,7), dtype=int) >>> a[2:5, 2:5] = 1 >>> a[4,4] = 2; a[2,3] = 3 >>> a array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 3, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> ndimage.morphological_gradient(a, size=(3,3)) array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 3, 3, 3, 1, 0], [0, 1, 3, 3, 3, 1, 0], [0, 1, 3, 2, 3, 2, 0], [0, 1, 1, 2, 2, 2, 0], [0, 1, 1, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 0]])
Multi-dimensional morphological gradient.
[ "Multi", "-", "dimensional", "morphological", "gradient", "." ]
def morphological_gradient(input, size=None, footprint=None, structure=None, output=None, mode="reflect", cval=0.0, origin=0): """ Multi-dimensional morphological gradient. The morphological gradient is calculated as the difference between a dilation and an erosion of the input with a given structuring element. Parameters ---------- input : array_like Array over which to compute the morphlogical gradient. size : tuple of ints Shape of a flat and full structuring element used for the mathematical morphology operations. Optional if `footprint` or `structure` is provided. A larger `size` yields a more blurred gradient. footprint : array of ints, optional Positions of non-infinite elements of a flat structuring element used for the morphology operations. Larger footprints give a more blurred morphological gradient. structure : array of ints, optional Structuring element used for the morphology operations. `structure` may be a non-flat structuring element. output : array, optional An array used for storing the output of the morphological gradient may be provided. mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional The `mode` parameter determines how the array borders are handled, where `cval` is the value when mode is equal to 'constant'. Default is 'reflect' cval : scalar, optional Value to fill past edges of input if `mode` is 'constant'. Default is 0.0. origin : scalar, optional The `origin` parameter controls the placement of the filter. Default 0 Returns ------- morphological_gradient : ndarray Morphological gradient of `input`. See also -------- grey_dilation, grey_erosion, ndimage.gaussian_gradient_magnitude Notes ----- For a flat structuring element, the morphological gradient computed at a given point corresponds to the maximal difference between elements of the input among the elements covered by the structuring element centered on the point. References ---------- .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology Examples -------- >>> from scipy import ndimage >>> a = np.zeros((7,7), dtype=int) >>> a[2:5, 2:5] = 1 >>> ndimage.morphological_gradient(a, size=(3,3)) array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> # The morphological gradient is computed as the difference >>> # between a dilation and an erosion >>> ndimage.grey_dilation(a, size=(3,3)) -\\ ... ndimage.grey_erosion(a, size=(3,3)) array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> a = np.zeros((7,7), dtype=int) >>> a[2:5, 2:5] = 1 >>> a[4,4] = 2; a[2,3] = 3 >>> a array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 3, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> ndimage.morphological_gradient(a, size=(3,3)) array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 3, 3, 3, 1, 0], [0, 1, 3, 3, 3, 1, 0], [0, 1, 3, 2, 3, 2, 0], [0, 1, 1, 2, 2, 2, 0], [0, 1, 1, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 0]]) """ tmp = grey_dilation(input, size, footprint, structure, None, mode, cval, origin) if isinstance(output, numpy.ndarray): grey_erosion(input, size, footprint, structure, output, mode, cval, origin) return numpy.subtract(tmp, output, output) else: return (tmp - grey_erosion(input, size, footprint, structure, None, mode, cval, origin))
[ "def", "morphological_gradient", "(", "input", ",", "size", "=", "None", ",", "footprint", "=", "None", ",", "structure", "=", "None", ",", "output", "=", "None", ",", "mode", "=", "\"reflect\"", ",", "cval", "=", "0.0", ",", "origin", "=", "0", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/ndimage/morphology.py#L1527-L1637
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xpathParserContext.xpathMultValues
(self)
Implement the multiply operation on XPath objects: The numeric operators convert their operands to numbers as if by calling the number function.
Implement the multiply operation on XPath objects: The numeric operators convert their operands to numbers as if by calling the number function.
[ "Implement", "the", "multiply", "operation", "on", "XPath", "objects", ":", "The", "numeric", "operators", "convert", "their", "operands", "to", "numbers", "as", "if", "by", "calling", "the", "number", "function", "." ]
def xpathMultValues(self): """Implement the multiply operation on XPath objects: The numeric operators convert their operands to numbers as if by calling the number function. """ libxml2mod.xmlXPathMultValues(self._o)
[ "def", "xpathMultValues", "(", "self", ")", ":", "libxml2mod", ".", "xmlXPathMultValues", "(", "self", ".", "_o", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L7581-L7585
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py
python
Node.postprocess
(self)
Clean up anything we don't need to hang onto after we've been built.
Clean up anything we don't need to hang onto after we've been built.
[ "Clean", "up", "anything", "we", "don", "t", "need", "to", "hang", "onto", "after", "we", "ve", "been", "built", "." ]
def postprocess(self): """Clean up anything we don't need to hang onto after we've been built.""" self.executor_cleanup() self.waiting_parents = set()
[ "def", "postprocess", "(", "self", ")", ":", "self", ".", "executor_cleanup", "(", ")", "self", ".", "waiting_parents", "=", "set", "(", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py#L814-L818
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/experiment.py
python
Experiment.train_and_evaluate
(self)
return eval_result, export_results
Interleaves training and evaluation. The frequency of evaluation is controlled by the constructor arg `min_eval_frequency`. When this parameter is 0, evaluation happens only after training has completed. Note that evaluation cannot happen more frequently than checkpoints are taken. If no new snapshots are available when evaluation is supposed to occur, then evaluation doesn't happen for another `min_eval_frequency` steps (assuming a checkpoint is available at that point). Thus, settings `min_eval_frequency` to 1 means that the model will be evaluated everytime there is a new checkpoint. This is particular useful for a "Master" task in the cloud, whose responsibility it is to take checkpoints, evaluate those checkpoints, and write out summaries. Participating in training as the supervisor allows such a task to accomplish the first and last items, while performing evaluation allows for the second. Returns: The result of the `evaluate` call to the `Estimator` as well as the export results using the specified `ExportStrategy`.
Interleaves training and evaluation.
[ "Interleaves", "training", "and", "evaluation", "." ]
def train_and_evaluate(self): """Interleaves training and evaluation. The frequency of evaluation is controlled by the constructor arg `min_eval_frequency`. When this parameter is 0, evaluation happens only after training has completed. Note that evaluation cannot happen more frequently than checkpoints are taken. If no new snapshots are available when evaluation is supposed to occur, then evaluation doesn't happen for another `min_eval_frequency` steps (assuming a checkpoint is available at that point). Thus, settings `min_eval_frequency` to 1 means that the model will be evaluated everytime there is a new checkpoint. This is particular useful for a "Master" task in the cloud, whose responsibility it is to take checkpoints, evaluate those checkpoints, and write out summaries. Participating in training as the supervisor allows such a task to accomplish the first and last items, while performing evaluation allows for the second. Returns: The result of the `evaluate` call to the `Estimator` as well as the export results using the specified `ExportStrategy`. """ # The directory to which evaluation summaries are written are determined # by adding a suffix to 'eval'; that suffix is the 'name' parameter to # the various evaluate(...) methods. By setting it to None, we force # the directory name to simply be 'eval'. eval_dir_suffix = None # We set every_n_steps to 1, but evaluation only occurs when a new # snapshot is available. If, by the time we finish evaluation # there is a new snapshot, then we just evaluate again. Otherwise, # we keep training until one becomes available. with _new_attr_context(self, "_train_monitors"): self._train_monitors = self._train_monitors or [] if self._min_eval_frequency: self._train_monitors += [monitors.ValidationMonitor( input_fn=self._eval_input_fn, eval_steps=self._eval_steps, metrics=self._eval_metrics, every_n_steps=self._min_eval_frequency, name=eval_dir_suffix, hooks=self._eval_hooks )] self.train(delay_secs=0) eval_result = self._call_evaluate(input_fn=self._eval_input_fn, steps=self._eval_steps, metrics=self._eval_metrics, name=eval_dir_suffix, hooks=self._eval_hooks) export_results = self._maybe_export(eval_result) return eval_result, export_results
[ "def", "train_and_evaluate", "(", "self", ")", ":", "# The directory to which evaluation summaries are written are determined", "# by adding a suffix to 'eval'; that suffix is the 'name' parameter to", "# the various evaluate(...) methods. By setting it to None, we force", "# the directory name to...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/experiment.py#L462-L510
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
Band.GetVirtualMemArray
(self, eAccess=gdalconst.GF_Read, xoff=0, yoff=0, xsize=None, ysize=None, bufxsize=None, bufysize=None, datatype=None, cache_size = 10 * 1024 * 1024, page_size_hint = 0, options=None)
return gdal_array.VirtualMemGetArray(virtualmem)
Return a NumPy array for the band, seen as a virtual memory mapping. An element is accessed with array[y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped.
Return a NumPy array for the band, seen as a virtual memory mapping. An element is accessed with array[y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped.
[ "Return", "a", "NumPy", "array", "for", "the", "band", "seen", "as", "a", "virtual", "memory", "mapping", ".", "An", "element", "is", "accessed", "with", "array", "[", "y", "]", "[", "x", "]", ".", "Any", "reference", "to", "the", "array", "must", "b...
def GetVirtualMemArray(self, eAccess=gdalconst.GF_Read, xoff=0, yoff=0, xsize=None, ysize=None, bufxsize=None, bufysize=None, datatype=None, cache_size = 10 * 1024 * 1024, page_size_hint = 0, options=None): """Return a NumPy array for the band, seen as a virtual memory mapping. An element is accessed with array[y][x]. Any reference to the array must be dropped before the last reference to the related dataset is also dropped. """ from osgeo import gdal_array if xsize is None: xsize = self.XSize if ysize is None: ysize = self.YSize if bufxsize is None: bufxsize = self.XSize if bufysize is None: bufysize = self.YSize if datatype is None: datatype = self.DataType if options is None: virtualmem = self.GetVirtualMem(eAccess, xoff, yoff, xsize, ysize, bufxsize, bufysize, datatype, cache_size, page_size_hint) else: virtualmem = self.GetVirtualMem(eAccess, xoff, yoff, xsize, ysize, bufxsize, bufysize, datatype, cache_size, page_size_hint, options) return gdal_array.VirtualMemGetArray(virtualmem)
[ "def", "GetVirtualMemArray", "(", "self", ",", "eAccess", "=", "gdalconst", ".", "GF_Read", ",", "xoff", "=", "0", ",", "yoff", "=", "0", ",", "xsize", "=", "None", ",", "ysize", "=", "None", ",", "bufxsize", "=", "None", ",", "bufysize", "=", "None"...
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3690-L3715
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/which/which.py
python
which
(command, path=None, verbose=0, exts=None)
return match
Return the full path to the first match of the given command on the path. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to use the PATH environment variable. "verbose", if true, will cause a 2-tuple to be returned. The second element is a textual description of where the match was found. "exts" optionally allows one to specify a list of extensions to use instead of the standard list for this system. This can effectively be used as an optimization to, for example, avoid stat's of "foo.vbs" when searching for "foo" and you know it is not a VisualBasic script but ".vbs" is on PATHEXT. This option is only supported on Windows. If no match is found for the command, a WhichError is raised.
Return the full path to the first match of the given command on the path. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to use the PATH environment variable. "verbose", if true, will cause a 2-tuple to be returned. The second element is a textual description of where the match was found. "exts" optionally allows one to specify a list of extensions to use instead of the standard list for this system. This can effectively be used as an optimization to, for example, avoid stat's of "foo.vbs" when searching for "foo" and you know it is not a VisualBasic script but ".vbs" is on PATHEXT. This option is only supported on Windows.
[ "Return", "the", "full", "path", "to", "the", "first", "match", "of", "the", "given", "command", "on", "the", "path", ".", "command", "is", "a", "the", "name", "of", "the", "executable", "to", "search", "for", ".", "path", "is", "an", "optional", "alte...
def which(command, path=None, verbose=0, exts=None): """Return the full path to the first match of the given command on the path. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to use the PATH environment variable. "verbose", if true, will cause a 2-tuple to be returned. The second element is a textual description of where the match was found. "exts" optionally allows one to specify a list of extensions to use instead of the standard list for this system. This can effectively be used as an optimization to, for example, avoid stat's of "foo.vbs" when searching for "foo" and you know it is not a VisualBasic script but ".vbs" is on PATHEXT. This option is only supported on Windows. If no match is found for the command, a WhichError is raised. """ try: match = whichgen(command, path, verbose, exts).next() except StopIteration: raise WhichError("Could not find '%s' on the path." % command) return match
[ "def", "which", "(", "command", ",", "path", "=", "None", ",", "verbose", "=", "0", ",", "exts", "=", "None", ")", ":", "try", ":", "match", "=", "whichgen", "(", "command", ",", "path", ",", "verbose", ",", "exts", ")", ".", "next", "(", ")", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/which/which.py#L227-L249
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextHTMLHandler.SetFontSizeMapping
(*args, **kwargs)
return _richtext.RichTextHTMLHandler_SetFontSizeMapping(*args, **kwargs)
SetFontSizeMapping(self, wxArrayInt fontSizeMapping) Set mapping from point size to HTML font size. There should be 7 elements, one for each HTML font size, each element specifying the maximum point size for that HTML font size. E.g. 8, 10, 13, 17, 22, 29, 100
SetFontSizeMapping(self, wxArrayInt fontSizeMapping)
[ "SetFontSizeMapping", "(", "self", "wxArrayInt", "fontSizeMapping", ")" ]
def SetFontSizeMapping(*args, **kwargs): """ SetFontSizeMapping(self, wxArrayInt fontSizeMapping) Set mapping from point size to HTML font size. There should be 7 elements, one for each HTML font size, each element specifying the maximum point size for that HTML font size. E.g. 8, 10, 13, 17, 22, 29, 100 """ return _richtext.RichTextHTMLHandler_SetFontSizeMapping(*args, **kwargs)
[ "def", "SetFontSizeMapping", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextHTMLHandler_SetFontSizeMapping", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L4393-L4402
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py
python
NDFrame.keys
(self)
return self._info_axis
Get the 'info axis' (see Indexing for more). This is index for Series, columns for DataFrame. Returns ------- Index Info axis.
Get the 'info axis' (see Indexing for more).
[ "Get", "the", "info", "axis", "(", "see", "Indexing", "for", "more", ")", "." ]
def keys(self): """ Get the 'info axis' (see Indexing for more). This is index for Series, columns for DataFrame. Returns ------- Index Info axis. """ return self._info_axis
[ "def", "keys", "(", "self", ")", ":", "return", "self", ".", "_info_axis" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py#L1815-L1826
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/cephfs/filesystem.py
python
FSStatus.get_filesystems
(self)
Iterator for all filesystems.
Iterator for all filesystems.
[ "Iterator", "for", "all", "filesystems", "." ]
def get_filesystems(self): """ Iterator for all filesystems. """ for fs in self.map['filesystems']: yield fs
[ "def", "get_filesystems", "(", "self", ")", ":", "for", "fs", "in", "self", ".", "map", "[", "'filesystems'", "]", ":", "yield", "fs" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/cephfs/filesystem.py#L90-L95
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/bisect_utils.py
python
RunGClientAndSync
(cwd=None)
return RunGClient(params, cwd=cwd)
Runs gclient and does a normal sync. Args: cwd: Working directory to run from. Returns: The return code of the call.
Runs gclient and does a normal sync.
[ "Runs", "gclient", "and", "does", "a", "normal", "sync", "." ]
def RunGClientAndSync(cwd=None): """Runs gclient and does a normal sync. Args: cwd: Working directory to run from. Returns: The return code of the call. """ params = ['sync', '--verbose', '--nohooks', '--reset', '--force'] return RunGClient(params, cwd=cwd)
[ "def", "RunGClientAndSync", "(", "cwd", "=", "None", ")", ":", "params", "=", "[", "'sync'", ",", "'--verbose'", ",", "'--nohooks'", ",", "'--reset'", ",", "'--force'", "]", "return", "RunGClient", "(", "params", ",", "cwd", "=", "cwd", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/bisect_utils.py#L320-L330
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/cross_device_utils.py
python
split_by_sparsity
(values)
return dense_values, dense_indices, sparse_values, sparse_indices
Split values into dense and sparse values. Args: values: a list of tensors or `PerReplica`s. Returns: Four lists: a list of dense values, a list of their indices in `values` and a list of sparse values, a list of their indices in `values`.
Split values into dense and sparse values.
[ "Split", "values", "into", "dense", "and", "sparse", "values", "." ]
def split_by_sparsity(values): """Split values into dense and sparse values. Args: values: a list of tensors or `PerReplica`s. Returns: Four lists: a list of dense values, a list of their indices in `values` and a list of sparse values, a list of their indices in `values`. """ dense_values = [] dense_indices = [] sparse_values = [] sparse_indices = [] for i, v in enumerate(values): if is_indexed_slices(v): sparse_values.append(v) sparse_indices.append(i) else: dense_values.append(v) dense_indices.append(i) return dense_values, dense_indices, sparse_values, sparse_indices
[ "def", "split_by_sparsity", "(", "values", ")", ":", "dense_values", "=", "[", "]", "dense_indices", "=", "[", "]", "sparse_values", "=", "[", "]", "sparse_indices", "=", "[", "]", "for", "i", ",", "v", "in", "enumerate", "(", "values", ")", ":", "if",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/cross_device_utils.py#L618-L640
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/BASIC/basiclex.py
python
t_NEWLINE
(t)
return t
r'\n
r'\n
[ "r", "\\", "n" ]
def t_NEWLINE(t): r'\n' t.lexer.lineno += 1 return t
[ "def", "t_NEWLINE", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "1", "return", "t" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/BASIC/basiclex.py#L48-L51
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/auth.py
python
SigV4Auth.string_to_sign
(self, request, canonical_request)
return '\n'.join(sts)
Return the canonical StringToSign as well as a dict containing the original version of all headers that were included in the StringToSign.
Return the canonical StringToSign as well as a dict containing the original version of all headers that were included in the StringToSign.
[ "Return", "the", "canonical", "StringToSign", "as", "well", "as", "a", "dict", "containing", "the", "original", "version", "of", "all", "headers", "that", "were", "included", "in", "the", "StringToSign", "." ]
def string_to_sign(self, request, canonical_request): """ Return the canonical StringToSign as well as a dict containing the original version of all headers that were included in the StringToSign. """ sts = ['AWS4-HMAC-SHA256'] sts.append(request.context['timestamp']) sts.append(self.credential_scope(request)) sts.append(sha256(canonical_request.encode('utf-8')).hexdigest()) return '\n'.join(sts)
[ "def", "string_to_sign", "(", "self", ",", "request", ",", "canonical_request", ")", ":", "sts", "=", "[", "'AWS4-HMAC-SHA256'", "]", "sts", ".", "append", "(", "request", ".", "context", "[", "'timestamp'", "]", ")", "sts", ".", "append", "(", "self", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/auth.py#L329-L339
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/tools/stats-viewer.py
python
UiCounter.__init__
(self, var, format)
Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter
Creates a new ui counter.
[ "Creates", "a", "new", "ui", "counter", "." ]
def __init__(self, var, format): """Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter """ self.var = var self.format = format self.last_value = None
[ "def", "__init__", "(", "self", ",", "var", ",", "format", ")", ":", "self", ".", "var", "=", "var", "self", ".", "format", "=", "format", "self", ".", "last_value", "=", "None" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/tools/stats-viewer.py#L271-L280
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py
python
HDFStore.create_table_index
( self, key: str, columns=None, optlevel: Optional[int] = None, kind: Optional[str] = None, )
Create a pytables index on the table. Parameters ---------- key : str columns : None, bool, or listlike[str] Indicate which columns to create an index on. * False : Do not create any indexes. * True : Create indexes on all columns. * None : Create indexes on all columns. * listlike : Create indexes on the given columns. optlevel : int or None, default None Optimization level, if None, pytables defaults to 6. kind : str or None, default None Kind of index, if None, pytables defaults to "medium". Raises ------ TypeError: raises if the node is not a table
Create a pytables index on the table.
[ "Create", "a", "pytables", "index", "on", "the", "table", "." ]
def create_table_index( self, key: str, columns=None, optlevel: Optional[int] = None, kind: Optional[str] = None, ): """ Create a pytables index on the table. Parameters ---------- key : str columns : None, bool, or listlike[str] Indicate which columns to create an index on. * False : Do not create any indexes. * True : Create indexes on all columns. * None : Create indexes on all columns. * listlike : Create indexes on the given columns. optlevel : int or None, default None Optimization level, if None, pytables defaults to 6. kind : str or None, default None Kind of index, if None, pytables defaults to "medium". Raises ------ TypeError: raises if the node is not a table """ # version requirements _tables() s = self.get_storer(key) if s is None: return if not isinstance(s, Table): raise TypeError("cannot create table index on a Fixed format store") s.create_index(columns=columns, optlevel=optlevel, kind=kind)
[ "def", "create_table_index", "(", "self", ",", "key", ":", "str", ",", "columns", "=", "None", ",", "optlevel", ":", "Optional", "[", "int", "]", "=", "None", ",", "kind", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", ":", "# version requi...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py#L1276-L1315
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/wizard.py
python
WizardEvent.__init__
(self, *args, **kwargs)
__init__(self, EventType type=wxEVT_NULL, int id=-1, bool direction=True, WizardPage page=None) -> WizardEvent
__init__(self, EventType type=wxEVT_NULL, int id=-1, bool direction=True, WizardPage page=None) -> WizardEvent
[ "__init__", "(", "self", "EventType", "type", "=", "wxEVT_NULL", "int", "id", "=", "-", "1", "bool", "direction", "=", "True", "WizardPage", "page", "=", "None", ")", "-", ">", "WizardEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, EventType type=wxEVT_NULL, int id=-1, bool direction=True, WizardPage page=None) -> WizardEvent """ _wizard.WizardEvent_swiginit(self,_wizard.new_WizardEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_wizard", ".", "WizardEvent_swiginit", "(", "self", ",", "_wizard", ".", "new_WizardEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/wizard.py#L90-L95
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/OpenSCAD/importCSG.py
python
p_boolean
(p)
boolean : true | false
boolean : true | false
[ "boolean", ":", "true", "|", "false" ]
def p_boolean(p): ''' boolean : true | false ''' p[0] = p[1]
[ "def", "p_boolean", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/OpenSCAD/importCSG.py#L242-L247
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/backend/recursivemake.py
python
RecursiveMakeTraversal.default_filter
(current, subdirs)
return current, [], subdirs.dirs + subdirs.tests
Default filter for use with compute_dependencies and traverse.
Default filter for use with compute_dependencies and traverse.
[ "Default", "filter", "for", "use", "with", "compute_dependencies", "and", "traverse", "." ]
def default_filter(current, subdirs): """ Default filter for use with compute_dependencies and traverse. """ return current, [], subdirs.dirs + subdirs.tests
[ "def", "default_filter", "(", "current", ",", "subdirs", ")", ":", "return", "current", ",", "[", "]", ",", "subdirs", ".", "dirs", "+", "subdirs", ".", "tests" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/backend/recursivemake.py#L175-L179
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.SetColPos
(*args, **kwargs)
return _grid.Grid_SetColPos(*args, **kwargs)
SetColPos(self, int colID, int newPos)
SetColPos(self, int colID, int newPos)
[ "SetColPos", "(", "self", "int", "colID", "int", "newPos", ")" ]
def SetColPos(*args, **kwargs): """SetColPos(self, int colID, int newPos)""" return _grid.Grid_SetColPos(*args, **kwargs)
[ "def", "SetColPos", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_SetColPos", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1870-L1872
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/portable_globe.py
python
Globe.Polygon
(self)
Tries to get globe polygon from glb file. Returns: The polygon for the globe. If no polygon is found in the globe, it returns "No polygon."
Tries to get globe polygon from glb file.
[ "Tries", "to", "get", "globe", "polygon", "from", "glb", "file", "." ]
def Polygon(self): """Tries to get globe polygon from glb file. Returns: The polygon for the globe. If no polygon is found in the globe, it returns "No polygon." """ try: return self.ReadFile("earth/polygon.kml") # Don't fail if old globe with no polygon file. except portable_exceptions.UnableToFindException: return "No polygon."
[ "def", "Polygon", "(", "self", ")", ":", "try", ":", "return", "self", ".", "ReadFile", "(", "\"earth/polygon.kml\"", ")", "# Don't fail if old globe with no polygon file.", "except", "portable_exceptions", ".", "UnableToFindException", ":", "return", "\"No polygon.\"" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/portable_globe.py#L577-L590
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/webkit.py
python
WebKitCtrl.MakeEditable
(*args, **kwargs)
return _webkit.WebKitCtrl_MakeEditable(*args, **kwargs)
MakeEditable(self, bool enable=True)
MakeEditable(self, bool enable=True)
[ "MakeEditable", "(", "self", "bool", "enable", "=", "True", ")" ]
def MakeEditable(*args, **kwargs): """MakeEditable(self, bool enable=True)""" return _webkit.WebKitCtrl_MakeEditable(*args, **kwargs)
[ "def", "MakeEditable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_webkit", ".", "WebKitCtrl_MakeEditable", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/webkit.py#L156-L158
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.CharLeftExtend
(*args, **kwargs)
return _stc.StyledTextCtrl_CharLeftExtend(*args, **kwargs)
CharLeftExtend(self) Move caret left one character extending selection to new caret position.
CharLeftExtend(self)
[ "CharLeftExtend", "(", "self", ")" ]
def CharLeftExtend(*args, **kwargs): """ CharLeftExtend(self) Move caret left one character extending selection to new caret position. """ return _stc.StyledTextCtrl_CharLeftExtend(*args, **kwargs)
[ "def", "CharLeftExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_CharLeftExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4368-L4374
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
xmlNode.prop
(self, name)
return ret
Search and get the value of an attribute associated to a node This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. NOTE: this function acts independently of namespaces associated to the attribute. Use xmlGetNsProp() or xmlGetNoNsProp() for namespace aware processing.
Search and get the value of an attribute associated to a node This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. NOTE: this function acts independently of namespaces associated to the attribute. Use xmlGetNsProp() or xmlGetNoNsProp() for namespace aware processing.
[ "Search", "and", "get", "the", "value", "of", "an", "attribute", "associated", "to", "a", "node", "This", "does", "the", "entity", "substitution", ".", "This", "function", "looks", "in", "DTD", "attribute", "declaration", "for", "#FIXED", "or", "default", "d...
def prop(self, name): """Search and get the value of an attribute associated to a node This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. NOTE: this function acts independently of namespaces associated to the attribute. Use xmlGetNsProp() or xmlGetNoNsProp() for namespace aware processing. """ ret = libxml2mod.xmlGetProp(self._o, name) return ret
[ "def", "prop", "(", "self", ",", "name", ")", ":", "ret", "=", "libxml2mod", ".", "xmlGetProp", "(", "self", ".", "_o", ",", "name", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L3465-L3474
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/ma/core.py
python
MaskedArray.__rsub__
(self, other)
return subtract(other, self)
Subtract self from other, and return a new masked array.
Subtract self from other, and return a new masked array.
[ "Subtract", "self", "from", "other", "and", "return", "a", "new", "masked", "array", "." ]
def __rsub__(self, other): """ Subtract self from other, and return a new masked array. """ return subtract(other, self)
[ "def", "__rsub__", "(", "self", ",", "other", ")", ":", "return", "subtract", "(", "other", ",", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L4159-L4164
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/methodDefs_randomGeneratorWrapper/generator.py
python
returnUniformAndTwoNormal
(*args)
return [int(np.random.uniform(args[0],args[1])),np.random.normal(args[2], args[3], 1),np.random.normal(args[4], args[5], 1)]
Return one integer uniformly distributed random variable and two normal random variables
Return one integer uniformly distributed random variable and two normal random variables
[ "Return", "one", "integer", "uniformly", "distributed", "random", "variable", "and", "two", "normal", "random", "variables" ]
def returnUniformAndTwoNormal(*args): """ Return one integer uniformly distributed random variable and two normal random variables """ return [int(np.random.uniform(args[0],args[1])),np.random.normal(args[2], args[3], 1),np.random.normal(args[4], args[5], 1)]
[ "def", "returnUniformAndTwoNormal", "(", "*", "args", ")", ":", "return", "[", "int", "(", "np", ".", "random", ".", "uniform", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ")", ")", ",", "np", ".", "random", ".", "normal", "(", "args"...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/methodDefs_randomGeneratorWrapper/generator.py#L81-L86
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/dispatch.py
python
should_series_dispatch
(left, right, op)
return False
Identify cases where a DataFrame operation should dispatch to its Series counterpart. Parameters ---------- left : DataFrame right : DataFrame or Series op : binary operator Returns ------- override : bool
Identify cases where a DataFrame operation should dispatch to its Series counterpart.
[ "Identify", "cases", "where", "a", "DataFrame", "operation", "should", "dispatch", "to", "its", "Series", "counterpart", "." ]
def should_series_dispatch(left, right, op): """ Identify cases where a DataFrame operation should dispatch to its Series counterpart. Parameters ---------- left : DataFrame right : DataFrame or Series op : binary operator Returns ------- override : bool """ if left._is_mixed_type or right._is_mixed_type: return True if op.__name__.strip("_") in ["and", "or", "xor", "rand", "ror", "rxor"]: # TODO: GH references for what this fixes # Note: this check must come before the check for nonempty columns. return True if right.ndim == 1: # operating with Series, short-circuit checks that would fail # with AttributeError. return False if not len(left.columns) or not len(right.columns): # ensure obj.dtypes[0] exists for each obj return False ldtype = left.dtypes.iloc[0] rdtype = right.dtypes.iloc[0] if (is_timedelta64_dtype(ldtype) and is_integer_dtype(rdtype)) or ( is_timedelta64_dtype(rdtype) and is_integer_dtype(ldtype) ): # numpy integer dtypes as timedelta64 dtypes in this scenario return True if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype): # in particular case where right is an array of DateOffsets return True return False
[ "def", "should_series_dispatch", "(", "left", ",", "right", ",", "op", ")", ":", "if", "left", ".", "_is_mixed_type", "or", "right", ".", "_is_mixed_type", ":", "return", "True", "if", "op", ".", "__name__", ".", "strip", "(", "\"_\"", ")", "in", "[", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/dispatch.py#L48-L93
strukturag/libheif
0082fea96ee70a20c8906a0373bedec0c01777bc
scripts/cpplint.py
python
Error
(filename, linenum, category, confidence, message)
Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message.
Logs the fact we've found a lint error.
[ "Logs", "the", "fact", "we", "ve", "found", "a", "lint", "error", "." ]
def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence))
[ "def", "Error", "(", "filename", ",", "linenum", ",", "category", ",", "confidence", ",", "message", ")", ":", "if", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "_cpplint_state", ".", "IncrementErrorCount", "(", "category...
https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L1169-L1201
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
VarVScrollHelper.GetRowCount
(*args, **kwargs)
return _windows_.VarVScrollHelper_GetRowCount(*args, **kwargs)
GetRowCount(self) -> size_t
GetRowCount(self) -> size_t
[ "GetRowCount", "(", "self", ")", "-", ">", "size_t" ]
def GetRowCount(*args, **kwargs): """GetRowCount(self) -> size_t""" return _windows_.VarVScrollHelper_GetRowCount(*args, **kwargs)
[ "def", "GetRowCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "VarVScrollHelper_GetRowCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L2297-L2299
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
python/lammps/core.py
python
lammps.is_running
(self)
return self.lib.lammps_is_running(self.lmp) == 1
Report whether being called from a function during a run or a minimization Various LAMMPS commands must not be called during an ongoing run or minimization. This property allows to check for that. This is a wrapper around the :cpp:func:`lammps_is_running` function of the library interface. .. versionadded:: 9Oct2020 :return: True when called during a run otherwise false :rtype: bool
Report whether being called from a function during a run or a minimization
[ "Report", "whether", "being", "called", "from", "a", "function", "during", "a", "run", "or", "a", "minimization" ]
def is_running(self): """ Report whether being called from a function during a run or a minimization Various LAMMPS commands must not be called during an ongoing run or minimization. This property allows to check for that. This is a wrapper around the :cpp:func:`lammps_is_running` function of the library interface. .. versionadded:: 9Oct2020 :return: True when called during a run otherwise false :rtype: bool """ return self.lib.lammps_is_running(self.lmp) == 1
[ "def", "is_running", "(", "self", ")", ":", "return", "self", ".", "lib", ".", "lammps_is_running", "(", "self", ".", "lmp", ")", "==", "1" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/python/lammps/core.py#L1479-L1492
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosgraph/src/rosgraph/network.py
python
is_local_address
(hostname)
return False
:param hostname: host name/address, ``str`` :returns True: if hostname maps to a local address, False otherwise. False conditions include invalid hostnames.
:param hostname: host name/address, ``str`` :returns True: if hostname maps to a local address, False otherwise. False conditions include invalid hostnames.
[ ":", "param", "hostname", ":", "host", "name", "/", "address", "str", ":", "returns", "True", ":", "if", "hostname", "maps", "to", "a", "local", "address", "False", "otherwise", ".", "False", "conditions", "include", "invalid", "hostnames", "." ]
def is_local_address(hostname): """ :param hostname: host name/address, ``str`` :returns True: if hostname maps to a local address, False otherwise. False conditions include invalid hostnames. """ try: if use_ipv6(): reverse_ips = [host[4][0] for host in socket.getaddrinfo(hostname, 0, 0, 0, socket.SOL_TCP)] else: reverse_ips = [host[4][0] for host in socket.getaddrinfo(hostname, 0, socket.AF_INET, 0, socket.SOL_TCP)] except socket.error: return False local_addresses = ['localhost'] + get_local_addresses() # 127. check is due to #1260 if ([ip for ip in reverse_ips if (ip.startswith('127.') or ip == '::1')] != []) or (set(reverse_ips) & set(local_addresses) != set()): return True return False
[ "def", "is_local_address", "(", "hostname", ")", ":", "try", ":", "if", "use_ipv6", "(", ")", ":", "reverse_ips", "=", "[", "host", "[", "4", "]", "[", "0", "]", "for", "host", "in", "socket", ".", "getaddrinfo", "(", "hostname", ",", "0", ",", "0"...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosgraph/src/rosgraph/network.py#L164-L180
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiManager_DCP._destroyDummyPane
(self)
Destroys the Dummy Center Pane (**DCP**).
Destroys the Dummy Center Pane (**DCP**).
[ "Destroys", "the", "Dummy", "Center", "Pane", "(", "**", "DCP", "**", ")", "." ]
def _destroyDummyPane(self): """ Destroys the Dummy Center Pane (**DCP**). """ if not self.hasDummyPane: return self.hasDummyPane = False self.ClosePane(self.GetPane('dummyCenterPane'))
[ "def", "_destroyDummyPane", "(", "self", ")", ":", "if", "not", "self", ".", "hasDummyPane", ":", "return", "self", ".", "hasDummyPane", "=", "False", "self", ".", "ClosePane", "(", "self", ".", "GetPane", "(", "'dummyCenterPane'", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L10657-L10664
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/io/loader.py
python
readVectorRaw
(text)
return [float(v) for v in items]
Reads a vector from a raw string 'v1 ... vn
Reads a vector from a raw string 'v1 ... vn
[ "Reads", "a", "vector", "from", "a", "raw", "string", "v1", "...", "vn" ]
def readVectorRaw(text): """Reads a vector from a raw string 'v1 ... vn'""" items = text.split() return [float(v) for v in items]
[ "def", "readVectorRaw", "(", "text", ")", ":", "items", "=", "text", ".", "split", "(", ")", "return", "[", "float", "(", "v", ")", "for", "v", "in", "items", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/loader.py#L113-L116
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py
python
DescriptorPool.Add
(self, file_desc_proto)
Adds the FileDescriptorProto and its types to this pool. Args: file_desc_proto: The FileDescriptorProto to add.
Adds the FileDescriptorProto and its types to this pool.
[ "Adds", "the", "FileDescriptorProto", "and", "its", "types", "to", "this", "pool", "." ]
def Add(self, file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: file_desc_proto: The FileDescriptorProto to add. """ self._internal_db.Add(file_desc_proto)
[ "def", "Add", "(", "self", ",", "file_desc_proto", ")", ":", "self", ".", "_internal_db", ".", "Add", "(", "file_desc_proto", ")" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py#L83-L90
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/control_flow_ops.py
python
exit
(data, name=None)
Exits the current frame to its parent frame. Exit makes its input `data` available to the parent frame. Args: data: The tensor to be made available to the parent frame. name: A name for this operation (optional). Returns: The same tensor as `data`.
Exits the current frame to its parent frame.
[ "Exits", "the", "current", "frame", "to", "its", "parent", "frame", "." ]
def exit(data, name=None): """Exits the current frame to its parent frame. Exit makes its input `data` available to the parent frame. Args: data: The tensor to be made available to the parent frame. name: A name for this operation (optional). Returns: The same tensor as `data`. """ data = ops.internal_convert_to_tensor_or_indexed_slices(data, as_ref=True) if isinstance(data, ops.Tensor): if data.dtype._is_ref_dtype: # pylint: disable=protected-access return gen_control_flow_ops._ref_exit(data, name) else: return gen_control_flow_ops._exit(data, name) else: if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(data)) values = exit(data.values, name=name) indices = gen_control_flow_ops._exit(data.indices, name="indices") if isinstance(data, ops.IndexedSlices): dense_shape = data.dense_shape if dense_shape is not None: dense_shape = gen_control_flow_ops._exit(dense_shape, name) return ops.IndexedSlices(values, indices, dense_shape) else: dense_shape = gen_control_flow_ops._exit(data.dense_shape, name) return sparse_tensor.SparseTensor(indices, values, dense_shape)
[ "def", "exit", "(", "data", ",", "name", "=", "None", ")", ":", "data", "=", "ops", ".", "internal_convert_to_tensor_or_indexed_slices", "(", "data", ",", "as_ref", "=", "True", ")", "if", "isinstance", "(", "data", ",", "ops", ".", "Tensor", ")", ":", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/control_flow_ops.py#L251-L281
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/git.py
python
Git.version
(self)
return self.run(['describe', '--long'])
The git describe --long output.
The git describe --long output.
[ "The", "git", "describe", "--", "long", "output", "." ]
def version(self): """The git describe --long output.""" return self.run(['describe', '--long'])
[ "def", "version", "(", "self", ")", ":", "return", "self", ".", "run", "(", "[", "'describe'", ",", "'--long'", "]", ")" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/git.py#L122-L124
eric1688/sphinx
514317761b35c07eb9f36db55a1ff365c4a9f0bc
api/sphinxapi.py
python
SphinxClient.SetSortMode
( self, mode, clause='' )
Set sorting mode.
Set sorting mode.
[ "Set", "sorting", "mode", "." ]
def SetSortMode ( self, mode, clause='' ): """ Set sorting mode. """ assert ( mode in [SPH_SORT_RELEVANCE, SPH_SORT_ATTR_DESC, SPH_SORT_ATTR_ASC, SPH_SORT_TIME_SEGMENTS, SPH_SORT_EXTENDED, SPH_SORT_EXPR] ) assert ( isinstance ( clause, str ) ) self._sort = mode self._sortby = clause
[ "def", "SetSortMode", "(", "self", ",", "mode", ",", "clause", "=", "''", ")", ":", "assert", "(", "mode", "in", "[", "SPH_SORT_RELEVANCE", ",", "SPH_SORT_ATTR_DESC", ",", "SPH_SORT_ATTR_ASC", ",", "SPH_SORT_TIME_SEGMENTS", ",", "SPH_SORT_EXTENDED", ",", "SPH_SO...
https://github.com/eric1688/sphinx/blob/514317761b35c07eb9f36db55a1ff365c4a9f0bc/api/sphinxapi.py#L365-L372
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/back/OptimizeTransposeReshapeSequence.py
python
OptimizeTransposeReshapeSequence.forward_new_reshape_shape
(reshape_node: Node, initial_output_shape: np.array)
Propagates the changed output shape of the Reshape node forward. The output of the Reshape node should be Transpose so it is necessary to update its 'order' attribute according to the updated shape and output data node. :param reshape_node: the Reshape node to propagate the shape :param initial_output_shape: old output shape of the Reshape node :return: None
Propagates the changed output shape of the Reshape node forward. The output of the Reshape node should be Transpose so it is necessary to update its 'order' attribute according to the updated shape and output data node. :param reshape_node: the Reshape node to propagate the shape :param initial_output_shape: old output shape of the Reshape node :return: None
[ "Propagates", "the", "changed", "output", "shape", "of", "the", "Reshape", "node", "forward", ".", "The", "output", "of", "the", "Reshape", "node", "should", "be", "Transpose", "so", "it", "is", "necessary", "to", "update", "its", "order", "attribute", "acco...
def forward_new_reshape_shape(reshape_node: Node, initial_output_shape: np.array): """ Propagates the changed output shape of the Reshape node forward. The output of the Reshape node should be Transpose so it is necessary to update its 'order' attribute according to the updated shape and output data node. :param reshape_node: the Reshape node to propagate the shape :param initial_output_shape: old output shape of the Reshape node :return: None """ output_shape = reshape_node.out_port(0).data.get_shape() if np.all(output_shape == initial_output_shape): log.debug('Initial output and new output shapes match for node "{}". Do nothing'.format( reshape_node.soft_get('name'))) return dest_node = reshape_node.out_port(0).get_destination().node if dest_node.type == 'Transpose': split_dims = split_dims_indices(initial_output_shape, output_shape) assert dest_node.in_port(1).data.get_value() is not None, \ 'The 1st input value "order" is not set for Transpose node "{}"'.format(dest_node.soft_get('name')) permute_order = dest_node.in_port(1).data.get_value() for split_dim in split_dims: permute_order = split_input_permute_dimension(split_dim, permute_order) dest_node.in_port(1).data.set_value(permute_order) dest_node.infer(dest_node) elif dest_node.type == 'Reshape': log.debug('Two subsequent reshape nodes: "{}" and "{}". Nothing to optimize'.format( reshape_node.soft_get('name'), dest_node.soft_get('name'))) else: assert False, 'Unsupported type of the node "{}" in the Transpose-Reshape optimization' \ ''.format(dest_node.type)
[ "def", "forward_new_reshape_shape", "(", "reshape_node", ":", "Node", ",", "initial_output_shape", ":", "np", ".", "array", ")", ":", "output_shape", "=", "reshape_node", ".", "out_port", "(", "0", ")", ".", "data", ".", "get_shape", "(", ")", "if", "np", ...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/back/OptimizeTransposeReshapeSequence.py#L263-L292
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/reduction_gui/reduction/scripter.py
python
BaseScriptElement.__str__
(self)
return self.to_script()
Script representation of the object. The output is meant to be executable as a Mantid python script
Script representation of the object. The output is meant to be executable as a Mantid python script
[ "Script", "representation", "of", "the", "object", ".", "The", "output", "is", "meant", "to", "be", "executable", "as", "a", "Mantid", "python", "script" ]
def __str__(self): """ Script representation of the object. The output is meant to be executable as a Mantid python script """ return self.to_script()
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "to_script", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/scripter.py#L47-L52
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/deep_mimic/mocap/transformation.py
python
quaternion_multiply
(quaternion1, quaternion0)
return numpy.array([ -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0, x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0, -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0, x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0 ], dtype=numpy.float64)
Return multiplication of two quaternions. >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7]) >>> numpy.allclose(q, [28, -44, -14, 48]) True
Return multiplication of two quaternions.
[ "Return", "multiplication", "of", "two", "quaternions", "." ]
def quaternion_multiply(quaternion1, quaternion0): """Return multiplication of two quaternions. >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7]) >>> numpy.allclose(q, [28, -44, -14, 48]) True """ w0, x0, y0, z0 = quaternion0 w1, x1, y1, z1 = quaternion1 return numpy.array([ -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0, x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0, -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0, x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0 ], dtype=numpy.float64)
[ "def", "quaternion_multiply", "(", "quaternion1", ",", "quaternion0", ")", ":", "w0", ",", "x0", ",", "y0", ",", "z0", "=", "quaternion0", "w1", ",", "x1", ",", "y1", ",", "z1", "=", "quaternion1", "return", "numpy", ".", "array", "(", "[", "-", "x1"...
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/deep_mimic/mocap/transformation.py#L1153-L1167
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Scripted/DICOMPatcher/DICOMPatcher.py
python
DICOMPatcherTest.setUp
(self)
Do whatever is needed to reset the state - typically a scene clear will be enough.
Do whatever is needed to reset the state - typically a scene clear will be enough.
[ "Do", "whatever", "is", "needed", "to", "reset", "the", "state", "-", "typically", "a", "scene", "clear", "will", "be", "enough", "." ]
def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0)
[ "def", "setUp", "(", "self", ")", ":", "slicer", ".", "mrmlScene", ".", "Clear", "(", "0", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMPatcher/DICOMPatcher.py#L603-L606
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py
python
TPen.showturtle
(self)
Makes the turtle visible. Aliases: showturtle | st No argument. Example (for a Turtle instance named turtle): >>> turtle.hideturtle() >>> turtle.showturtle()
Makes the turtle visible.
[ "Makes", "the", "turtle", "visible", "." ]
def showturtle(self): """Makes the turtle visible. Aliases: showturtle | st No argument. Example (for a Turtle instance named turtle): >>> turtle.hideturtle() >>> turtle.showturtle() """ self.pen(shown=True)
[ "def", "showturtle", "(", "self", ")", ":", "self", ".", "pen", "(", "shown", "=", "True", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L2209-L2220
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/layers/python/layers/summaries.py
python
is_summary_tag_unique
(tag)
return tag.encode() not in existing_tags
Checks if a summary tag is unique. Args: tag: The tag to use Returns: True if the summary tag is unique.
Checks if a summary tag is unique.
[ "Checks", "if", "a", "summary", "tag", "is", "unique", "." ]
def is_summary_tag_unique(tag): """Checks if a summary tag is unique. Args: tag: The tag to use Returns: True if the summary tag is unique. """ existing_tags = [tensor_util.constant_value(summary.op.inputs[0]) for summary in ops.get_collection(ops.GraphKeys.SUMMARIES)] existing_tags = [name.tolist() if isinstance(name, np.ndarray) else name for name in existing_tags] return tag.encode() not in existing_tags
[ "def", "is_summary_tag_unique", "(", "tag", ")", ":", "existing_tags", "=", "[", "tensor_util", ".", "constant_value", "(", "summary", ".", "op", ".", "inputs", "[", "0", "]", ")", "for", "summary", "in", "ops", ".", "get_collection", "(", "ops", ".", "G...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/layers/python/layers/summaries.py#L81-L94
taichi-dev/taichi
973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6
python/taichi/lang/snode.py
python
SNode.name
(self)
return self.ptr.name()
Gets the name of `self`. Returns: str: The name of `self`.
Gets the name of `self`.
[ "Gets", "the", "name", "of", "self", "." ]
def name(self): """Gets the name of `self`. Returns: str: The name of `self`. """ return self.ptr.name()
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "ptr", ".", "name", "(", ")" ]
https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/snode.py#L242-L248
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/PeriodicTable/periodic_table.py
python
PeriodicList._selectionChanged
(self, treeItem, column)
Emit a :attr:`sigSelectionChanged` and send a list of :class:`PeriodicTableItem` objects.
Emit a :attr:`sigSelectionChanged` and send a list of :class:`PeriodicTableItem` objects.
[ "Emit", "a", ":", "attr", ":", "sigSelectionChanged", "and", "send", "a", "list", "of", ":", "class", ":", "PeriodicTableItem", "objects", "." ]
def _selectionChanged(self, treeItem, column): """Emit a :attr:`sigSelectionChanged` and send a list of :class:`PeriodicTableItem` objects.""" self.sigSelectionChanged.emit(self.getSelection())
[ "def", "_selectionChanged", "(", "self", ",", "treeItem", ",", "column", ")", ":", "self", ".", "sigSelectionChanged", ".", "emit", "(", "self", ".", "getSelection", "(", ")", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/PeriodicTable/periodic_table.py#L760-L763
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/filters.py
python
do_tojson
(eval_ctx, value, indent=None)
return htmlsafe_json_dumps(value, dumper=dumper, **options)
Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9
Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags.
[ "Dumps", "a", "structure", "to", "JSON", "so", "that", "it", "s", "safe", "to", "use", "in", "<script", ">", "tags", ".", "It", "accepts", "the", "same", "arguments", "and", "returns", "a", "JSON", "string", ".", "Note", "that", "this", "is", "availabl...
def do_tojson(eval_ctx, value, indent=None): """Dumps a structure to JSON so that it's safe to use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of ``<script>`` tags. The following characters are escaped in strings: - ``<`` - ``>`` - ``&`` - ``'`` This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition. The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with. Note that this filter is for use in HTML contexts only. .. versionadded:: 2.9 """ policies = eval_ctx.environment.policies dumper = policies['json.dumps_function'] options = policies['json.dumps_kwargs'] if indent is not None: options = dict(options) options['indent'] = indent return htmlsafe_json_dumps(value, dumper=dumper, **options)
[ "def", "do_tojson", "(", "eval_ctx", ",", "value", ",", "indent", "=", "None", ")", ":", "policies", "=", "eval_ctx", ".", "environment", ".", "policies", "dumper", "=", "policies", "[", "'json.dumps_function'", "]", "options", "=", "policies", "[", "'json.d...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/filters.py#L1047-L1078
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBProcess.GetQueueAtIndex
(self, *args)
return _lldb.SBProcess_GetQueueAtIndex(self, *args)
GetQueueAtIndex(self, uint32_t index) -> SBQueue
GetQueueAtIndex(self, uint32_t index) -> SBQueue
[ "GetQueueAtIndex", "(", "self", "uint32_t", "index", ")", "-", ">", "SBQueue" ]
def GetQueueAtIndex(self, *args): """GetQueueAtIndex(self, uint32_t index) -> SBQueue""" return _lldb.SBProcess_GetQueueAtIndex(self, *args)
[ "def", "GetQueueAtIndex", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBProcess_GetQueueAtIndex", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7088-L7090
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/linalg.py
python
check_c_int
(context, builder, n)
Check whether *n* fits in a C `int`.
Check whether *n* fits in a C `int`.
[ "Check", "whether", "*", "n", "*", "fits", "in", "a", "C", "int", "." ]
def check_c_int(context, builder, n): """ Check whether *n* fits in a C `int`. """ _maxint = 2**31 - 1 def impl(n): if n > _maxint: raise OverflowError("array size too large to fit in C int") context.compile_internal(builder, impl, signature(types.none, types.intp), (n,))
[ "def", "check_c_int", "(", "context", ",", "builder", ",", "n", ")", ":", "_maxint", "=", "2", "**", "31", "-", "1", "def", "impl", "(", "n", ")", ":", "if", "n", ">", "_maxint", ":", "raise", "OverflowError", "(", "\"array size too large to fit in C int...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/linalg.py#L306-L317
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py
python
NDFrame.swapaxes
(self: FrameOrSeries, axis1, axis2, copy=True)
return self._constructor(new_values, *new_axes).__finalize__(self)
Interchange axes and swap values axes appropriately. Returns ------- y : same as input
Interchange axes and swap values axes appropriately.
[ "Interchange", "axes", "and", "swap", "values", "axes", "appropriately", "." ]
def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: """ Interchange axes and swap values axes appropriately. Returns ------- y : same as input """ i = self._get_axis_number(axis1) j = self._get_axis_number(axis2) if i == j: if copy: return self.copy() return self mapping = {i: j, j: i} new_axes = (self._get_axis(mapping.get(k, k)) for k in range(self._AXIS_LEN)) new_values = self.values.swapaxes(i, j) if copy: new_values = new_values.copy() return self._constructor(new_values, *new_axes).__finalize__(self)
[ "def", "swapaxes", "(", "self", ":", "FrameOrSeries", ",", "axis1", ",", "axis2", ",", "copy", "=", "True", ")", "->", "FrameOrSeries", ":", "i", "=", "self", ".", "_get_axis_number", "(", "axis1", ")", "j", "=", "self", ".", "_get_axis_number", "(", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L664-L687
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/shell.py
python
cp
(src, dest)
Copy src to dest
Copy src to dest
[ "Copy", "src", "to", "dest" ]
def cp(src, dest): """ Copy src to dest """ _shutil.copy2(native(src), native(dest))
[ "def", "cp", "(", "src", ",", "dest", ")", ":", "_shutil", ".", "copy2", "(", "native", "(", "src", ")", ",", "native", "(", "dest", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/shell.py#L66-L68
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/algorithm_detail/slice_sans_event.py
python
slice_sans_event
(state_slice, input_ws, input_ws_monitor, data_type_str="Sample")
return to_return
Takes an event slice from an event workspace :param state_slice: The state.slice object :param input_ws: The input workspace. If it is an event workspace, then the slice is taken. In case of a Workspace2D the original workspace is returned :param input_ws_monitor: The monitor workspace associated with the main input workspace. :param data_type_str: The component of the instrument which is to be reduced. Allowed values: ['Sample', 'Can'] :return: A dict with the following: 'SliceEventFactor': The factor of the event slicing. This corresponds to the proportion of the the total proton charge, which the slice corresponds to. 'OutputWorkspace' : The slice workspace 'OutputWorkspaceMonitor' : The output monitor workspace which has the correct slice factor applied to it.
Takes an event slice from an event workspace :param state_slice: The state.slice object :param input_ws: The input workspace. If it is an event workspace, then the slice is taken. In case of a Workspace2D the original workspace is returned :param input_ws_monitor: The monitor workspace associated with the main input workspace. :param data_type_str: The component of the instrument which is to be reduced. Allowed values: ['Sample', 'Can'] :return: A dict with the following: 'SliceEventFactor': The factor of the event slicing. This corresponds to the proportion of the the total proton charge, which the slice corresponds to. 'OutputWorkspace' : The slice workspace 'OutputWorkspaceMonitor' : The output monitor workspace which has the correct slice factor applied to it.
[ "Takes", "an", "event", "slice", "from", "an", "event", "workspace", ":", "param", "state_slice", ":", "The", "state", ".", "slice", "object", ":", "param", "input_ws", ":", "The", "input", "workspace", ".", "If", "it", "is", "an", "event", "workspace", ...
def slice_sans_event(state_slice, input_ws, input_ws_monitor, data_type_str="Sample"): """ Takes an event slice from an event workspace :param state_slice: The state.slice object :param input_ws: The input workspace. If it is an event workspace, then the slice is taken. In case of a Workspace2D the original workspace is returned :param input_ws_monitor: The monitor workspace associated with the main input workspace. :param data_type_str: The component of the instrument which is to be reduced. Allowed values: ['Sample', 'Can'] :return: A dict with the following: 'SliceEventFactor': The factor of the event slicing. This corresponds to the proportion of the the total proton charge, which the slice corresponds to. 'OutputWorkspace' : The slice workspace 'OutputWorkspaceMonitor' : The output monitor workspace which has the correct slice factor applied to it. """ data_type = DataType(data_type_str) # This should be removed in the future when cycle 19/1 data is unlikely to be processed by users # This prevents time slicing falling over, since we wrap around and get -0 _clean_logs(ws=input_ws, estimate_logs=True) if isinstance(input_ws, Workspace2D): sliced_workspace = input_ws slice_factor = 1.0 else: sliced_workspace, slice_factor = _create_slice(workspace=input_ws, slice_info=state_slice, data_type=data_type) # Scale the monitor accordingly slice_monitor = _scale_monitors(slice_factor=slice_factor, input_monitor_ws=input_ws_monitor) # Set the outputs append_to_sans_file_tag(sliced_workspace, "_sliced") to_return = {"OutputWorkspace": sliced_workspace, "SliceEventFactor": slice_factor, "OutputWorkspaceMonitor": slice_monitor} return to_return
[ "def", "slice_sans_event", "(", "state_slice", ",", "input_ws", ",", "input_ws_monitor", ",", "data_type_str", "=", "\"Sample\"", ")", ":", "data_type", "=", "DataType", "(", "data_type_str", ")", "# This should be removed in the future when cycle 19/1 data is unlikely to be ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/slice_sans_event.py#L14-L52
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_diagram.py
python
Diagram.GetQuickEditMode
(self)
return self._quickEditMode
Return quick edit mode.
Return quick edit mode.
[ "Return", "quick", "edit", "mode", "." ]
def GetQuickEditMode(self): """Return quick edit mode.""" return self._quickEditMode
[ "def", "GetQuickEditMode", "(", "self", ")", ":", "return", "self", ".", "_quickEditMode" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_diagram.py#L146-L148
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/openpgp/sap/pkt/Packet.py
python
Packet.fill
(self, d)
Set the Packet instances's data, filling its attributes. :Parameters: - `d`: string of OpenPGP packet data :Returns: Nothing Tag data (d) must be a string of valid OpenPGP packet data (tag, length, body, and possibly partial length/body interlacing). Example: >>> tag = chr(0xb4) # old version, user id (type 13), single octet length >>> length = chr(0x17) # body occupies next 23 octets >>> body = "Tester <test@email.com>" >>> pkt = Packet(tag+length+body) >>> pkt.tag.type, pkt.length.size, pkt.body.value 13, 23, 'Tester <test@email.com>'
Set the Packet instances's data, filling its attributes.
[ "Set", "the", "Packet", "instances", "s", "data", "filling", "its", "attributes", "." ]
def fill(self, d): """Set the Packet instances's data, filling its attributes. :Parameters: - `d`: string of OpenPGP packet data :Returns: Nothing Tag data (d) must be a string of valid OpenPGP packet data (tag, length, body, and possibly partial length/body interlacing). Example: >>> tag = chr(0xb4) # old version, user id (type 13), single octet length >>> length = chr(0x17) # body occupies next 23 octets >>> body = "Tester <test@email.com>" >>> pkt = Packet(tag+length+body) >>> pkt.tag.type, pkt.length.size, pkt.body.value 13, 23, 'Tester <test@email.com>' """ # Partial Length Mechanics (..elif 1 == self.tag.version..): Body # length is determined locally (with the help of str2int # functions) to accomodate a flow between partial body fragments, # concluding fragments, and complete packet bodies (append to # list, concatenate the list at the end). The actual length object # is determined after the fact and must match up with the body # data recovered in order to pass a selfcheck(). # TODO see how much of the new length logic can use NewLength.data2size. self.tag = Tag(d[0:1]) if 0 == self.tag.version: # old lo = [1, 2, 4, 0][self.tag.length_type] # [length octs][length type] idx = 1 + lo self.length = OldLength(d[1:idx]) if 'UNDEFINED' == self.length.size: self.fill_body(d[idx:]) else: self.fill_body(d[idx:idx+self.length.size]) elif 1 == self.tag.version: # new idx = 1 bodydata, lengthdata = [], [] L1 = d[idx:idx+1] L1_ord = ord(L1) while 224 <= L1_ord <= 254: # catch partials size, idx = STN.strcalc(STN.partial2int, L1, idx) if 0 == len(lengthdata) and 512 > size: raise PGPFormatError("First partial length MUST be at least 512 octets long. Received: length.size->(%s) length.data->(%s)" % (len(lengthdata), hex(L1_ord))) else: lengthdata.append(L1) bodydata.append(d[idx:idx+size]) idx = idx + size L1 = d[idx:idx+1] L1_ord = ord(L1) if L1_ord < 192: size, idx = STN.strcalc(STN.str2int, L1, idx) lengthdata.append(L1) bodydata.append(d[idx:idx+size]) elif 192 <= L1_ord <= 223: lengthdata.append(d[idx:idx+2]) size, idx = STN.strcalc(STN.doubleoct2int, d[idx:idx+2], idx) bodydata.append(d[idx:idx+size]) elif 255 == L1_ord: lengthdata.append(d[idx:idx+5]) size, idx = STN.strcalc(STN.pentoct2int, d[idx:idx+5], idx) bodydata.append(d[idx:idx+size]) else: raise PGPError, "Extreme weirdness. Fix source." self.length = NewLength(''.join(lengthdata)) self.fill_body(''.join(bodydata)) self.size = len(self.tag._d) + len(self.length._d) + len(self.body._d) if self.check(): return 1 else: raise self.err[0], self.err[1]
[ "def", "fill", "(", "self", ",", "d", ")", ":", "# Partial Length Mechanics (..elif 1 == self.tag.version..): Body", "# length is determined locally (with the help of str2int", "# functions) to accomodate a flow between partial body fragments,", "# concluding fragments, and complete packet bod...
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/pkt/Packet.py#L294-L378
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/learn_io/dask_io.py
python
extract_dask_labels
(labels)
Extract data from dask.Series or dask.DataFrame for labels. Given a distributed dask.DataFrame or dask.Series containing exactly one column or name, this operation returns a single dask.DataFrame or dask.Series that can be iterated over. Args: labels: A distributed dask.DataFrame or dask.Series with exactly one column or name. Returns: A dask.DataFrame or dask.Series that can be iterated over. If the supplied argument is neither a dask.DataFrame nor a dask.Series this operation returns it without modification. Raises: ValueError: If the supplied dask.DataFrame contains more than one column or the supplied dask.Series contains more than one name.
Extract data from dask.Series or dask.DataFrame for labels.
[ "Extract", "data", "from", "dask", ".", "Series", "or", "dask", ".", "DataFrame", "for", "labels", "." ]
def extract_dask_labels(labels): """Extract data from dask.Series or dask.DataFrame for labels. Given a distributed dask.DataFrame or dask.Series containing exactly one column or name, this operation returns a single dask.DataFrame or dask.Series that can be iterated over. Args: labels: A distributed dask.DataFrame or dask.Series with exactly one column or name. Returns: A dask.DataFrame or dask.Series that can be iterated over. If the supplied argument is neither a dask.DataFrame nor a dask.Series this operation returns it without modification. Raises: ValueError: If the supplied dask.DataFrame contains more than one column or the supplied dask.Series contains more than one name. """ if isinstance(labels, dd.DataFrame): ncol = labels.columns elif isinstance(labels, dd.Series): ncol = labels.name if isinstance(labels, allowed_classes): if len(ncol) > 1: raise ValueError('Only one column for labels is allowed.') return _construct_dask_df_with_divisions(labels) else: return labels
[ "def", "extract_dask_labels", "(", "labels", ")", ":", "if", "isinstance", "(", "labels", ",", "dd", ".", "DataFrame", ")", ":", "ncol", "=", "labels", ".", "columns", "elif", "isinstance", "(", "labels", ",", "dd", ".", "Series", ")", ":", "ncol", "="...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py#L84-L114