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
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/generator/msvs.py
python
_GetUniquePlatforms
(spec)
return platforms
Returns the list of unique platforms for this spec, e.g ['win32', ...]. Arguments: spec: The target dictionary containing the properties of the target. Returns: The MSVSUserFile object created.
Returns the list of unique platforms for this spec, e.g ['win32', ...].
[ "Returns", "the", "list", "of", "unique", "platforms", "for", "this", "spec", "e", ".", "g", "[", "win32", "...", "]", "." ]
def _GetUniquePlatforms(spec): """Returns the list of unique platforms for this spec, e.g ['win32', ...]. Arguments: spec: The target dictionary containing the properties of the target. Returns: The MSVSUserFile object created. """ # Gather list of unique platforms. platforms = OrderedSet() for configuration in spec['configurations']: platforms.add(_ConfigPlatform(spec['configurations'][configuration])) platforms = list(platforms) return platforms
[ "def", "_GetUniquePlatforms", "(", "spec", ")", ":", "# Gather list of unique platforms.", "platforms", "=", "OrderedSet", "(", ")", "for", "configuration", "in", "spec", "[", "'configurations'", "]", ":", "platforms", ".", "add", "(", "_ConfigPlatform", "(", "spe...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/msvs.py#L1074-L1087
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TextAttr.HasFontUnderlined
(*args, **kwargs)
return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs)
HasFontUnderlined(self) -> bool
HasFontUnderlined(self) -> bool
[ "HasFontUnderlined", "(", "self", ")", "-", ">", "bool" ]
def HasFontUnderlined(*args, **kwargs): """HasFontUnderlined(self) -> bool""" return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs)
[ "def", "HasFontUnderlined", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_HasFontUnderlined", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L1804-L1806
PlatformLab/Arachne
e67391471007174dd4002dc2c160628e19c284e8
scripts/cpplint.py
python
FindStartOfExpressionInLine
(line, endpos, stack)
return (-1, stack)
Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line)
Find position at the matching start of current expression.
[ "Find", "position", "at", "the", "matching", "start", "of", "current", "expression", "." ]
def FindStartOfExpressionInLine(line, endpos, stack): """Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line) """ i = endpos while i >= 0: char = line[i] if char in ')]}': # Found end of expression, push to expression stack stack.append(char) elif char == '>': # Found potential end of template argument list. # # Ignore it if it's a "->" or ">=" or "operator>" if (i > 0 and (line[i - 1] == '-' or Match(r'\s>=\s', line[i - 1:]) or Search(r'\boperator\s*$', line[0:i]))): i -= 1 else: stack.append('>') elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator i -= 1 else: # If there is a matching '>', we can pop the expression stack. # Otherwise, ignore this '<' since it must be an operator. if stack and stack[-1] == '>': stack.pop() if not stack: return (i, None) elif char in '([{': # Found start of expression. # # If there are any unmatched '>' on the stack, they must be # operators. Remove those. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) if ((char == '(' and stack[-1] == ')') or (char == '[' and stack[-1] == ']') or (char == '{' and stack[-1] == '}')): stack.pop() if not stack: return (i, None) else: # Mismatched parentheses return (-1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '<', the matching '>' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) i -= 1 return (-1, stack)
[ "def", "FindStartOfExpressionInLine", "(", "line", ",", "endpos", ",", "stack", ")", ":", "i", "=", "endpos", "while", "i", ">=", "0", ":", "char", "=", "line", "[", "i", "]", "if", "char", "in", "')]}'", ":", "# Found end of expression, push to expression s...
https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L1614-L1688
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pydoc.py
python
HTMLDoc.markup
(self, text, escape=None, funcs={}, classes={}, methods={})
return ''.join(results)
Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.
Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.
[ "Mark", "up", "some", "plain", "text", "given", "a", "context", "of", "symbols", "to", "look", "for", ".", "Each", "context", "dictionary", "maps", "object", "names", "to", "anchor", "names", "." ]
def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|https|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?(\w+))') while True: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'https://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif selfdot: # Create a link for methods like 'self.method(...)' # and use <strong> for attributes like 'self.attr' if text[end:end+1] == '(': results.append('self.' + self.namelink(name, methods)) else: results.append('self.<strong>%s</strong>' % name) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return ''.join(results)
[ "def", "markup", "(", "self", ",", "text", ",", "escape", "=", "None", ",", "funcs", "=", "{", "}", ",", "classes", "=", "{", "}", ",", "methods", "=", "{", "}", ")", ":", "escape", "=", "escape", "or", "self", ".", "escape", "results", "=", "[...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pydoc.py#L673-L712
sailing-pmls/bosen
06cb58902d011fbea5f9428f10ce30e621492204
style_script/cpplint.py
python
FindNextMultiLineCommentEnd
(lines, lineix)
return len(lines)
We are inside a comment, find the end marker.
We are inside a comment, find the end marker.
[ "We", "are", "inside", "a", "comment", "find", "the", "end", "marker", "." ]
def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentEnd", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "endswith", "(", "'*/'", ")", ":", "return", "lineix", ...
https://github.com/sailing-pmls/bosen/blob/06cb58902d011fbea5f9428f10ce30e621492204/style_script/cpplint.py#L1241-L1247
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/mingw32ccompiler.py
python
_check_for_import_lib
()
return (False, candidates[0])
Check if an import library for the Python runtime already exists.
Check if an import library for the Python runtime already exists.
[ "Check", "if", "an", "import", "library", "for", "the", "Python", "runtime", "already", "exists", "." ]
def _check_for_import_lib(): """Check if an import library for the Python runtime already exists.""" major_version, minor_version = tuple(sys.version_info[:2]) # patterns for the file name of the library itself patterns = ['libpython%d%d.a', 'libpython%d%d.dll.a', 'libpython%d.%d.dll.a'] # directory trees that may contain the library stems = [sys.prefix] if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: stems.append(sys.base_prefix) elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: stems.append(sys.real_prefix) # possible subdirectories within those trees where it is placed sub_dirs = ['libs', 'lib'] # generate a list of candidate locations candidates = [] for pat in patterns: filename = pat % (major_version, minor_version) for stem_dir in stems: for folder in sub_dirs: candidates.append(os.path.join(stem_dir, folder, filename)) # test the filesystem to see if we can find any of these for fullname in candidates: if os.path.isfile(fullname): # already exists, in location given return (True, fullname) # needs to be built, preferred location given first return (False, candidates[0])
[ "def", "_check_for_import_lib", "(", ")", ":", "major_version", ",", "minor_version", "=", "tuple", "(", "sys", ".", "version_info", "[", ":", "2", "]", ")", "# patterns for the file name of the library itself", "patterns", "=", "[", "'libpython%d%d.a'", ",", "'libp...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/mingw32ccompiler.py#L420-L454
OkCupid/okws
1c337392c676ccb4e9a4c92d11d5d2fada6427d2
contrib/pub3-upgrade.py
python
Pub1Parser.p_pub
(self, p)
pub : switch | set | include | load | comment
pub : switch | set | include | load | comment
[ "pub", ":", "switch", "|", "set", "|", "include", "|", "load", "|", "comment" ]
def p_pub (self, p): '''pub : switch | set | include | load | comment ''' p[0] = p[1]
[ "def", "p_pub", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/contrib/pub3-upgrade.py#L872-L878
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/search.py
python
SearchResults.next_page
(self)
Call Cloudsearch to get the next page of search results :rtype: :class:`boto.cloudsearch2.search.SearchResults` :return: the following page of search results
Call Cloudsearch to get the next page of search results
[ "Call", "Cloudsearch", "to", "get", "the", "next", "page", "of", "search", "results" ]
def next_page(self): """Call Cloudsearch to get the next page of search results :rtype: :class:`boto.cloudsearch2.search.SearchResults` :return: the following page of search results """ if self.query.page <= self.num_pages_needed: self.query.start += self.query.real_size self.query.page += 1 return self.search_service(self.query) else: raise StopIteration
[ "def", "next_page", "(", "self", ")", ":", "if", "self", ".", "query", ".", "page", "<=", "self", ".", "num_pages_needed", ":", "self", ".", "query", ".", "start", "+=", "self", ".", "query", ".", "real_size", "self", ".", "query", ".", "page", "+=",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/search.py#L62-L73
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
Font.Scale
(*args, **kwargs)
return _gdi_.Font_Scale(*args, **kwargs)
Scale(self, float x) -> Font
Scale(self, float x) -> Font
[ "Scale", "(", "self", "float", "x", ")", "-", ">", "Font" ]
def Scale(*args, **kwargs): """Scale(self, float x) -> Font""" return _gdi_.Font_Scale(*args, **kwargs)
[ "def", "Scale", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Font_Scale", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L2472-L2474
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_diagram.py
python
Diagram.GetCount
(self)
return len(self._shapeList)
Return the number of shapes in the diagram.
Return the number of shapes in the diagram.
[ "Return", "the", "number", "of", "shapes", "in", "the", "diagram", "." ]
def GetCount(self): """Return the number of shapes in the diagram.""" return len(self._shapeList)
[ "def", "GetCount", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_shapeList", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_diagram.py#L165-L167
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/training/queue_runner.py
python
QueueRunner.name
(self)
return self._queue.name
The string name of the underlying Queue.
The string name of the underlying Queue.
[ "The", "string", "name", "of", "the", "underlying", "Queue", "." ]
def name(self): """The string name of the underlying Queue.""" return self._queue.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_queue", ".", "name" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/queue_runner.py#L165-L167
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/tree.py
python
TreeItem._GetSubList
(self)
return sublist
Do not override! Called by TreeNode.
Do not override! Called by TreeNode.
[ "Do", "not", "override!", "Called", "by", "TreeNode", "." ]
def _GetSubList(self): """Do not override! Called by TreeNode.""" if not self.IsExpandable(): return [] sublist = self.GetSubList() if not sublist: self.expandable = 0 return sublist
[ "def", "_GetSubList", "(", "self", ")", ":", "if", "not", "self", ".", "IsExpandable", "(", ")", ":", "return", "[", "]", "sublist", "=", "self", ".", "GetSubList", "(", ")", "if", "not", "sublist", ":", "self", ".", "expandable", "=", "0", "return",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/tree.py#L363-L370
dolphin-emu/dolphin
b4c7f2b1e834ce5ea4b2301f9d4fb07c11afeabb
Externals/fmt/support/rst2md.py
python
convert
(rst_path)
return core.publish_file(source_path=rst_path, writer=MDWriter())
Converts RST file to Markdown.
Converts RST file to Markdown.
[ "Converts", "RST", "file", "to", "Markdown", "." ]
def convert(rst_path): """Converts RST file to Markdown.""" return core.publish_file(source_path=rst_path, writer=MDWriter())
[ "def", "convert", "(", "rst_path", ")", ":", "return", "core", ".", "publish_file", "(", "source_path", "=", "rst_path", ",", "writer", "=", "MDWriter", "(", ")", ")" ]
https://github.com/dolphin-emu/dolphin/blob/b4c7f2b1e834ce5ea4b2301f9d4fb07c11afeabb/Externals/fmt/support/rst2md.py#L153-L155
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/__init__.py
python
Process.cpu_times
(self)
return self._proc.cpu_times()
Return a (user, system, children_user, children_system) namedtuple representing the accumulated process time, in seconds. This is similar to os.times() but per-process. On macOS and Windows children_user and children_system are always set to 0.
Return a (user, system, children_user, children_system) namedtuple representing the accumulated process time, in seconds. This is similar to os.times() but per-process. On macOS and Windows children_user and children_system are always set to 0.
[ "Return", "a", "(", "user", "system", "children_user", "children_system", ")", "namedtuple", "representing", "the", "accumulated", "process", "time", "in", "seconds", ".", "This", "is", "similar", "to", "os", ".", "times", "()", "but", "per", "-", "process", ...
def cpu_times(self): """Return a (user, system, children_user, children_system) namedtuple representing the accumulated process time, in seconds. This is similar to os.times() but per-process. On macOS and Windows children_user and children_system are always set to 0. """ return self._proc.cpu_times()
[ "def", "cpu_times", "(", "self", ")", ":", "return", "self", ".", "_proc", ".", "cpu_times", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/__init__.py#L1051-L1059
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/models/rnn/translate/seq2seq_model.py
python
Seq2SeqModel.__init__
(self, source_vocab_size, target_vocab_size, buckets, size, num_layers, max_gradient_norm, batch_size, learning_rate, learning_rate_decay_factor, use_lstm=False, num_samples=512, forward_only=False)
Create the model. Args: source_vocab_size: size of the source vocabulary. target_vocab_size: size of the target vocabulary. buckets: a list of pairs (I, O), where I specifies maximum input length that will be processed in that bucket, and O specifies maximum output length. Training instances that have inputs longer than I or outputs longer than O will be pushed to the next bucket and padded accordingly. We assume that the list is sorted, e.g., [(2, 4), (8, 16)]. size: number of units in each layer of the model. num_layers: number of layers in the model. max_gradient_norm: gradients will be clipped to maximally this norm. batch_size: the size of the batches used during training; the model construction is independent of batch_size, so it can be changed after initialization if this is convenient, e.g., for decoding. learning_rate: learning rate to start with. learning_rate_decay_factor: decay learning rate by this much when needed. use_lstm: if true, we use LSTM cells instead of GRU cells. num_samples: number of samples for sampled softmax. forward_only: if set, we do not construct the backward pass in the model.
Create the model.
[ "Create", "the", "model", "." ]
def __init__(self, source_vocab_size, target_vocab_size, buckets, size, num_layers, max_gradient_norm, batch_size, learning_rate, learning_rate_decay_factor, use_lstm=False, num_samples=512, forward_only=False): """Create the model. Args: source_vocab_size: size of the source vocabulary. target_vocab_size: size of the target vocabulary. buckets: a list of pairs (I, O), where I specifies maximum input length that will be processed in that bucket, and O specifies maximum output length. Training instances that have inputs longer than I or outputs longer than O will be pushed to the next bucket and padded accordingly. We assume that the list is sorted, e.g., [(2, 4), (8, 16)]. size: number of units in each layer of the model. num_layers: number of layers in the model. max_gradient_norm: gradients will be clipped to maximally this norm. batch_size: the size of the batches used during training; the model construction is independent of batch_size, so it can be changed after initialization if this is convenient, e.g., for decoding. learning_rate: learning rate to start with. learning_rate_decay_factor: decay learning rate by this much when needed. use_lstm: if true, we use LSTM cells instead of GRU cells. num_samples: number of samples for sampled softmax. forward_only: if set, we do not construct the backward pass in the model. """ self.source_vocab_size = source_vocab_size self.target_vocab_size = target_vocab_size self.buckets = buckets self.batch_size = batch_size self.learning_rate = tf.Variable(float(learning_rate), trainable=False) self.learning_rate_decay_op = self.learning_rate.assign( self.learning_rate * learning_rate_decay_factor) self.global_step = tf.Variable(0, trainable=False) # If we use sampled softmax, we need an output projection. output_projection = None softmax_loss_function = None # Sampled softmax only makes sense if we sample less than vocabulary size. if num_samples > 0 and num_samples < self.target_vocab_size: w = tf.get_variable("proj_w", [size, self.target_vocab_size]) w_t = tf.transpose(w) b = tf.get_variable("proj_b", [self.target_vocab_size]) output_projection = (w, b) def sampled_loss(inputs, labels): labels = tf.reshape(labels, [-1, 1]) return tf.nn.sampled_softmax_loss(w_t, b, inputs, labels, num_samples, self.target_vocab_size) softmax_loss_function = sampled_loss # Create the internal multi-layer cell for our RNN. single_cell = tf.nn.rnn_cell.GRUCell(size) if use_lstm: single_cell = tf.nn.rnn_cell.BasicLSTMCell(size) cell = single_cell if num_layers > 1: cell = tf.nn.rnn_cell.MultiRNNCell([single_cell] * num_layers) # The seq2seq function: we use embedding for the input and attention. def seq2seq_f(encoder_inputs, decoder_inputs, do_decode): return tf.nn.seq2seq.embedding_attention_seq2seq( encoder_inputs, decoder_inputs, cell, num_encoder_symbols=source_vocab_size, num_decoder_symbols=target_vocab_size, embedding_size=size, output_projection=output_projection, feed_previous=do_decode) # Feeds for inputs. self.encoder_inputs = [] self.decoder_inputs = [] self.target_weights = [] for i in xrange(buckets[-1][0]): # Last bucket is the biggest one. self.encoder_inputs.append(tf.placeholder(tf.int32, shape=[None], name="encoder{0}".format(i))) for i in xrange(buckets[-1][1] + 1): self.decoder_inputs.append(tf.placeholder(tf.int32, shape=[None], name="decoder{0}".format(i))) self.target_weights.append(tf.placeholder(tf.float32, shape=[None], name="weight{0}".format(i))) # Our targets are decoder inputs shifted by one. targets = [self.decoder_inputs[i + 1] for i in xrange(len(self.decoder_inputs) - 1)] # Training outputs and losses. if forward_only: self.outputs, self.losses = tf.nn.seq2seq.model_with_buckets( self.encoder_inputs, self.decoder_inputs, targets, self.target_weights, buckets, lambda x, y: seq2seq_f(x, y, True), softmax_loss_function=softmax_loss_function) # If we use output projection, we need to project outputs for decoding. if output_projection is not None: for b in xrange(len(buckets)): self.outputs[b] = [ tf.matmul(output, output_projection[0]) + output_projection[1] for output in self.outputs[b] ] else: self.outputs, self.losses = tf.nn.seq2seq.model_with_buckets( self.encoder_inputs, self.decoder_inputs, targets, self.target_weights, buckets, lambda x, y: seq2seq_f(x, y, False), softmax_loss_function=softmax_loss_function) # Gradients and SGD update operation for training the model. params = tf.trainable_variables() if not forward_only: self.gradient_norms = [] self.updates = [] opt = tf.train.GradientDescentOptimizer(self.learning_rate) for b in xrange(len(buckets)): gradients = tf.gradients(self.losses[b], params) clipped_gradients, norm = tf.clip_by_global_norm(gradients, max_gradient_norm) self.gradient_norms.append(norm) self.updates.append(opt.apply_gradients( zip(clipped_gradients, params), global_step=self.global_step)) self.saver = tf.train.Saver(tf.all_variables())
[ "def", "__init__", "(", "self", ",", "source_vocab_size", ",", "target_vocab_size", ",", "buckets", ",", "size", ",", "num_layers", ",", "max_gradient_norm", ",", "batch_size", ",", "learning_rate", ",", "learning_rate_decay_factor", ",", "use_lstm", "=", "False", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/models/rnn/translate/seq2seq_model.py#L46-L166
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Node/FS.py
python
Dir.__clearRepositoryCache
(self, duplicate=None)
Called when we change the repository(ies) for a directory. This clears any cached information that is invalidated by changing the repository.
Called when we change the repository(ies) for a directory. This clears any cached information that is invalidated by changing the repository.
[ "Called", "when", "we", "change", "the", "repository", "(", "ies", ")", "for", "a", "directory", ".", "This", "clears", "any", "cached", "information", "that", "is", "invalidated", "by", "changing", "the", "repository", "." ]
def __clearRepositoryCache(self, duplicate=None): """Called when we change the repository(ies) for a directory. This clears any cached information that is invalidated by changing the repository.""" for node in self.entries.values(): if node != self.dir: if node != self and isinstance(node, Dir): node.__clearRepositoryCache(duplicate) else: node.clear() try: del node._srcreps except AttributeError: pass if duplicate is not None: node.duplicate = duplicate
[ "def", "__clearRepositoryCache", "(", "self", ",", "duplicate", "=", "None", ")", ":", "for", "node", "in", "self", ".", "entries", ".", "values", "(", ")", ":", "if", "node", "!=", "self", ".", "dir", ":", "if", "node", "!=", "self", "and", "isinsta...
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L1612-L1628
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/filter/all_.py
python
All.__reduce__
(self)
return (type(self), tuple())
Enable (deep)copying and pickling of `All` particle filters.
Enable (deep)copying and pickling of `All` particle filters.
[ "Enable", "(", "deep", ")", "copying", "and", "pickling", "of", "All", "particle", "filters", "." ]
def __reduce__(self): """Enable (deep)copying and pickling of `All` particle filters.""" return (type(self), tuple())
[ "def", "__reduce__", "(", "self", ")", ":", "return", "(", "type", "(", "self", ")", ",", "tuple", "(", ")", ")" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/filter/all_.py#L28-L30
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
LogBuffer.__init__
(self, *args, **kwargs)
__init__(self) -> LogBuffer
__init__(self) -> LogBuffer
[ "__init__", "(", "self", ")", "-", ">", "LogBuffer" ]
def __init__(self, *args, **kwargs): """__init__(self) -> LogBuffer""" _misc_.LogBuffer_swiginit(self,_misc_.new_LogBuffer(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "LogBuffer_swiginit", "(", "self", ",", "_misc_", ".", "new_LogBuffer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1828-L1830
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridCellAttr.SetBackgroundColour
(*args, **kwargs)
return _grid.GridCellAttr_SetBackgroundColour(*args, **kwargs)
SetBackgroundColour(self, Colour colBack)
SetBackgroundColour(self, Colour colBack)
[ "SetBackgroundColour", "(", "self", "Colour", "colBack", ")" ]
def SetBackgroundColour(*args, **kwargs): """SetBackgroundColour(self, Colour colBack)""" return _grid.GridCellAttr_SetBackgroundColour(*args, **kwargs)
[ "def", "SetBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellAttr_SetBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L547-L549
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py
python
Index.isna
(self)
return self._isnan
Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as ``None``, :attr:`numpy.NaN` or :attr:`pd.NaT`, get mapped to ``True`` values. Everything else get mapped to ``False`` values. Characters such as empty strings `''` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). Returns ------- numpy.ndarray A boolean array of whether my values are NA. See Also -------- Index.notna : Boolean inverse of isna. Index.dropna : Omit entries with missing values. isna : Top-level isna. Series.isna : Detect missing values in Series object. Examples -------- Show which entries in a pandas.Index are NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.isna() array([False, False, True], dtype=bool) Empty strings are not considered NA values. None is considered an NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.isna() array([False, False, False, True], dtype=bool) For datetimes, `NaT` (Not a Time) is considered as an NA value. >>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'), ... pd.Timestamp(''), None, pd.NaT]) >>> idx DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'], dtype='datetime64[ns]', freq=None) >>> idx.isna() array([False, True, True, True], dtype=bool)
Detect missing values.
[ "Detect", "missing", "values", "." ]
def isna(self): """ Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as ``None``, :attr:`numpy.NaN` or :attr:`pd.NaT`, get mapped to ``True`` values. Everything else get mapped to ``False`` values. Characters such as empty strings `''` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). Returns ------- numpy.ndarray A boolean array of whether my values are NA. See Also -------- Index.notna : Boolean inverse of isna. Index.dropna : Omit entries with missing values. isna : Top-level isna. Series.isna : Detect missing values in Series object. Examples -------- Show which entries in a pandas.Index are NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.isna() array([False, False, True], dtype=bool) Empty strings are not considered NA values. None is considered an NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.isna() array([False, False, False, True], dtype=bool) For datetimes, `NaT` (Not a Time) is considered as an NA value. >>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'), ... pd.Timestamp(''), None, pd.NaT]) >>> idx DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'], dtype='datetime64[ns]', freq=None) >>> idx.isna() array([False, True, True, True], dtype=bool) """ return self._isnan
[ "def", "isna", "(", "self", ")", ":", "return", "self", ".", "_isnan" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L1785-L1838
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
_ExtractImportantEnvironment
(output_of_set)
return env
Extracts environment variables required for the toolchain to run from a textual dump output by the cmd.exe 'set' command.
Extracts environment variables required for the toolchain to run from a textual dump output by the cmd.exe 'set' command.
[ "Extracts", "environment", "variables", "required", "for", "the", "toolchain", "to", "run", "from", "a", "textual", "dump", "output", "by", "the", "cmd", ".", "exe", "set", "command", "." ]
def _ExtractImportantEnvironment(output_of_set): """Extracts environment variables required for the toolchain to run from a textual dump output by the cmd.exe 'set' command.""" envvars_to_save = ( "goma_.*", # TODO(scottmg): This is ugly, but needed for goma. "include", "lib", "libpath", "path", "pathext", "systemroot", "temp", "tmp", ) env = {} # This occasionally happens and leads to misleading SYSTEMROOT error messages # if not caught here. if output_of_set.count("=") == 0: raise Exception("Invalid output_of_set. Value is:\n%s" % output_of_set) for line in output_of_set.splitlines(): for envvar in envvars_to_save: if re.match(envvar + "=", line.lower()): var, setting = line.split("=", 1) if envvar == "path": # Our own rules (for running gyp-win-tool) and other actions in # Chromium rely on python being in the path. Add the path to this # python here so that if it's not in the path when ninja is run # later, python will still be found. setting = os.path.dirname(sys.executable) + os.pathsep + setting env[var.upper()] = setting break for required in ("SYSTEMROOT", "TEMP", "TMP"): if required not in env: raise Exception( 'Environment variable "%s" ' "required to be set to valid path" % required ) return env
[ "def", "_ExtractImportantEnvironment", "(", "output_of_set", ")", ":", "envvars_to_save", "=", "(", "\"goma_.*\"", ",", "# TODO(scottmg): This is ugly, but needed for goma.", "\"include\"", ",", "\"lib\"", ",", "\"libpath\"", ",", "\"path\"", ",", "\"pathext\"", ",", "\"s...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L1115-L1152
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py
python
_EagerVariableStore._get_single_variable
( self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, partition_info=None, reuse=None, trainable=None, caching_device=None, validate_shape=True, constraint=None, synchronization=vs.VariableSynchronization.AUTO, aggregation=vs.VariableAggregation.NONE)
return v
Get or create a single Variable (e.g. a shard or entire variable). See the documentation of get_variable above (ignore partitioning components) for details. Args: name: see get_variable. shape: see get_variable. dtype: see get_variable. initializer: see get_variable. regularizer: see get_variable. partition_info: _PartitionInfo object. reuse: see get_variable. trainable: see get_variable. caching_device: see get_variable. validate_shape: see get_variable. constraint: see get_variable. synchronization: see get_variable. aggregation: see get_variable. Returns: A Variable. See documentation of get_variable above. Raises: ValueError: See documentation of get_variable above.
Get or create a single Variable (e.g.
[ "Get", "or", "create", "a", "single", "Variable", "(", "e", ".", "g", "." ]
def _get_single_variable( self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, partition_info=None, reuse=None, trainable=None, caching_device=None, validate_shape=True, constraint=None, synchronization=vs.VariableSynchronization.AUTO, aggregation=vs.VariableAggregation.NONE): """Get or create a single Variable (e.g. a shard or entire variable). See the documentation of get_variable above (ignore partitioning components) for details. Args: name: see get_variable. shape: see get_variable. dtype: see get_variable. initializer: see get_variable. regularizer: see get_variable. partition_info: _PartitionInfo object. reuse: see get_variable. trainable: see get_variable. caching_device: see get_variable. validate_shape: see get_variable. constraint: see get_variable. synchronization: see get_variable. aggregation: see get_variable. Returns: A Variable. See documentation of get_variable above. Raises: ValueError: See documentation of get_variable above. """ # Set to true if initializer is a constant. initializing_from_value = False if initializer is not None and not callable(initializer): initializing_from_value = True if shape is not None and initializing_from_value: raise ValueError("If initializer is a constant, do not specify shape.") dtype = dtypes.as_dtype(dtype) shape = as_shape(shape) if name in self._vars: # Here we handle the case when returning an existing variable. if reuse is False: # pylint: disable=g-bool-id-comparison err_msg = ("Variable %s already exists, disallowed." " Did you mean to set reuse=True or " "reuse=tf.AUTO_REUSE in VarScope?" % name) # ResourceVariables don't have an op associated with so no traceback raise ValueError(err_msg) found_var = self._vars[name] if not shape.is_compatible_with(found_var.get_shape()): raise ValueError("Trying to share variable %s, but specified shape %s" " and found shape %s." % (name, shape, found_var.get_shape())) if not dtype.is_compatible_with(found_var.dtype): dtype_str = dtype.name found_type_str = found_var.dtype.name raise ValueError("Trying to share variable %s, but specified dtype %s" " and found dtype %s." % (name, dtype_str, found_type_str)) return found_var # The code below handles only the case of creating a new variable. if reuse is True: # pylint: disable=g-bool-id-comparison raise ValueError("Variable %s does not exist, or was not created with " "tf.get_variable(). Did you mean to set " "reuse=tf.AUTO_REUSE in VarScope?" % name) # Create the tensor to initialize the variable with default value. if initializer is None: initializer, initializing_from_value = self._get_default_initializer( name=name, shape=shape, dtype=dtype) # Enter an init scope when creating the initializer. with ops.init_scope(): if initializing_from_value: init_val = initializer variable_dtype = None else: # Instantiate initializer if provided initializer is a type object. if tf_inspect.isclass(initializer): initializer = initializer() if shape.is_fully_defined(): if "partition_info" in tf_inspect.getargspec(initializer).args: init_val = functools.partial(initializer, shape.as_list(), dtype=dtype, partition_info=partition_info) else: init_val = functools.partial(initializer, shape.as_list(), dtype=dtype) variable_dtype = dtype.base_dtype else: init_val = initializer variable_dtype = None # Create the variable (Always eagerly as a workaround for a strange # tpu / funcgraph / keras functional model interaction ) with ops.init_scope(): v = variables.Variable( initial_value=init_val, name=name, trainable=trainable, caching_device=caching_device, dtype=variable_dtype, validate_shape=validate_shape, constraint=constraint, synchronization=synchronization, aggregation=aggregation) self._vars[name] = v logging.vlog(1, "Created variable %s with shape %s and init %s", v.name, format(shape), initializer) # Run the regularizer if requested and save the resulting loss. if regularizer: self.add_regularizer(v, regularizer) return v
[ "def", "_get_single_variable", "(", "self", ",", "name", ",", "shape", "=", "None", ",", "dtype", "=", "dtypes", ".", "float32", ",", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "partition_info", "=", "None", ",", "reuse", "=", "Non...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py#L388-L517
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/xml/sax/xmlreader.py
python
Locator.getPublicId
(self)
return None
Return the public identifier for the current event.
Return the public identifier for the current event.
[ "Return", "the", "public", "identifier", "for", "the", "current", "event", "." ]
def getPublicId(self): "Return the public identifier for the current event." return None
[ "def", "getPublicId", "(", "self", ")", ":", "return", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/sax/xmlreader.py#L179-L181
tangzhenyu/Scene-Text-Understanding
0f7ffc7aea5971a50cdc03d33d0a41075285948b
ctpn_crnn_ocr/CTPN/caffe/python/summarize.py
python
print_table
(table, max_width)
Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.
Print a simple nicely-aligned table.
[ "Print", "a", "simple", "nicely", "-", "aligned", "table", "." ]
def print_table(table, max_width): """Print a simple nicely-aligned table. table must be a list of (equal-length) lists. Columns are space-separated, and as narrow as possible, but no wider than max_width. Text may overflow columns; note that unlike string.format, this will not affect subsequent columns, if possible.""" max_widths = [max_width] * len(table[0]) column_widths = [max(printed_len(row[j]) + 1 for row in table) for j in range(len(table[0]))] column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)] for row in table: row_str = '' right_col = 0 for cell, width in zip(row, column_widths): right_col += width row_str += cell + ' ' row_str += ' ' * max(right_col - printed_len(row_str), 0) print row_str
[ "def", "print_table", "(", "table", ",", "max_width", ")", ":", "max_widths", "=", "[", "max_width", "]", "*", "len", "(", "table", "[", "0", "]", ")", "column_widths", "=", "[", "max", "(", "printed_len", "(", "row", "[", "j", "]", ")", "+", "1", ...
https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/ctpn_crnn_ocr/CTPN/caffe/python/summarize.py#L41-L61
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/platform.py
python
python_version
()
return _sys_version()[1]
Returns the Python version as string 'major.minor.patchlevel' Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0).
Returns the Python version as string 'major.minor.patchlevel'
[ "Returns", "the", "Python", "version", "as", "string", "major", ".", "minor", ".", "patchlevel" ]
def python_version(): """ Returns the Python version as string 'major.minor.patchlevel' Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0). """ return _sys_version()[1]
[ "def", "python_version", "(", ")", ":", "return", "_sys_version", "(", ")", "[", "1", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/platform.py#L1518-L1526
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
clang/utils/check_cfc/check_cfc.py
python
main_is_frozen
()
return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__"))
Returns True when running as a py2exe executable.
Returns True when running as a py2exe executable.
[ "Returns", "True", "when", "running", "as", "a", "py2exe", "executable", "." ]
def main_is_frozen(): """Returns True when running as a py2exe executable.""" return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__"))
[ "def", "main_is_frozen", "(", ")", ":", "return", "(", "hasattr", "(", "sys", ",", "\"frozen\"", ")", "or", "# new py2exe", "hasattr", "(", "sys", ",", "\"importers\"", ")", "or", "# old py2exe", "imp", ".", "is_frozen", "(", "\"__main__\"", ")", ")" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/utils/check_cfc/check_cfc.py#L84-L88
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/op_def_registry.py
python
get_registered_ops
()
return _registered_ops
Returns a dictionary mapping names to OpDefs.
Returns a dictionary mapping names to OpDefs.
[ "Returns", "a", "dictionary", "mapping", "names", "to", "OpDefs", "." ]
def get_registered_ops(): """Returns a dictionary mapping names to OpDefs.""" return _registered_ops
[ "def", "get_registered_ops", "(", ")", ":", "return", "_registered_ops" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/op_def_registry.py#L40-L42
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
GridCellFloatRenderer.GetFormat
(*args, **kwargs)
return _grid.GridCellFloatRenderer_GetFormat(*args, **kwargs)
GetFormat(self) -> int
GetFormat(self) -> int
[ "GetFormat", "(", "self", ")", "-", ">", "int" ]
def GetFormat(*args, **kwargs): """GetFormat(self) -> int""" return _grid.GridCellFloatRenderer_GetFormat(*args, **kwargs)
[ "def", "GetFormat", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellFloatRenderer_GetFormat", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L203-L205
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/appstats.py
python
DeviceSnapshot.GetTimestamp
(self)
return self.timestamp
Returns the time since program start that this snapshot was taken.
Returns the time since program start that this snapshot was taken.
[ "Returns", "the", "time", "since", "program", "start", "that", "this", "snapshot", "was", "taken", "." ]
def GetTimestamp(self): """Returns the time since program start that this snapshot was taken.""" return self.timestamp
[ "def", "GetTimestamp", "(", "self", ")", ":", "return", "self", ".", "timestamp" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/appstats.py#L424-L426
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ListEvent.GetLabel
(*args, **kwargs)
return _controls_.ListEvent_GetLabel(*args, **kwargs)
GetLabel(self) -> String
GetLabel(self) -> String
[ "GetLabel", "(", "self", ")", "-", ">", "String" ]
def GetLabel(*args, **kwargs): """GetLabel(self) -> String""" return _controls_.ListEvent_GetLabel(*args, **kwargs)
[ "def", "GetLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListEvent_GetLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4326-L4328
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/contrib/data/vision/transforms/bbox/utils.py
python
bbox_xyxy_to_xywh
(xyxy)
Convert bounding boxes from format (xmin, ymin, xmax, ymax) to (x, y, w, h). Parameters ---------- xyxy : list, tuple or numpy.ndarray The bbox in format (xmin, ymin, xmax, ymax). If numpy.ndarray is provided, we expect multiple bounding boxes with shape `(N, 4)`. Returns ------- tuple or numpy.ndarray The converted bboxes in format (x, y, w, h). If input is numpy.ndarray, return is numpy.ndarray correspondingly.
Convert bounding boxes from format (xmin, ymin, xmax, ymax) to (x, y, w, h).
[ "Convert", "bounding", "boxes", "from", "format", "(", "xmin", "ymin", "xmax", "ymax", ")", "to", "(", "x", "y", "w", "h", ")", "." ]
def bbox_xyxy_to_xywh(xyxy): """Convert bounding boxes from format (xmin, ymin, xmax, ymax) to (x, y, w, h). Parameters ---------- xyxy : list, tuple or numpy.ndarray The bbox in format (xmin, ymin, xmax, ymax). If numpy.ndarray is provided, we expect multiple bounding boxes with shape `(N, 4)`. Returns ------- tuple or numpy.ndarray The converted bboxes in format (x, y, w, h). If input is numpy.ndarray, return is numpy.ndarray correspondingly. """ if isinstance(xyxy, (tuple, list)): if not len(xyxy) == 4: raise IndexError( "Bounding boxes must have 4 elements, given {}".format(len(xyxy))) x1, y1 = xyxy[0], xyxy[1] w, h = xyxy[2] - x1 + 1, xyxy[3] - y1 + 1 return x1, y1, w, h elif isinstance(xyxy, np.ndarray): if not xyxy.size % 4 == 0: raise IndexError( "Bounding boxes must have n * 4 elements, given {}".format(xyxy.shape)) return np.hstack((xyxy[:, :2], xyxy[:, 2:4] - xyxy[:, :2] + 1)) else: raise TypeError( 'Expect input xywh a list, tuple or numpy.ndarray, given {}'.format(type(xyxy)))
[ "def", "bbox_xyxy_to_xywh", "(", "xyxy", ")", ":", "if", "isinstance", "(", "xyxy", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "not", "len", "(", "xyxy", ")", "==", "4", ":", "raise", "IndexError", "(", "\"Bounding boxes must have 4 elements, giv...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/contrib/data/vision/transforms/bbox/utils.py#L252-L283
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/palindrome-permutation-ii.py
python
Solution2.generatePalindromes
(self, s)
return [''.join(half_palindrome + mid + half_palindrome[::-1]) \ for half_palindrome in set(itertools.permutations(chars))] if len(mid) < 2 else []
:type s: str :rtype: List[str]
:type s: str :rtype: List[str]
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "List", "[", "str", "]" ]
def generatePalindromes(self, s): """ :type s: str :rtype: List[str] """ cnt = collections.Counter(s) mid = tuple(k for k, v in cnt.iteritems() if v % 2) chars = ''.join(k * (v / 2) for k, v in cnt.iteritems()) return [''.join(half_palindrome + mid + half_palindrome[::-1]) \ for half_palindrome in set(itertools.permutations(chars))] if len(mid) < 2 else []
[ "def", "generatePalindromes", "(", "self", ",", "s", ")", ":", "cnt", "=", "collections", ".", "Counter", "(", "s", ")", "mid", "=", "tuple", "(", "k", "for", "k", ",", "v", "in", "cnt", ".", "iteritems", "(", ")", "if", "v", "%", "2", ")", "ch...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/palindrome-permutation-ii.py#L39-L48
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py
python
TFAsymmetryFittingModel._update_tf_asymmetry_simultaneous_fit_function_after_sequential
(self, workspaces: list, functions: list)
Updates the single fit functions after a sequential fit has been run on the Sequential fitting tab.
Updates the single fit functions after a sequential fit has been run on the Sequential fitting tab.
[ "Updates", "the", "single", "fit", "functions", "after", "a", "sequential", "fit", "has", "been", "run", "on", "the", "Sequential", "fitting", "tab", "." ]
def _update_tf_asymmetry_simultaneous_fit_function_after_sequential(self, workspaces: list, functions: list) -> None: """Updates the single fit functions after a sequential fit has been run on the Sequential fitting tab.""" for fit_index, workspace_names in enumerate(workspaces): if self._are_same_workspaces_as_the_datasets(workspace_names): self.update_tf_asymmetry_simultaneous_fit_function(functions[fit_index]) break
[ "def", "_update_tf_asymmetry_simultaneous_fit_function_after_sequential", "(", "self", ",", "workspaces", ":", "list", ",", "functions", ":", "list", ")", "->", "None", ":", "for", "fit_index", ",", "workspace_names", "in", "enumerate", "(", "workspaces", ")", ":", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py#L900-L905
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/clang/bindings/python/clang/cindex.py
python
CursorKind.is_invalid
(self)
return conf.lib.clang_isInvalid(self)
Test if this is an invalid kind.
Test if this is an invalid kind.
[ "Test", "if", "this", "is", "an", "invalid", "kind", "." ]
def is_invalid(self): """Test if this is an invalid kind.""" return conf.lib.clang_isInvalid(self)
[ "def", "is_invalid", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isInvalid", "(", "self", ")" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L691-L693
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/files.py
python
TreeMatcher.info
(self)
return self.dirs
A list of strings for displaying when dumping state.
A list of strings for displaying when dumping state.
[ "A", "list", "of", "strings", "for", "displaying", "when", "dumping", "state", "." ]
def info(self): """A list of strings for displaying when dumping state.""" return self.dirs
[ "def", "info", "(", "self", ")", ":", "return", "self", ".", "dirs" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/files.py#L193-L195
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/multiprocessing/managers.py
python
BaseProxy.__str__
(self)
Return representation of the referent (or a fall-back if that fails)
Return representation of the referent (or a fall-back if that fails)
[ "Return", "representation", "of", "the", "referent", "(", "or", "a", "fall", "-", "back", "if", "that", "fails", ")" ]
def __str__(self): ''' Return representation of the referent (or a fall-back if that fails) ''' try: return self._callmethod('__repr__') except Exception: return repr(self)[:-1] + "; '__str__()' failed>"
[ "def", "__str__", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_callmethod", "(", "'__repr__'", ")", "except", "Exception", ":", "return", "repr", "(", "self", ")", "[", ":", "-", "1", "]", "+", "\"; '__str__()' failed>\"" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/multiprocessing/managers.py#L817-L824
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
CalculateLayoutEvent.SetRect
(*args, **kwargs)
return _windows_.CalculateLayoutEvent_SetRect(*args, **kwargs)
SetRect(self, Rect rect)
SetRect(self, Rect rect)
[ "SetRect", "(", "self", "Rect", "rect", ")" ]
def SetRect(*args, **kwargs): """SetRect(self, Rect rect)""" return _windows_.CalculateLayoutEvent_SetRect(*args, **kwargs)
[ "def", "SetRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "CalculateLayoutEvent_SetRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L2019-L2021
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/symtable.py
python
Symbol.is_namespace
(self)
return bool(self.__namespaces)
Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace.
Returns true if name binding introduces new namespace.
[ "Returns", "true", "if", "name", "binding", "introduces", "new", "namespace", "." ]
def is_namespace(self): """Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace. """ return bool(self.__namespaces)
[ "def", "is_namespace", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "__namespaces", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/symtable.py#L210-L221
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/lib/stepper.py
python
NodeStepper.last_updated
(self)
return self._last_updated
Get the names of the variables updated in the last cont() call. Returns: A set of the variable names updated in the previous cont() call. If no cont() call has occurred before, returns None.
Get the names of the variables updated in the last cont() call.
[ "Get", "the", "names", "of", "the", "variables", "updated", "in", "the", "last", "cont", "()", "call", "." ]
def last_updated(self): """Get the names of the variables updated in the last cont() call. Returns: A set of the variable names updated in the previous cont() call. If no cont() call has occurred before, returns None. """ return self._last_updated
[ "def", "last_updated", "(", "self", ")", ":", "return", "self", ".", "_last_updated" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/lib/stepper.py#L852-L860
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
setup.py
python
generate_singa_config
(with_cuda, with_nccl)
Generate singa_config.h file to define some macros for the cpp code. Args: with_cuda(bool): indicator for cudnn and cuda lib with_nccl(bool): indicator for nccl lib
Generate singa_config.h file to define some macros for the cpp code.
[ "Generate", "singa_config", ".", "h", "file", "to", "define", "some", "macros", "for", "the", "cpp", "code", "." ]
def generate_singa_config(with_cuda, with_nccl): '''Generate singa_config.h file to define some macros for the cpp code. Args: with_cuda(bool): indicator for cudnn and cuda lib with_nccl(bool): indicator for nccl lib ''' config = ['#define USE_CBLAS', '#define USE_GLOG', '#define USE_DNNL'] if not with_cuda: config.append('#define CPU_ONLY') else: config.append('#define USE_CUDA') config.append('#define USE_CUDNN') if with_nccl: config.append('#define ENABLE_DIST') config.append('#define USE_DIST') # singa_config.h to be included by cpp code cpp_conf_path = SINGA_HDR / 'singa/singa_config.h' print('Writing configs to {}'.format(cpp_conf_path)) with cpp_conf_path.open('w') as fd: for line in config: fd.write(line + '\n') versions = [int(x) for x in VERSION.split('+')[0].split('.')[:3]] fd.write('#define SINGA_MAJOR_VERSION {}\n'.format(versions[0])) fd.write('#define SINGA_MINOR_VERSION {}\n'.format(versions[1])) fd.write('#define SINGA_PATCH_VERSION {}\n'.format(versions[2])) fd.write('#define SINGA_VERSION "{}"\n'.format(VERSION)) # config.i to be included by swig files swig_conf_path = SINGA_SRC / 'api/config.i' with swig_conf_path.open('w') as fd: for line in config: fd.write(line + ' 1 \n') fd.write('#define USE_PYTHON 1\n') if not with_nccl: fd.write('#define USE_DIST 0\n') if not with_cuda: fd.write('#define USE_CUDA 0\n') fd.write('#define USE_CUDNN 0\n') else: fd.write('#define CUDNN_VERSION "{}"\n'.format( os.environ.get('CUDNN_VERSION'))) versions = [int(x) for x in VERSION.split('+')[0].split('.')[:3]] fd.write('#define SINGA_MAJOR_VERSION {}\n'.format(versions[0])) fd.write('#define SINGA_MINOR_VERSION {}\n'.format(versions[1])) fd.write('#define SINGA_PATCH_VERSION {}\n'.format(versions[2])) fd.write('#define SINGA_VERSION "{}"\n'.format(VERSION))
[ "def", "generate_singa_config", "(", "with_cuda", ",", "with_nccl", ")", ":", "config", "=", "[", "'#define USE_CBLAS'", ",", "'#define USE_GLOG'", ",", "'#define USE_DNNL'", "]", "if", "not", "with_cuda", ":", "config", ".", "append", "(", "'#define CPU_ONLY'", "...
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/setup.py#L140-L189
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/docs/parser.py
python
is_free_function
(py_object, full_name, index)
return True
Check if input is a free function (and not a class- or static method). Args: py_object: The the object in question. full_name: The full name of the object, like `tf.module.symbol`. index: The {full_name:py_object} dictionary for the public API. Returns: True if the obeject is a stand-alone function, and not part of a class definition.
Check if input is a free function (and not a class- or static method).
[ "Check", "if", "input", "is", "a", "free", "function", "(", "and", "not", "a", "class", "-", "or", "static", "method", ")", "." ]
def is_free_function(py_object, full_name, index): """Check if input is a free function (and not a class- or static method). Args: py_object: The the object in question. full_name: The full name of the object, like `tf.module.symbol`. index: The {full_name:py_object} dictionary for the public API. Returns: True if the obeject is a stand-alone function, and not part of a class definition. """ if not tf_inspect.isfunction(py_object): return False parent_name = full_name.rsplit('.', 1)[0] if tf_inspect.isclass(index[parent_name]): return False return True
[ "def", "is_free_function", "(", "py_object", ",", "full_name", ",", "index", ")", ":", "if", "not", "tf_inspect", ".", "isfunction", "(", "py_object", ")", ":", "return", "False", "parent_name", "=", "full_name", ".", "rsplit", "(", "'.'", ",", "1", ")", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/docs/parser.py#L38-L57
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/google/protobuf/message.py
python
Message.__getstate__
(self)
return dict(serialized=self.SerializePartialToString())
Support the pickle protocol.
Support the pickle protocol.
[ "Support", "the", "pickle", "protocol", "." ]
def __getstate__(self): """Support the pickle protocol.""" return dict(serialized=self.SerializePartialToString())
[ "def", "__getstate__", "(", "self", ")", ":", "return", "dict", "(", "serialized", "=", "self", ".", "SerializePartialToString", "(", ")", ")" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/message.py#L277-L279
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/operations/check.py
python
create_package_set_from_installed
(**kwargs)
return package_set, problems
Converts a list of distributions into a PackageSet.
Converts a list of distributions into a PackageSet.
[ "Converts", "a", "list", "of", "distributions", "into", "a", "PackageSet", "." ]
def create_package_set_from_installed(**kwargs): # type: (**Any) -> Tuple[PackageSet, bool] """Converts a list of distributions into a PackageSet. """ # Default to using all packages installed on the system if kwargs == {}: kwargs = {"local_only": False, "skip": ()} package_set = {} problems = False for dist in get_installed_distributions(**kwargs): name = canonicalize_name(dist.project_name) try: package_set[name] = PackageDetails(dist.version, dist.requires()) except (OSError, RequirementParseError) as e: # Don't crash on unreadable or broken metadata logger.warning("Error parsing requirements for %s: %s", name, e) problems = True return package_set, problems
[ "def", "create_package_set_from_installed", "(", "*", "*", "kwargs", ")", ":", "# type: (**Any) -> Tuple[PackageSet, bool]", "# Default to using all packages installed on the system", "if", "kwargs", "==", "{", "}", ":", "kwargs", "=", "{", "\"local_only\"", ":", "False", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/operations/check.py#L34-L52
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/boringssl/src/util/bot/extract.py
python
CheckedJoin
(output, path)
return os.path.join(output, path)
CheckedJoin returns os.path.join(output, path). It does sanity checks to ensure the resulting path is under output, but shouldn't be used on untrusted input.
CheckedJoin returns os.path.join(output, path). It does sanity checks to ensure the resulting path is under output, but shouldn't be used on untrusted input.
[ "CheckedJoin", "returns", "os", ".", "path", ".", "join", "(", "output", "path", ")", ".", "It", "does", "sanity", "checks", "to", "ensure", "the", "resulting", "path", "is", "under", "output", "but", "shouldn", "t", "be", "used", "on", "untrusted", "inp...
def CheckedJoin(output, path): """ CheckedJoin returns os.path.join(output, path). It does sanity checks to ensure the resulting path is under output, but shouldn't be used on untrusted input. """ path = os.path.normpath(path) if os.path.isabs(path) or path.startswith('.'): raise ValueError(path) return os.path.join(output, path)
[ "def", "CheckedJoin", "(", "output", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", "or", "path", ".", "startswith", "(", "'.'", ")", ":", "raise"...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/boringssl/src/util/bot/extract.py#L27-L36
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Config.set_library_file
(filename)
Set the exact location of libclang
Set the exact location of libclang
[ "Set", "the", "exact", "location", "of", "libclang" ]
def set_library_file(filename): """Set the exact location of libclang""" if Config.loaded: raise Exception("library file must be set before before using " \ "any other functionalities in libclang.") Config.library_file = filename
[ "def", "set_library_file", "(", "filename", ")", ":", "if", "Config", ".", "loaded", ":", "raise", "Exception", "(", "\"library file must be set before before using \"", "\"any other functionalities in libclang.\"", ")", "Config", ".", "library_file", "=", "filename" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L3335-L3341
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/fuchsia/device_target.py
python
DeviceTarget._GetSdkHash
(self)
return (version_info[product_key], version_info[version_key])
Read version of hash in pre-installed package directory. Returns: Tuple of (product, version) of image to be installed. Raises: VersionNotFoundError: if contents of buildargs.gn cannot be found or the version number cannot be extracted.
Read version of hash in pre-installed package directory. Returns: Tuple of (product, version) of image to be installed. Raises: VersionNotFoundError: if contents of buildargs.gn cannot be found or the version number cannot be extracted.
[ "Read", "version", "of", "hash", "in", "pre", "-", "installed", "package", "directory", ".", "Returns", ":", "Tuple", "of", "(", "product", "version", ")", "of", "image", "to", "be", "installed", ".", "Raises", ":", "VersionNotFoundError", ":", "if", "cont...
def _GetSdkHash(self): """Read version of hash in pre-installed package directory. Returns: Tuple of (product, version) of image to be installed. Raises: VersionNotFoundError: if contents of buildargs.gn cannot be found or the version number cannot be extracted. """ # TODO(crbug.com/1261961): Stop processing buildargs.gn directly. with open(os.path.join(self._system_image_dir, _BUILD_ARGS)) as f: contents = f.readlines() if not contents: raise VersionNotFoundError('Could not retrieve %s' % _BUILD_ARGS) version_key = 'build_info_version' product_key = 'build_info_product' info_keys = [product_key, version_key] version_info = {} for line in contents: for k in info_keys: match = re.match(r'%s = "(.*)"' % k, line) if match: version_info[k] = match.group(1) if not (version_key in version_info and product_key in version_info): raise VersionNotFoundError( 'Could not extract version info from %s. Contents: %s' % (_BUILD_ARGS, contents)) return (version_info[product_key], version_info[version_key])
[ "def", "_GetSdkHash", "(", "self", ")", ":", "# TODO(crbug.com/1261961): Stop processing buildargs.gn directly.", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_system_image_dir", ",", "_BUILD_ARGS", ")", ")", "as", "f", ":", "contents", ...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/device_target.py#L264-L292
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/integer-break.py
python
Solution2.integerBreak
(self, n)
return res[n % 4]
:type n: int :rtype: int
:type n: int :rtype: int
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int" ]
def integerBreak(self, n): """ :type n: int :rtype: int """ if n < 4: return n - 1 # integerBreak(n) = max(integerBreak(n - 2) * 2, integerBreak(n - 3) * 3) res = [0, 1, 2, 3] for i in xrange(4, n + 1): res[i % 4] = max(res[(i - 2) % 4] * 2, res[(i - 3) % 4] * 3) return res[n % 4]
[ "def", "integerBreak", "(", "self", ",", "n", ")", ":", "if", "n", "<", "4", ":", "return", "n", "-", "1", "# integerBreak(n) = max(integerBreak(n - 2) * 2, integerBreak(n - 3) * 3)", "res", "=", "[", "0", ",", "1", ",", "2", ",", "3", "]", "for", "i", "...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/integer-break.py#L50-L62
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py
python
IMAP4.deleteacl
(self, mailbox, who)
return self._simple_command('DELETEACL', mailbox, who)
Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who)
Delete the ACLs (remove any rights) set for who on mailbox.
[ "Delete", "the", "ACLs", "(", "remove", "any", "rights", ")", "set", "for", "who", "on", "mailbox", "." ]
def deleteacl(self, mailbox, who): """Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who) """ return self._simple_command('DELETEACL', mailbox, who)
[ "def", "deleteacl", "(", "self", ",", "mailbox", ",", "who", ")", ":", "return", "self", ".", "_simple_command", "(", "'DELETEACL'", ",", "mailbox", ",", "who", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L490-L495
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
src/icebox/icebox_py/__init__.py
python
Vm.resume
(self)
Resume vm.
Resume vm.
[ "Resume", "vm", "." ]
def resume(self): """Resume vm.""" libicebox.resume()
[ "def", "resume", "(", "self", ")", ":", "libicebox", ".", "resume", "(", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/src/icebox/icebox_py/__init__.py#L650-L652
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetAsmflags
(self, config)
return asmflags
Returns the flags that need to be added to ml invocations.
Returns the flags that need to be added to ml invocations.
[ "Returns", "the", "flags", "that", "need", "to", "be", "added", "to", "ml", "invocations", "." ]
def GetAsmflags(self, config): """Returns the flags that need to be added to ml invocations.""" config = self._TargetConfig(config) asmflags = [] safeseh = self._Setting(('MASM', 'UseSafeExceptionHandlers'), config) if safeseh == 'true': asmflags.append('/safeseh') return asmflags
[ "def", "GetAsmflags", "(", "self", ",", "config", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "asmflags", "=", "[", "]", "safeseh", "=", "self", ".", "_Setting", "(", "(", "'MASM'", ",", "'UseSafeExceptionHandlers'", ")", "...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L425-L432
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py
python
OrderedSet.__iter__
(self)
return iter(self.items)
Example: >>> list(iter(OrderedSet([1, 2, 3]))) [1, 2, 3]
Example: >>> list(iter(OrderedSet([1, 2, 3]))) [1, 2, 3]
[ "Example", ":", ">>>", "list", "(", "iter", "(", "OrderedSet", "(", "[", "1", "2", "3", "]", ")))", "[", "1", "2", "3", "]" ]
def __iter__(self): """ Example: >>> list(iter(OrderedSet([1, 2, 3]))) [1, 2, 3] """ return iter(self.items)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "items", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py#L259-L265
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/auto_bisect/bisect_perf_regression.py
python
BisectPerformanceMetrics._FindNextDepotToBisect
( self, current_depot, min_revision_state, max_revision_state)
return external_depot
Decides which depot the script should dive into next (if any). Args: current_depot: Current depot being bisected. min_revision_state: State of the earliest revision in the bisect range. max_revision_state: State of the latest revision in the bisect range. Returns: Name of the depot to bisect next, or None.
Decides which depot the script should dive into next (if any).
[ "Decides", "which", "depot", "the", "script", "should", "dive", "into", "next", "(", "if", "any", ")", "." ]
def _FindNextDepotToBisect( self, current_depot, min_revision_state, max_revision_state): """Decides which depot the script should dive into next (if any). Args: current_depot: Current depot being bisected. min_revision_state: State of the earliest revision in the bisect range. max_revision_state: State of the latest revision in the bisect range. Returns: Name of the depot to bisect next, or None. """ external_depot = None for next_depot in bisect_utils.DEPOT_NAMES: if ('platform' in bisect_utils.DEPOT_DEPS_NAME[next_depot] and bisect_utils.DEPOT_DEPS_NAME[next_depot]['platform'] != os.name): continue if not (bisect_utils.DEPOT_DEPS_NAME[next_depot]['recurse'] and min_revision_state.depot in bisect_utils.DEPOT_DEPS_NAME[next_depot]['from']): continue if current_depot == 'v8': # We grab the bleeding_edge info here rather than earlier because we # finally have the revision range. From that we can search forwards and # backwards to try to match trunk revisions to bleeding_edge. self._FillInV8BleedingEdgeInfo(min_revision_state, max_revision_state) if (min_revision_state.external.get(next_depot) == max_revision_state.external.get(next_depot)): continue if (min_revision_state.external.get(next_depot) and max_revision_state.external.get(next_depot)): external_depot = next_depot break return external_depot
[ "def", "_FindNextDepotToBisect", "(", "self", ",", "current_depot", ",", "min_revision_state", ",", "max_revision_state", ")", ":", "external_depot", "=", "None", "for", "next_depot", "in", "bisect_utils", ".", "DEPOT_NAMES", ":", "if", "(", "'platform'", "in", "b...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/bisect_perf_regression.py#L1784-L1822
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py
python
parse_bdist_wininst
(name)
return base, py_ver, plat
Return (base,pyversion) or (None,None) for possible .exe name
Return (base,pyversion) or (None,None) for possible .exe name
[ "Return", "(", "base", "pyversion", ")", "or", "(", "None", "None", ")", "for", "possible", ".", "exe", "name" ]
def parse_bdist_wininst(name): """Return (base,pyversion) or (None,None) for possible .exe name""" lower = name.lower() base, py_ver, plat = None, None, None if lower.endswith('.exe'): if lower.endswith('.win32.exe'): base = name[:-10] plat = 'win32' elif lower.startswith('.win32-py', -16): py_ver = name[-7:-4] base = name[:-16] plat = 'win32' elif lower.endswith('.win-amd64.exe'): base = name[:-14] plat = 'win-amd64' elif lower.startswith('.win-amd64-py', -20): py_ver = name[-7:-4] base = name[:-20] plat = 'win-amd64' return base, py_ver, plat
[ "def", "parse_bdist_wininst", "(", "name", ")", ":", "lower", "=", "name", ".", "lower", "(", ")", "base", ",", "py_ver", ",", "plat", "=", "None", ",", "None", ",", "None", "if", "lower", ".", "endswith", "(", "'.exe'", ")", ":", "if", "lower", "....
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/package_index.py#L62-L83
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchProfile.py
python
makeProfile
(profile=[0,'REC','REC100x100','R',100,100])
return obj
makeProfile(profile): returns a shape with the face defined by the profile data
makeProfile(profile): returns a shape with the face defined by the profile data
[ "makeProfile", "(", "profile", ")", ":", "returns", "a", "shape", "with", "the", "face", "defined", "by", "the", "profile", "data" ]
def makeProfile(profile=[0,'REC','REC100x100','R',100,100]): '''makeProfile(profile): returns a shape with the face defined by the profile data''' if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",profile[2]) obj.Label = profile[2] if profile[3]=="C": _ProfileC(obj, profile) elif profile[3]=="H": _ProfileH(obj, profile) elif profile[3]=="R": _ProfileR(obj, profile) elif profile[3]=="RH": _ProfileRH(obj, profile) elif profile[3]=="U": _ProfileU(obj, profile) else : print("Profile not supported") if FreeCAD.GuiUp: ViewProviderProfile(obj.ViewObject) return obj
[ "def", "makeProfile", "(", "profile", "=", "[", "0", ",", "'REC'", ",", "'REC100x100'", ",", "'R'", ",", "100", ",", "100", "]", ")", ":", "if", "not", "FreeCAD", ".", "ActiveDocument", ":", "FreeCAD", ".", "Console", ".", "PrintError", "(", "\"No acti...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchProfile.py#L85-L108
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/inspect.py
python
Parameter.replace
(self, *, name=_void, kind=_void, annotation=_void, default=_void)
return type(self)(name, kind, default=default, annotation=annotation)
Creates a customized copy of the Parameter.
Creates a customized copy of the Parameter.
[ "Creates", "a", "customized", "copy", "of", "the", "Parameter", "." ]
def replace(self, *, name=_void, kind=_void, annotation=_void, default=_void): """Creates a customized copy of the Parameter.""" if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default return type(self)(name, kind, default=default, annotation=annotation)
[ "def", "replace", "(", "self", ",", "*", ",", "name", "=", "_void", ",", "kind", "=", "_void", ",", "annotation", "=", "_void", ",", "default", "=", "_void", ")", ":", "if", "name", "is", "_void", ":", "name", "=", "self", ".", "_name", "if", "ki...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/inspect.py#L2533-L2549
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/py/py/_io/capture.py
python
FDCapture.__init__
(self, targetfd, tmpfile=None, now=True, patchsys=False)
save targetfd descriptor, and open a new temporary file there. If no tmpfile is specified a tempfile.Tempfile() will be opened in text mode.
save targetfd descriptor, and open a new temporary file there. If no tmpfile is specified a tempfile.Tempfile() will be opened in text mode.
[ "save", "targetfd", "descriptor", "and", "open", "a", "new", "temporary", "file", "there", ".", "If", "no", "tmpfile", "is", "specified", "a", "tempfile", ".", "Tempfile", "()", "will", "be", "opened", "in", "text", "mode", "." ]
def __init__(self, targetfd, tmpfile=None, now=True, patchsys=False): """ save targetfd descriptor, and open a new temporary file there. If no tmpfile is specified a tempfile.Tempfile() will be opened in text mode. """ self.targetfd = targetfd if tmpfile is None and targetfd != 0: f = tempfile.TemporaryFile('wb+') tmpfile = dupfile(f, encoding="UTF-8") f.close() self.tmpfile = tmpfile self._savefd = os.dup(self.targetfd) if patchsys: self._oldsys = getattr(sys, patchsysdict[targetfd]) if now: self.start()
[ "def", "__init__", "(", "self", ",", "targetfd", ",", "tmpfile", "=", "None", ",", "now", "=", "True", ",", "patchsys", "=", "False", ")", ":", "self", ".", "targetfd", "=", "targetfd", "if", "tmpfile", "is", "None", "and", "targetfd", "!=", "0", ":"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_io/capture.py#L34-L50
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/tensor_forest/python/ops/training_ops.py
python
_ScatterAddNdimShape
(unused_op)
return []
Shape function for ScatterAddNdim Op.
Shape function for ScatterAddNdim Op.
[ "Shape", "function", "for", "ScatterAddNdim", "Op", "." ]
def _ScatterAddNdimShape(unused_op): """Shape function for ScatterAddNdim Op.""" return []
[ "def", "_ScatterAddNdimShape", "(", "unused_op", ")", ":", "return", "[", "]" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/tensor_forest/python/ops/training_ops.py#L95-L97
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
external/marcopede-face-eval-f2870fd85d48/util.py
python
load
(filename)
return aux
load any python object
load any python object
[ "load", "any", "python", "object" ]
def load(filename): """ load any python object """ fd = open(filename, "r") aux = cPickle.load(fd) fd.close() return aux
[ "def", "load", "(", "filename", ")", ":", "fd", "=", "open", "(", "filename", ",", "\"r\"", ")", "aux", "=", "cPickle", ".", "load", "(", "fd", ")", "fd", ".", "close", "(", ")", "return", "aux" ]
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/external/marcopede-face-eval-f2870fd85d48/util.py#L43-L50
gaoxiang12/ORBSLAM2_with_pointcloud_map
cf94d66a9e4253abd66398c7ef461a7a903efffe
ORB_SLAM2_modified/Examples/ROS/ORB_SLAM2/build/devel/_setup_util.py
python
rollback_env_variables
(environ, env_var_subfolders)
return lines
Generate shell code to reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH. This does not cover modifications performed by environment hooks.
Generate shell code to reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH. This does not cover modifications performed by environment hooks.
[ "Generate", "shell", "code", "to", "reset", "environment", "variables", "by", "unrolling", "modifications", "based", "on", "all", "workspaces", "in", "CMAKE_PREFIX_PATH", ".", "This", "does", "not", "cover", "modifications", "performed", "by", "environment", "hooks"...
def rollback_env_variables(environ, env_var_subfolders): ''' Generate shell code to reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH. This does not cover modifications performed by environment hooks. ''' lines = [] unmodified_environ = copy.copy(environ) for key in sorted(env_var_subfolders.keys()): subfolders = env_var_subfolders[key] if not isinstance(subfolders, list): subfolders = [subfolders] value = _rollback_env_variable(unmodified_environ, key, subfolders) if value is not None: environ[key] = value lines.append(assignment(key, value)) if lines: lines.insert(0, comment('reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH')) return lines
[ "def", "rollback_env_variables", "(", "environ", ",", "env_var_subfolders", ")", ":", "lines", "=", "[", "]", "unmodified_environ", "=", "copy", ".", "copy", "(", "environ", ")", "for", "key", "in", "sorted", "(", "env_var_subfolders", ".", "keys", "(", ")",...
https://github.com/gaoxiang12/ORBSLAM2_with_pointcloud_map/blob/cf94d66a9e4253abd66398c7ef461a7a903efffe/ORB_SLAM2_modified/Examples/ROS/ORB_SLAM2/build/devel/_setup_util.py#L62-L80
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Tools/c_config.py
python
cxx_load_tools
(conf)
Loads the Waf c++ extensions
Loads the Waf c++ extensions
[ "Loads", "the", "Waf", "c", "++", "extensions" ]
def cxx_load_tools(conf): """ Loads the Waf c++ extensions """ if not conf.env.DEST_OS: conf.env.DEST_OS = Utils.unversioned_sys_platform() conf.load('cxx')
[ "def", "cxx_load_tools", "(", "conf", ")", ":", "if", "not", "conf", ".", "env", ".", "DEST_OS", ":", "conf", ".", "env", ".", "DEST_OS", "=", "Utils", ".", "unversioned_sys_platform", "(", ")", "conf", ".", "load", "(", "'cxx'", ")" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/c_config.py#L1010-L1016
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/index/package_finder.py
python
CandidateEvaluator._sort_key
(self, candidate)
return ( has_allowed_hash, yank_value, binary_preference, candidate.version, build_tag, pri, )
Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference. Returns a tuple such that tuples sorting as greater using Python's default comparison operator are more preferred. The preference is as follows: First and foremost, candidates with allowed (matching) hashes are always preferred over candidates without matching hashes. This is because e.g. if the only candidate with an allowed hash is yanked, we still want to use that candidate. Second, excepting hash considerations, candidates that have been yanked (in the sense of PEP 592) are always less preferred than candidates that haven't been yanked. Then: If not finding wheels, they are sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min(self._supported_tags) 3. source archives If prefer_binary was set, then all wheels are sorted above sources. Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal
Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference.
[ "Function", "to", "pass", "as", "the", "key", "argument", "to", "a", "call", "to", "sorted", "()", "to", "sort", "InstallationCandidates", "by", "preference", "." ]
def _sort_key(self, candidate): # type: (InstallationCandidate) -> CandidateSortingKey """ Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference. Returns a tuple such that tuples sorting as greater using Python's default comparison operator are more preferred. The preference is as follows: First and foremost, candidates with allowed (matching) hashes are always preferred over candidates without matching hashes. This is because e.g. if the only candidate with an allowed hash is yanked, we still want to use that candidate. Second, excepting hash considerations, candidates that have been yanked (in the sense of PEP 592) are always less preferred than candidates that haven't been yanked. Then: If not finding wheels, they are sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min(self._supported_tags) 3. source archives If prefer_binary was set, then all wheels are sorted above sources. Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal """ valid_tags = self._supported_tags support_num = len(valid_tags) build_tag = () # type: BuildTag binary_preference = 0 link = candidate.link if link.is_wheel: # can raise InvalidWheelFilename wheel = Wheel(link.filename) if not wheel.supported(valid_tags): raise UnsupportedWheel( "{} is not a supported wheel for this platform. It " "can't be sorted.".format(wheel.filename) ) if self._prefer_binary: binary_preference = 1 pri = -(wheel.support_index_min(valid_tags)) if wheel.build_tag is not None: match = re.match(r'^(\d+)(.*)$', wheel.build_tag) build_tag_groups = match.groups() build_tag = (int(build_tag_groups[0]), build_tag_groups[1]) else: # sdist pri = -(support_num) has_allowed_hash = int(link.is_hash_allowed(self._hashes)) yank_value = -1 * int(link.is_yanked) # -1 for yanked. return ( has_allowed_hash, yank_value, binary_preference, candidate.version, build_tag, pri, )
[ "def", "_sort_key", "(", "self", ",", "candidate", ")", ":", "# type: (InstallationCandidate) -> CandidateSortingKey", "valid_tags", "=", "self", ".", "_supported_tags", "support_num", "=", "len", "(", "valid_tags", ")", "build_tag", "=", "(", ")", "# type: BuildTag",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/index/package_finder.py#L482-L540
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/api.py
python
device_array
(shape, dtype=np.float, strides=None, order='C', stream=0)
return devicearray.DeviceNDArray(shape=shape, strides=strides, dtype=dtype, stream=stream)
device_array(shape, dtype=np.float, strides=None, order='C', stream=0) Allocate an empty device ndarray. Similar to :meth:`numpy.empty`.
device_array(shape, dtype=np.float, strides=None, order='C', stream=0)
[ "device_array", "(", "shape", "dtype", "=", "np", ".", "float", "strides", "=", "None", "order", "=", "C", "stream", "=", "0", ")" ]
def device_array(shape, dtype=np.float, strides=None, order='C', stream=0): """device_array(shape, dtype=np.float, strides=None, order='C', stream=0) Allocate an empty device ndarray. Similar to :meth:`numpy.empty`. """ shape, strides, dtype = _prepare_shape_strides_dtype(shape, strides, dtype, order) return devicearray.DeviceNDArray(shape=shape, strides=strides, dtype=dtype, stream=stream)
[ "def", "device_array", "(", "shape", ",", "dtype", "=", "np", ".", "float", ",", "strides", "=", "None", ",", "order", "=", "'C'", ",", "stream", "=", "0", ")", ":", "shape", ",", "strides", ",", "dtype", "=", "_prepare_shape_strides_dtype", "(", "shap...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/api.py#L119-L127
mysql/mysql-router
cc0179f982bb9739a834eb6fd205a56224616133
ext/gmock/scripts/gmock_doctor.py
python
_OverloadedFunctionActionDiagnoser
(msg)
return _GenericDiagnoser('OFA', 'Overloaded Function Action', [(gcc_regex, diagnosis), (clang_regex, diagnosis)], msg)
Diagnoses the OFA disease, given the error messages by the compiler.
Diagnoses the OFA disease, given the error messages by the compiler.
[ "Diagnoses", "the", "OFA", "disease", "given", "the", "error", "messages", "by", "the", "compiler", "." ]
def _OverloadedFunctionActionDiagnoser(msg): """Diagnoses the OFA disease, given the error messages by the compiler.""" gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to ' r'\'Invoke\(<unresolved overloaded function type>') clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching ' r'function for call to \'Invoke\'\r?\n' r'(.*\n)*?' r'.*\bgmock-\w+-actions\.h:\d+:\d+:\s+' r'note: candidate template ignored:\s+' r'couldn\'t infer template argument \'FunctionImpl\'') diagnosis = """ Function you are passing to Invoke is overloaded. Please tell your compiler which overloaded version you want to use. For example, if you want to use the version whose signature is bool MyFunction(int n, double x); you should write something like Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))""" return _GenericDiagnoser('OFA', 'Overloaded Function Action', [(gcc_regex, diagnosis), (clang_regex, diagnosis)], msg)
[ "def", "_OverloadedFunctionActionDiagnoser", "(", "msg", ")", ":", "gcc_regex", "=", "(", "_GCC_FILE_LINE_RE", "+", "r'error: no matching function for call to '", "r'\\'Invoke\\(<unresolved overloaded function type>'", ")", "clang_regex", "=", "(", "_CLANG_FILE_LINE_RE", "+", "...
https://github.com/mysql/mysql-router/blob/cc0179f982bb9739a834eb6fd205a56224616133/ext/gmock/scripts/gmock_doctor.py#L299-L321
vusec/vuzzer64
2b1b0ed757a3dca114db0192fa4ab1add92348bc
fuzzer-code/operators.py
python
GAoperator.double_full_mutate
(self,original,fl)
return self.change_random_full(result,fl)
This is called to do heavy mutation when no progress is made in previous generations.
This is called to do heavy mutation when no progress is made in previous generations.
[ "This", "is", "called", "to", "do", "heavy", "mutation", "when", "no", "progress", "is", "made", "in", "previous", "generations", "." ]
def double_full_mutate(self,original,fl): ''' This is called to do heavy mutation when no progress is made in previous generations. ''' result = self.change_random_full(original,fl) return self.change_random_full(result,fl)
[ "def", "double_full_mutate", "(", "self", ",", "original", ",", "fl", ")", ":", "result", "=", "self", ".", "change_random_full", "(", "original", ",", "fl", ")", "return", "self", ".", "change_random_full", "(", "result", ",", "fl", ")" ]
https://github.com/vusec/vuzzer64/blob/2b1b0ed757a3dca114db0192fa4ab1add92348bc/fuzzer-code/operators.py#L260-L263
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/Chem/GraphDescriptors.py
python
_pyChi0v
(mol)
return res
From equations (5),(9) and (10) of Rev. Comp. Chem. vol 2, 367-422, (1991)
From equations (5),(9) and (10) of Rev. Comp. Chem. vol 2, 367-422, (1991)
[ "From", "equations", "(", "5", ")", "(", "9", ")", "and", "(", "10", ")", "of", "Rev", ".", "Comp", ".", "Chem", ".", "vol", "2", "367", "-", "422", "(", "1991", ")" ]
def _pyChi0v(mol): """ From equations (5),(9) and (10) of Rev. Comp. Chem. vol 2, 367-422, (1991) """ deltas = _hkDeltas(mol) while 0 in deltas: deltas.remove(0) mol._hkDeltas = None res = sum(numpy.sqrt(1. / numpy.array(deltas))) return res
[ "def", "_pyChi0v", "(", "mol", ")", ":", "deltas", "=", "_hkDeltas", "(", "mol", ")", "while", "0", "in", "deltas", ":", "deltas", ".", "remove", "(", "0", ")", "mol", ".", "_hkDeltas", "=", "None", "res", "=", "sum", "(", "numpy", ".", "sqrt", "...
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/GraphDescriptors.py#L259-L268
nnrg/opennero
43e12a1bcba6e228639db3886fec1dc47ddc24cb
mods/Maze/environment.py
python
MazeEnvironment.mark_maze_agent
(self, agent, r1, c1, r2, c2)
mark a maze cell with an agent moving from r1, c1 to r2, c2
mark a maze cell with an agent moving from r1, c1 to r2, c2
[ "mark", "a", "maze", "cell", "with", "an", "agent", "moving", "from", "r1", "c1", "to", "r2", "c2" ]
def mark_maze_agent(self, agent, r1, c1, r2, c2): """ mark a maze cell with an agent moving from r1, c1 to r2, c2 """ # remove the previous object, if necessary self.unmark_maze_agent(r2,c2) # add a new marker object position = Vector3f( (r1+1) * GRID_DX, (c1+1) * GRID_DY, 0) rotation = self.get_next_rotation( (r2-r1, c2-c1) ) agent_id = addObject(agent, position = position, rotation = rotation) self.marker_states[agent_id] = ((r1, c1), (r2, c2)) self.agent_map[(r2,c2)] = agent_id
[ "def", "mark_maze_agent", "(", "self", ",", "agent", ",", "r1", ",", "c1", ",", "r2", ",", "c2", ")", ":", "# remove the previous object, if necessary", "self", ".", "unmark_maze_agent", "(", "r2", ",", "c2", ")", "# add a new marker object", "position", "=", ...
https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Maze/environment.py#L328-L337
DaFuCoding/MTCNN_Caffe
09c30c3ff391bd9cb6b249c1910afaf147767ab3
python/caffe/coord_map.py
python
crop
(top_from, top_to)
return L.Crop(top_from, top_to, crop_param=dict(axis=ax + 1, # +1 for first cropping dim. offset=list(-np.round(b).astype(int))))
Define a Crop layer to crop a top (from) to another top (to) by determining the coordinate mapping between the two and net spec'ing the axis and shift parameters of the crop.
Define a Crop layer to crop a top (from) to another top (to) by determining the coordinate mapping between the two and net spec'ing the axis and shift parameters of the crop.
[ "Define", "a", "Crop", "layer", "to", "crop", "a", "top", "(", "from", ")", "to", "another", "top", "(", "to", ")", "by", "determining", "the", "coordinate", "mapping", "between", "the", "two", "and", "net", "spec", "ing", "the", "axis", "and", "shift"...
def crop(top_from, top_to): """ Define a Crop layer to crop a top (from) to another top (to) by determining the coordinate mapping between the two and net spec'ing the axis and shift parameters of the crop. """ ax, a, b = coord_map_from_to(top_from, top_to) assert (a == 1).all(), 'scale mismatch on crop (a = {})'.format(a) assert (b <= 0).all(), 'cannot crop negative offset (b = {})'.format(b) assert (np.round(b) == b).all(), 'cannot crop noninteger offset ' \ '(b = {})'.format(b) return L.Crop(top_from, top_to, crop_param=dict(axis=ax + 1, # +1 for first cropping dim. offset=list(-np.round(b).astype(int))))
[ "def", "crop", "(", "top_from", ",", "top_to", ")", ":", "ax", ",", "a", ",", "b", "=", "coord_map_from_to", "(", "top_from", ",", "top_to", ")", "assert", "(", "a", "==", "1", ")", ".", "all", "(", ")", ",", "'scale mismatch on crop (a = {})'", ".", ...
https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/python/caffe/coord_map.py#L172-L185
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/motionplanning.py
python
CSpaceInterface.setSampler
(self, pySamp)
return _motionplanning.CSpaceInterface_setSampler(self, pySamp)
setSampler(CSpaceInterface self, PyObject * pySamp)
setSampler(CSpaceInterface self, PyObject * pySamp)
[ "setSampler", "(", "CSpaceInterface", "self", "PyObject", "*", "pySamp", ")" ]
def setSampler(self, pySamp): """ setSampler(CSpaceInterface self, PyObject * pySamp) """ return _motionplanning.CSpaceInterface_setSampler(self, pySamp)
[ "def", "setSampler", "(", "self", ",", "pySamp", ")", ":", "return", "_motionplanning", ".", "CSpaceInterface_setSampler", "(", "self", ",", "pySamp", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L386-L393
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
ConfigBase.GetNextEntry
(*args, **kwargs)
return _misc_.ConfigBase_GetNextEntry(*args, **kwargs)
GetNextEntry(long index) -> (more, value, index) Allows enumerating the entries in the current group in a config object. Returns a tuple containing a flag indicating there are more items, the name of the current item, and an index to pass to GetNextGroup to fetch the next item.
GetNextEntry(long index) -> (more, value, index)
[ "GetNextEntry", "(", "long", "index", ")", "-", ">", "(", "more", "value", "index", ")" ]
def GetNextEntry(*args, **kwargs): """ GetNextEntry(long index) -> (more, value, index) Allows enumerating the entries in the current group in a config object. Returns a tuple containing a flag indicating there are more items, the name of the current item, and an index to pass to GetNextGroup to fetch the next item. """ return _misc_.ConfigBase_GetNextEntry(*args, **kwargs)
[ "def", "GetNextEntry", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_GetNextEntry", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3194-L3203
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py
python
FieldMask.AllFieldsFromDescriptor
(self, message_descriptor)
Gets all direct fields of Message Descriptor to FieldMask.
Gets all direct fields of Message Descriptor to FieldMask.
[ "Gets", "all", "direct", "fields", "of", "Message", "Descriptor", "to", "FieldMask", "." ]
def AllFieldsFromDescriptor(self, message_descriptor): """Gets all direct fields of Message Descriptor to FieldMask.""" self.Clear() for field in message_descriptor.fields: self.paths.append(field.name)
[ "def", "AllFieldsFromDescriptor", "(", "self", ",", "message_descriptor", ")", ":", "self", ".", "Clear", "(", ")", "for", "field", "in", "message_descriptor", ".", "fields", ":", "self", ".", "paths", ".", "append", "(", "field", ".", "name", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py#L397-L401
nnrg/opennero
43e12a1bcba6e228639db3886fec1dc47ddc24cb
mods/Roomba/module.py
python
furniture
(x,y)
return (constants.XDIM * x, constants.YDIM * (1-y))
convert from furniture space to roomba space
convert from furniture space to roomba space
[ "convert", "from", "furniture", "space", "to", "roomba", "space" ]
def furniture(x,y): """ convert from furniture space to roomba space """ return (constants.XDIM * x, constants.YDIM * (1-y))
[ "def", "furniture", "(", "x", ",", "y", ")", ":", "return", "(", "constants", ".", "XDIM", "*", "x", ",", "constants", ".", "YDIM", "*", "(", "1", "-", "y", ")", ")" ]
https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Roomba/module.py#L158-L162
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/katana/WalterIn/walterUSDExtern.py
python
WalterUSDExtern.getPrimsCount
(self)
return WALTER_IN_SO.WalterUSDExtern_getPrimsCount(self.obj)
Gets the number of USD primitives.
Gets the number of USD primitives.
[ "Gets", "the", "number", "of", "USD", "primitives", "." ]
def getPrimsCount(self): WALTER_IN_SO.WalterUSDExtern_getPrimsCount.restype = c_int WALTER_IN_SO.WalterUSDExtern_getPrimsCount.argtypes = [c_void_p] """Gets the number of USD primitives.""" return WALTER_IN_SO.WalterUSDExtern_getPrimsCount(self.obj)
[ "def", "getPrimsCount", "(", "self", ")", ":", "WALTER_IN_SO", ".", "WalterUSDExtern_getPrimsCount", ".", "restype", "=", "c_int", "WALTER_IN_SO", ".", "WalterUSDExtern_getPrimsCount", ".", "argtypes", "=", "[", "c_void_p", "]", "return", "WALTER_IN_SO", ".", "Walte...
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/katana/WalterIn/walterUSDExtern.py#L65-L69
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/symbol/symbol.py
python
Symbol._compose
(self, *args, **kwargs)
Composes symbol using inputs. x._compose(y, z) <=> x(y,z) This function mutates the current symbol. Example ------- >>> data = mx.symbol.Variable('data') >>> net1 = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10) >>> net2 = mx.symbol.FullyConnected(name='fc3', num_hidden=10) >>> net2 <Symbol fc3> >>> net2._compose(fc3_data=net1, name='composed') >>> net2 <Symbol composed> Parameters ---------- args: Positional arguments. kwargs: Keyword arguments. Returns ------- The resulting symbol.
Composes symbol using inputs.
[ "Composes", "symbol", "using", "inputs", "." ]
def _compose(self, *args, **kwargs): """Composes symbol using inputs. x._compose(y, z) <=> x(y,z) This function mutates the current symbol. Example ------- >>> data = mx.symbol.Variable('data') >>> net1 = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10) >>> net2 = mx.symbol.FullyConnected(name='fc3', num_hidden=10) >>> net2 <Symbol fc3> >>> net2._compose(fc3_data=net1, name='composed') >>> net2 <Symbol composed> Parameters ---------- args: Positional arguments. kwargs: Keyword arguments. Returns ------- The resulting symbol. """ name = kwargs.pop('name', None) if name: name = c_str(name) if len(args) != 0 and len(kwargs) != 0: raise TypeError('compose only accept input Symbols \ either as positional or keyword arguments, not both') for arg in args: if not isinstance(arg, Symbol): raise TypeError('Compose expect `Symbol` as arguments') for val in kwargs.values(): if not isinstance(val, Symbol): raise TypeError('Compose expect `Symbol` as arguments') num_args = len(args) + len(kwargs) if len(kwargs) != 0: keys = c_str_array(kwargs.keys()) args = c_handle_array(kwargs.values()) else: keys = None args = c_handle_array(args) check_call(_LIB.MXSymbolCompose( self.handle, name, num_args, keys, args))
[ "def", "_compose", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ",", "None", ")", "if", "name", ":", "name", "=", "c_str", "(", "name", ")", "if", "len", "(", "args", ")", ...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/symbol.py#L420-L473
Tencent/TNN
7acca99f54c55747b415a4c57677403eebc7b706
third_party/flatbuffers/python/flatbuffers/flexbuffers.py
python
Builder._WriteScalarVector
(self, element_type, byte_width, elements, fixed)
return loc
Writes scalar vector elements to the underlying buffer.
Writes scalar vector elements to the underlying buffer.
[ "Writes", "scalar", "vector", "elements", "to", "the", "underlying", "buffer", "." ]
def _WriteScalarVector(self, element_type, byte_width, elements, fixed): """Writes scalar vector elements to the underlying buffer.""" bit_width = BitWidth.B(byte_width) # If you get this exception, you're trying to write a vector with a size # field that is bigger than the scalars you're trying to write (e.g. a # byte vector > 255 elements). For such types, write a "blob" instead. if BitWidth.U(len(elements)) > bit_width: raise ValueError('too many elements for the given byte_width') self._Align(bit_width) if not fixed: self._Write(U, len(elements), byte_width) loc = len(self._buf) fmt = {Type.INT: I, Type.UINT: U, Type.FLOAT: F}.get(element_type) if not fmt: raise TypeError('unsupported element_type') self._WriteVector(fmt, elements, byte_width) type_ = Type.ToTypedVector(element_type, len(elements) if fixed else 0) self._stack.append(Value(loc, type_, bit_width)) return loc
[ "def", "_WriteScalarVector", "(", "self", ",", "element_type", ",", "byte_width", ",", "elements", ",", "fixed", ")", ":", "bit_width", "=", "BitWidth", ".", "B", "(", "byte_width", ")", "# If you get this exception, you're trying to write a vector with a size", "# fiel...
https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/flexbuffers.py#L1066-L1088
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/_vendor/six.py
python
add_metaclass
(metaclass)
return wrapper
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
[ "Class", "decorator", "for", "creating", "a", "class", "with", "a", "metaclass", "." ]
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "slots", "=", "orig_vars", ".", "get", "(", "'__slots__'", ")", "if", "slots", "is", "not", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/six.py#L812-L825
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/plasma/PlasmaTypes.py
python
PtFindAvatar
(events)
return None
Find the avatar in one of the event records
Find the avatar in one of the event records
[ "Find", "the", "avatar", "in", "one", "of", "the", "event", "records" ]
def PtFindAvatar(events): "Find the avatar in one of the event records" for event in events: if event[0]==kCollisionEvent or event[0]==kPickedEvent or event[0]==kFacingEvent or event[0]==kContainedEvent or event[0]==kSpawnedEvent: return event[2] if event[0] == kMultiStageEvent: return event[3] # didn't find one return None
[ "def", "PtFindAvatar", "(", "events", ")", ":", "for", "event", "in", "events", ":", "if", "event", "[", "0", "]", "==", "kCollisionEvent", "or", "event", "[", "0", "]", "==", "kPickedEvent", "or", "event", "[", "0", "]", "==", "kFacingEvent", "or", ...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/PlasmaTypes.py#L209-L217
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py
python
_preprocess_conv3d_input
(x, data_format)
return x, tf_data_format
Transpose and cast the input before the conv3d. Arguments: x: input tensor. data_format: string, `"channels_last"` or `"channels_first"`. Returns: A tensor.
Transpose and cast the input before the conv3d.
[ "Transpose", "and", "cast", "the", "input", "before", "the", "conv3d", "." ]
def _preprocess_conv3d_input(x, data_format): """Transpose and cast the input before the conv3d. Arguments: x: input tensor. data_format: string, `"channels_last"` or `"channels_first"`. Returns: A tensor. """ tf_data_format = 'NDHWC' if data_format == 'channels_first': if not _has_nchw_support(): x = array_ops.transpose(x, (0, 2, 3, 4, 1)) else: tf_data_format = 'NCDHW' return x, tf_data_format
[ "def", "_preprocess_conv3d_input", "(", "x", ",", "data_format", ")", ":", "tf_data_format", "=", "'NDHWC'", "if", "data_format", "==", "'channels_first'", ":", "if", "not", "_has_nchw_support", "(", ")", ":", "x", "=", "array_ops", ".", "transpose", "(", "x",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L4631-L4647
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py
python
IMAP4.sort
(self, sort_criteria, charset, *search_criteria)
return self._untagged_response(typ, dat, name)
IMAP4rev1 extension SORT command. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
IMAP4rev1 extension SORT command.
[ "IMAP4rev1", "extension", "SORT", "command", "." ]
def sort(self, sort_criteria, charset, *search_criteria): """IMAP4rev1 extension SORT command. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...) """ name = 'SORT' #if not name in self.capabilities: # Let the server decide! # raise self.error('unimplemented extension command: %s' % name) if (sort_criteria[0],sort_criteria[-1]) != ('(',')'): sort_criteria = '(%s)' % sort_criteria typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria) return self._untagged_response(typ, dat, name)
[ "def", "sort", "(", "self", ",", "sort_criteria", ",", "charset", ",", "*", "search_criteria", ")", ":", "name", "=", "'SORT'", "#if not name in self.capabilities: # Let the server decide!", "# raise self.error('unimplemented extension command: %s' % name)", "if", "(...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py#L688-L699
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/chebyshev.py
python
_zseries_mul
(z1, z2)
return np.convolve(z1, z2)
Multiply two z-series. Multiply two z-series to produce a z-series. Parameters ---------- z1, z2 : 1-D ndarray The arrays must be 1-D but this is not checked. Returns ------- product : 1-D ndarray The product z-series. Notes ----- This is simply convolution. If symmetric/anti-symmetric z-series are denoted by S/A then the following rules apply: S*S, A*A -> S S*A, A*S -> A
Multiply two z-series.
[ "Multiply", "two", "z", "-", "series", "." ]
def _zseries_mul(z1, z2) : """Multiply two z-series. Multiply two z-series to produce a z-series. Parameters ---------- z1, z2 : 1-D ndarray The arrays must be 1-D but this is not checked. Returns ------- product : 1-D ndarray The product z-series. Notes ----- This is simply convolution. If symmetric/anti-symmetric z-series are denoted by S/A then the following rules apply: S*S, A*A -> S S*A, A*S -> A """ return np.convolve(z1, z2)
[ "def", "_zseries_mul", "(", "z1", ",", "z2", ")", ":", "return", "np", ".", "convolve", "(", "z1", ",", "z2", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/chebyshev.py#L161-L185
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/mavlink_px4.py
python
MAVLink.hil_rc_inputs_raw_send
(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi)
return self.send(self.hil_rc_inputs_raw_encode(time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi))
Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) chan1_raw : RC channel 1 value, in microseconds (uint16_t) chan2_raw : RC channel 2 value, in microseconds (uint16_t) chan3_raw : RC channel 3 value, in microseconds (uint16_t) chan4_raw : RC channel 4 value, in microseconds (uint16_t) chan5_raw : RC channel 5 value, in microseconds (uint16_t) chan6_raw : RC channel 6 value, in microseconds (uint16_t) chan7_raw : RC channel 7 value, in microseconds (uint16_t) chan8_raw : RC channel 8 value, in microseconds (uint16_t) chan9_raw : RC channel 9 value, in microseconds (uint16_t) chan10_raw : RC channel 10 value, in microseconds (uint16_t) chan11_raw : RC channel 11 value, in microseconds (uint16_t) chan12_raw : RC channel 12 value, in microseconds (uint16_t) rssi : Receive signal strength indicator, 0: 0%, 255: 100% (uint8_t)
Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification.
[ "Sent", "from", "simulation", "to", "autopilot", ".", "The", "RAW", "values", "of", "the", "RC", "channels", "received", ".", "The", "standard", "PPM", "modulation", "is", "as", "follows", ":", "1000", "microseconds", ":", "0%", "2000", "microseconds", ":", ...
def hil_rc_inputs_raw_send(self, time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi): ''' Sent from simulation to autopilot. The RAW values of the RC channels received. The standard PPM modulation is as follows: 1000 microseconds: 0%, 2000 microseconds: 100%. Individual receivers/transmitters might violate this specification. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) chan1_raw : RC channel 1 value, in microseconds (uint16_t) chan2_raw : RC channel 2 value, in microseconds (uint16_t) chan3_raw : RC channel 3 value, in microseconds (uint16_t) chan4_raw : RC channel 4 value, in microseconds (uint16_t) chan5_raw : RC channel 5 value, in microseconds (uint16_t) chan6_raw : RC channel 6 value, in microseconds (uint16_t) chan7_raw : RC channel 7 value, in microseconds (uint16_t) chan8_raw : RC channel 8 value, in microseconds (uint16_t) chan9_raw : RC channel 9 value, in microseconds (uint16_t) chan10_raw : RC channel 10 value, in microseconds (uint16_t) chan11_raw : RC channel 11 value, in microseconds (uint16_t) chan12_raw : RC channel 12 value, in microseconds (uint16_t) rssi : Receive signal strength indicator, 0: 0%, 255: 100% (uint8_t) ''' return self.send(self.hil_rc_inputs_raw_encode(time_usec, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, chan9_raw, chan10_raw, chan11_raw, chan12_raw, rssi))
[ "def", "hil_rc_inputs_raw_send", "(", "self", ",", "time_usec", ",", "chan1_raw", ",", "chan2_raw", ",", "chan3_raw", ",", "chan4_raw", ",", "chan5_raw", ",", "chan6_raw", ",", "chan7_raw", ",", "chan8_raw", ",", "chan9_raw", ",", "chan10_raw", ",", "chan11_raw"...
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L4683-L4707
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/AbstractVisitor.py
python
AbstractVisitor.DictStartVisit
(self, obj)
Defined to generate start of command Python class.
Defined to generate start of command Python class.
[ "Defined", "to", "generate", "start", "of", "command", "Python", "class", "." ]
def DictStartVisit(self, obj): """ Defined to generate start of command Python class. """ raise Exception( "# DictStartVisit.startCommandVisit() - Implementation Error: you must supply your own concrete implementation." )
[ "def", "DictStartVisit", "(", "self", ",", "obj", ")", ":", "raise", "Exception", "(", "\"# DictStartVisit.startCommandVisit() - Implementation Error: you must supply your own concrete implementation.\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/AbstractVisitor.py#L147-L153
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Platform/posix.py
python
escape
(arg)
return '"' + arg + '"'
escape shell special characters
escape shell special characters
[ "escape", "shell", "special", "characters" ]
def escape(arg): """escape shell special characters""" slash = '\\' special = '"$' arg = arg.replace(slash, slash+slash) for c in special: arg = arg.replace(c, slash+c) # print("ESCAPE RESULT: %s" % arg) return '"' + arg + '"'
[ "def", "escape", "(", "arg", ")", ":", "slash", "=", "'\\\\'", "special", "=", "'\"$'", "arg", "=", "arg", ".", "replace", "(", "slash", ",", "slash", "+", "slash", ")", "for", "c", "in", "special", ":", "arg", "=", "arg", ".", "replace", "(", "c...
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Platform/posix.py#L45-L55
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
FileType.GetOpenCommand
(*args, **kwargs)
return _misc_.FileType_GetOpenCommand(*args, **kwargs)
GetOpenCommand(self, String filename, String mimetype=EmptyString) -> PyObject
GetOpenCommand(self, String filename, String mimetype=EmptyString) -> PyObject
[ "GetOpenCommand", "(", "self", "String", "filename", "String", "mimetype", "=", "EmptyString", ")", "-", ">", "PyObject" ]
def GetOpenCommand(*args, **kwargs): """GetOpenCommand(self, String filename, String mimetype=EmptyString) -> PyObject""" return _misc_.FileType_GetOpenCommand(*args, **kwargs)
[ "def", "GetOpenCommand", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "FileType_GetOpenCommand", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2605-L2607
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/rev3/rev3_api.py
python
Videos.getVideoID
(self, link)
return videoID
Read the Web page to find the video ID number used for fullscreen autoplay return the video ID number return None if the number cannot be found
Read the Web page to find the video ID number used for fullscreen autoplay return the video ID number return None if the number cannot be found
[ "Read", "the", "Web", "page", "to", "find", "the", "video", "ID", "number", "used", "for", "fullscreen", "autoplay", "return", "the", "video", "ID", "number", "return", "None", "if", "the", "number", "cannot", "be", "found" ]
def getVideoID(self, link): ''' Read the Web page to find the video ID number used for fullscreen autoplay return the video ID number return None if the number cannot be found ''' videoID = None try: eTree = etree.parse(link, self.FullScreenParser) except Exception as errormsg: sys.stderr.write("! Error: The URL (%s) cause the exception error (%s)\n" % (link, errormsg)) return videoID if self.config['debug_enabled']: print("Raw unfiltered URL imput:") sys.stdout.write(etree.tostring(eTree, encoding='UTF-8', pretty_print=True)) print() if not eTree: return videoID # Filter out the video id try: tmpVideoID = self.FullScreenVidIDxPath(eTree) except AssertionError as e: sys.stderr.write("No filter results for VideoID from url(%s)\n" % link) sys.stderr.write("! Error:(%s)\n" % e) return videoID if len(tmpVideoID): if tmpVideoID[0].get('id'): videoID = tmpVideoID[0].attrib['id'].strip().replace('player-', '') return videoID
[ "def", "getVideoID", "(", "self", ",", "link", ")", ":", "videoID", "=", "None", "try", ":", "eTree", "=", "etree", ".", "parse", "(", "link", ",", "self", ".", "FullScreenParser", ")", "except", "Exception", "as", "errormsg", ":", "sys", ".", "stderr"...
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/rev3/rev3_api.py#L457-L489
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/Sophus/py/sophus/so2.py
python
So2.matrix
(self)
return sympy.Matrix([ [self.z.real, -self.z.imag], [self.z.imag, self.z.real]])
returns matrix representation
returns matrix representation
[ "returns", "matrix", "representation" ]
def matrix(self): """ returns matrix representation """ return sympy.Matrix([ [self.z.real, -self.z.imag], [self.z.imag, self.z.real]])
[ "def", "matrix", "(", "self", ")", ":", "return", "sympy", ".", "Matrix", "(", "[", "[", "self", ".", "z", ".", "real", ",", "-", "self", ".", "z", ".", "imag", "]", ",", "[", "self", ".", "z", ".", "imag", ",", "self", ".", "z", ".", "real...
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/Sophus/py/sophus/so2.py#L35-L39
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/grid.py
python
GridTableMessage.SetCommandInt2
(*args, **kwargs)
return _grid.GridTableMessage_SetCommandInt2(*args, **kwargs)
SetCommandInt2(self, int comInt2)
SetCommandInt2(self, int comInt2)
[ "SetCommandInt2", "(", "self", "int", "comInt2", ")" ]
def SetCommandInt2(*args, **kwargs): """SetCommandInt2(self, int comInt2)""" return _grid.GridTableMessage_SetCommandInt2(*args, **kwargs)
[ "def", "SetCommandInt2", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridTableMessage_SetCommandInt2", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1099-L1101
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/bindings/python/MythTV/dataheap.py
python
Job.setStatus
(self,status)
Job.setStatus(Status) -> None, updates status
Job.setStatus(Status) -> None, updates status
[ "Job", ".", "setStatus", "(", "Status", ")", "-", ">", "None", "updates", "status" ]
def setStatus(self,status): """Job.setStatus(Status) -> None, updates status""" self.status = status self.update()
[ "def", "setStatus", "(", "self", ",", "status", ")", ":", "self", ".", "status", "=", "status", "self", ".", "update", "(", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/dataheap.py#L712-L715
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
linked_list/is_palindrome.py
python
Node.__init__
(self, data)
initializing single node with data
initializing single node with data
[ "initializing", "single", "node", "with", "data" ]
def __init__(self, data): """ initializing single node with data """ self.data = data self.next = None
[ "def", "__init__", "(", "self", ",", "data", ")", ":", "self", ".", "data", "=", "data", "self", ".", "next", "=", "None" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/is_palindrome.py#L6-L9
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py
python
Cursor.is_anonymous
(self)
return conf.lib.clang_Cursor_isAnonymous(self)
Check if the record is anonymous.
Check if the record is anonymous.
[ "Check", "if", "the", "record", "is", "anonymous", "." ]
def is_anonymous(self): """ Check if the record is anonymous. """ if self.kind == CursorKind.FIELD_DECL: return self.type.get_declaration().is_anonymous() return conf.lib.clang_Cursor_isAnonymous(self)
[ "def", "is_anonymous", "(", "self", ")", ":", "if", "self", ".", "kind", "==", "CursorKind", ".", "FIELD_DECL", ":", "return", "self", ".", "type", ".", "get_declaration", "(", ")", ".", "is_anonymous", "(", ")", "return", "conf", ".", "lib", ".", "cla...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L1714-L1720
3drobotics/ardupilot-solo
05a123b002c11dccc905d4d7703a38e5f36ee723
mk/PX4/Tools/gencpp/src/gencpp/__init__.py
python
msg_type_to_cpp
(type)
Converts a message type (e.g. uint32, std_msgs/String, etc.) into the C++ declaration for that type (e.g. uint32_t, std_msgs::String_<ContainerAllocator>) @param type: The message type @type type: str @return: The C++ declaration @rtype: str
Converts a message type (e.g. uint32, std_msgs/String, etc.) into the C++ declaration for that type (e.g. uint32_t, std_msgs::String_<ContainerAllocator>)
[ "Converts", "a", "message", "type", "(", "e", ".", "g", ".", "uint32", "std_msgs", "/", "String", "etc", ".", ")", "into", "the", "C", "++", "declaration", "for", "that", "type", "(", "e", ".", "g", ".", "uint32_t", "std_msgs", "::", "String_<Container...
def msg_type_to_cpp(type): """ Converts a message type (e.g. uint32, std_msgs/String, etc.) into the C++ declaration for that type (e.g. uint32_t, std_msgs::String_<ContainerAllocator>) @param type: The message type @type type: str @return: The C++ declaration @rtype: str """ (base_type, is_array, array_len) = genmsg.msgs.parse_type(type) cpp_type = None if (genmsg.msgs.is_builtin(base_type)): cpp_type = MSG_TYPE_TO_CPP[base_type] elif (len(base_type.split('/')) == 1): if (genmsg.msgs.is_header_type(base_type)): cpp_type = ' ::std_msgs::Header_<ContainerAllocator> ' else: cpp_type = '%s_<ContainerAllocator> '%(base_type) else: pkg = base_type.split('/')[0] msg = base_type.split('/')[1] cpp_type = ' ::%s::%s_<ContainerAllocator> '%(pkg, msg) if (is_array): if (array_len is None): return 'std::vector<%s, typename ContainerAllocator::template rebind<%s>::other > '%(cpp_type, cpp_type) else: return 'boost::array<%s, %s> '%(cpp_type, array_len) else: return cpp_type
[ "def", "msg_type_to_cpp", "(", "type", ")", ":", "(", "base_type", ",", "is_array", ",", "array_len", ")", "=", "genmsg", ".", "msgs", ".", "parse_type", "(", "type", ")", "cpp_type", "=", "None", "if", "(", "genmsg", ".", "msgs", ".", "is_builtin", "(...
https://github.com/3drobotics/ardupilot-solo/blob/05a123b002c11dccc905d4d7703a38e5f36ee723/mk/PX4/Tools/gencpp/src/gencpp/__init__.py#L58-L88
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_stc.py
python
EditraStc.StopRecord
(self)
Stops the recording and builds the macro script @postcondition: macro recording is stopped
Stops the recording and builds the macro script @postcondition: macro recording is stopped
[ "Stops", "the", "recording", "and", "builds", "the", "macro", "script", "@postcondition", ":", "macro", "recording", "is", "stopped" ]
def StopRecord(self): # pylint: disable-msg=W0221 """Stops the recording and builds the macro script @postcondition: macro recording is stopped """ self.recording = False super(EditraStc, self).StopRecord() evt = ed_event.StatusEvent(ed_event.edEVT_STATUS, self.GetId(), _("Recording Finished"), ed_glob.SB_INFO) wx.PostEvent(self.TopLevelParent, evt) self._BuildMacro()
[ "def", "StopRecord", "(", "self", ")", ":", "# pylint: disable-msg=W0221", "self", ".", "recording", "=", "False", "super", "(", "EditraStc", ",", "self", ")", ".", "StopRecord", "(", ")", "evt", "=", "ed_event", ".", "StatusEvent", "(", "ed_event", ".", "...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L1513-L1524
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
docs/examples/use_cases/tensorflow/efficientdet/model/backbone/efficientnet_model.py
python
Head.call
(self, inputs, training, pooled_features_only)
return outputs
Call the layer.
Call the layer.
[ "Call", "the", "layer", "." ]
def call(self, inputs, training, pooled_features_only): """Call the layer.""" outputs = self._relu_fn(self._bn(self._conv_head(inputs), training=training)) self.endpoints["head_1x1"] = outputs if self._global_params.local_pooling: shape = outputs.get_shape().as_list() kernel_size = [1, shape[self.h_axis], shape[self.w_axis], 1] outputs = tf.nn.avg_pool( outputs, ksize=kernel_size, strides=[1, 1, 1, 1], padding="VALID" ) self.endpoints["pooled_features"] = outputs if not pooled_features_only: if self._dropout: outputs = self._dropout(outputs, training=training) self.endpoints["global_pool"] = outputs if self._fc: outputs = tf.squeeze(outputs, [self.h_axis, self.w_axis]) outputs = self._fc(outputs) self.endpoints["head"] = outputs else: outputs = self._avg_pooling(outputs) self.endpoints["pooled_features"] = outputs if not pooled_features_only: if self._dropout: outputs = self._dropout(outputs, training=training) self.endpoints["global_pool"] = outputs if self._fc: outputs = self._fc(outputs) self.endpoints["head"] = outputs return outputs
[ "def", "call", "(", "self", ",", "inputs", ",", "training", ",", "pooled_features_only", ")", ":", "outputs", "=", "self", ".", "_relu_fn", "(", "self", ".", "_bn", "(", "self", ".", "_conv_head", "(", "inputs", ")", ",", "training", "=", "training", "...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/tensorflow/efficientdet/model/backbone/efficientnet_model.py#L606-L636
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/sparse/base.py
python
spmatrix.tolil
(self, copy=False)
return self.tocsr(copy=False).tolil(copy=copy)
Convert this matrix to LInked List format. With copy=False, the data/indices may be shared between this matrix and the resultant lil_matrix.
Convert this matrix to LInked List format.
[ "Convert", "this", "matrix", "to", "LInked", "List", "format", "." ]
def tolil(self, copy=False): """Convert this matrix to LInked List format. With copy=False, the data/indices may be shared between this matrix and the resultant lil_matrix. """ return self.tocsr(copy=False).tolil(copy=copy)
[ "def", "tolil", "(", "self", ",", "copy", "=", "False", ")", ":", "return", "self", ".", "tocsr", "(", "copy", "=", "False", ")", ".", "tolil", "(", "copy", "=", "copy", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/base.py#L752-L758
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
sign
(x, name=None)
Returns an element-wise indication of the sign of a number. `y = sign(x) = -1` if `x < 0`; 0 if `x == 0`; 1 if `x > 0`. For complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`. Args: x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.
Returns an element-wise indication of the sign of a number.
[ "Returns", "an", "element", "-", "wise", "indication", "of", "the", "sign", "of", "a", "number", "." ]
def sign(x, name=None): """Returns an element-wise indication of the sign of a number. `y = sign(x) = -1` if `x < 0`; 0 if `x == 0`; 1 if `x > 0`. For complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`. Args: x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. """ with ops.op_scope([x], name, "Sign") as name: if isinstance(x, ops.SparseTensor): x_sign = gen_math_ops.sign(x.values, name=name) return ops.SparseTensor(indices=x.indices, values=x_sign, shape=x.shape) else: return gen_math_ops.sign(x, name=name)
[ "def", "sign", "(", "x", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "x", "]", ",", "name", ",", "\"Sign\"", ")", "as", "name", ":", "if", "isinstance", "(", "x", ",", "ops", ".", "SparseTensor", ")", ":", "x_s...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L304-L324
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
chrome/common/extensions/PRESUBMIT.py
python
DocsGenerated
(input_api)
return any(IsGeneratedDoc(path, input_api) for path in input_api.LocalPaths())
Return True if there are any generated docs in this change. Generated docs are the files that are the output of build.py. Typically all docs changes will contain both generated docs and non-generated files.
Return True if there are any generated docs in this change.
[ "Return", "True", "if", "there", "are", "any", "generated", "docs", "in", "this", "change", "." ]
def DocsGenerated(input_api): """Return True if there are any generated docs in this change. Generated docs are the files that are the output of build.py. Typically all docs changes will contain both generated docs and non-generated files. """ return any(IsGeneratedDoc(path, input_api) for path in input_api.LocalPaths())
[ "def", "DocsGenerated", "(", "input_api", ")", ":", "return", "any", "(", "IsGeneratedDoc", "(", "path", ",", "input_api", ")", "for", "path", "in", "input_api", ".", "LocalPaths", "(", ")", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/PRESUBMIT.py#L117-L124
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/isis_instrument.py
python
BaseInstrument.get_default_beam_center
(self)
return [0, 0]
Returns the default beam center position, or the pixel location of real-space coordinates (0,0).
Returns the default beam center position, or the pixel location of real-space coordinates (0,0).
[ "Returns", "the", "default", "beam", "center", "position", "or", "the", "pixel", "location", "of", "real", "-", "space", "coordinates", "(", "0", "0", ")", "." ]
def get_default_beam_center(self): """ Returns the default beam center position, or the pixel location of real-space coordinates (0,0). """ return [0, 0]
[ "def", "get_default_beam_center", "(", "self", ")", ":", "return", "[", "0", ",", "0", "]" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_instrument.py#L39-L44
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/generic.py
python
NDFrame.to_excel
( self, excel_writer, sheet_name: str = "Sheet1", na_rep: str = "", float_format: str | None = None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep="inf", verbose=True, freeze_panes=None, storage_options: StorageOptions = None, )
Write {klass} to an Excel sheet. To write a single {klass} to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an `ExcelWriter` object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique `sheet_name`. With all data written to the file it is necessary to save the changes. Note that creating an `ExcelWriter` object with a file name that already exists will result in the contents of the existing file being erased. Parameters ---------- excel_writer : path-like, file-like, or ExcelWriter object File path or existing ExcelWriter. sheet_name : str, default 'Sheet1' Name of sheet which will contain DataFrame. na_rep : str, default '' Missing data representation. float_format : str, optional Format string for floating point numbers. For example ``float_format="%.2f"`` will format 0.1234 to 0.12. columns : sequence or list of str, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of string is given it is assumed to be aliases for the column names. index : bool, default True Write row names (index). index_label : str or sequence, optional Column label for index column(s) if desired. If not specified, and `header` and `index` are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. startrow : int, default 0 Upper left cell row to dump data frame. startcol : int, default 0 Upper left cell column to dump data frame. engine : str, optional Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and ``io.excel.xlsm.writer``. .. deprecated:: 1.2.0 As the `xlwt <https://pypi.org/project/xlwt/>`__ package is no longer maintained, the ``xlwt`` engine will be removed in a future version of pandas. merge_cells : bool, default True Write MultiIndex and Hierarchical Rows as merged cells. encoding : str, optional Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively. inf_rep : str, default 'inf' Representation for infinity (there is no native representation for infinity in Excel). verbose : bool, default True Display more information in the error logs. freeze_panes : tuple of int (length 2), optional Specifies the one-based bottommost row and rightmost column that is to be frozen. {storage_options} .. versionadded:: 1.2.0 See Also -------- to_csv : Write DataFrame to a comma-separated values (csv) file. ExcelWriter : Class for writing DataFrame objects into excel sheets. read_excel : Read an Excel file into a pandas DataFrame. read_csv : Read a comma-separated values (csv) file into DataFrame. Notes ----- For compatibility with :meth:`~DataFrame.to_csv`, to_excel serializes lists and dicts to strings before writing. Once a workbook has been saved it is not possible to write further data without rewriting the whole workbook. Examples -------- Create, write to and save a workbook: >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']) >>> df1.to_excel("output.xlsx") # doctest: +SKIP To specify the sheet name: >>> df1.to_excel("output.xlsx", ... sheet_name='Sheet_name_1') # doctest: +SKIP If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object: >>> df2 = df1.copy() >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP ... df1.to_excel(writer, sheet_name='Sheet_name_1') ... df2.to_excel(writer, sheet_name='Sheet_name_2') ExcelWriter can also be used to append to an existing Excel file: >>> with pd.ExcelWriter('output.xlsx', ... mode='a') as writer: # doctest: +SKIP ... df.to_excel(writer, sheet_name='Sheet_name_3') To set the library that is used to write the Excel file, you can pass the `engine` keyword (the default engine is automatically chosen depending on the file extension): >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP
Write {klass} to an Excel sheet.
[ "Write", "{", "klass", "}", "to", "an", "Excel", "sheet", "." ]
def to_excel( self, excel_writer, sheet_name: str = "Sheet1", na_rep: str = "", float_format: str | None = None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep="inf", verbose=True, freeze_panes=None, storage_options: StorageOptions = None, ) -> None: """ Write {klass} to an Excel sheet. To write a single {klass} to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an `ExcelWriter` object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique `sheet_name`. With all data written to the file it is necessary to save the changes. Note that creating an `ExcelWriter` object with a file name that already exists will result in the contents of the existing file being erased. Parameters ---------- excel_writer : path-like, file-like, or ExcelWriter object File path or existing ExcelWriter. sheet_name : str, default 'Sheet1' Name of sheet which will contain DataFrame. na_rep : str, default '' Missing data representation. float_format : str, optional Format string for floating point numbers. For example ``float_format="%.2f"`` will format 0.1234 to 0.12. columns : sequence or list of str, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of string is given it is assumed to be aliases for the column names. index : bool, default True Write row names (index). index_label : str or sequence, optional Column label for index column(s) if desired. If not specified, and `header` and `index` are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. startrow : int, default 0 Upper left cell row to dump data frame. startcol : int, default 0 Upper left cell column to dump data frame. engine : str, optional Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and ``io.excel.xlsm.writer``. .. deprecated:: 1.2.0 As the `xlwt <https://pypi.org/project/xlwt/>`__ package is no longer maintained, the ``xlwt`` engine will be removed in a future version of pandas. merge_cells : bool, default True Write MultiIndex and Hierarchical Rows as merged cells. encoding : str, optional Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively. inf_rep : str, default 'inf' Representation for infinity (there is no native representation for infinity in Excel). verbose : bool, default True Display more information in the error logs. freeze_panes : tuple of int (length 2), optional Specifies the one-based bottommost row and rightmost column that is to be frozen. {storage_options} .. versionadded:: 1.2.0 See Also -------- to_csv : Write DataFrame to a comma-separated values (csv) file. ExcelWriter : Class for writing DataFrame objects into excel sheets. read_excel : Read an Excel file into a pandas DataFrame. read_csv : Read a comma-separated values (csv) file into DataFrame. Notes ----- For compatibility with :meth:`~DataFrame.to_csv`, to_excel serializes lists and dicts to strings before writing. Once a workbook has been saved it is not possible to write further data without rewriting the whole workbook. Examples -------- Create, write to and save a workbook: >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']) >>> df1.to_excel("output.xlsx") # doctest: +SKIP To specify the sheet name: >>> df1.to_excel("output.xlsx", ... sheet_name='Sheet_name_1') # doctest: +SKIP If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object: >>> df2 = df1.copy() >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP ... df1.to_excel(writer, sheet_name='Sheet_name_1') ... df2.to_excel(writer, sheet_name='Sheet_name_2') ExcelWriter can also be used to append to an existing Excel file: >>> with pd.ExcelWriter('output.xlsx', ... mode='a') as writer: # doctest: +SKIP ... df.to_excel(writer, sheet_name='Sheet_name_3') To set the library that is used to write the Excel file, you can pass the `engine` keyword (the default engine is automatically chosen depending on the file extension): >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP """ df = self if isinstance(self, ABCDataFrame) else self.to_frame() from pandas.io.formats.excel import ExcelFormatter formatter = ExcelFormatter( df, na_rep=na_rep, cols=columns, header=header, float_format=float_format, index=index, index_label=index_label, merge_cells=merge_cells, inf_rep=inf_rep, ) formatter.write( excel_writer, sheet_name=sheet_name, startrow=startrow, startcol=startcol, freeze_panes=freeze_panes, engine=engine, storage_options=storage_options, )
[ "def", "to_excel", "(", "self", ",", "excel_writer", ",", "sheet_name", ":", "str", "=", "\"Sheet1\"", ",", "na_rep", ":", "str", "=", "\"\"", ",", "float_format", ":", "str", "|", "None", "=", "None", ",", "columns", "=", "None", ",", "header", "=", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L2131-L2292
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/common/tokenizer.py
python
Tokenizer._CreateToken
(self, string, token_type, line, line_number, values=None)
return tokens.Token(string, token_type, line, line_number, values)
Creates a new Token object (or subclass). Args: string: The string of input the token represents. token_type: The type of token. line: The text of the line this token is in. line_number: The line number of the token. values: A dict of named values within the token. For instance, a function declaration may have a value called 'name' which captures the name of the function. Returns: The newly created Token object.
Creates a new Token object (or subclass).
[ "Creates", "a", "new", "Token", "object", "(", "or", "subclass", ")", "." ]
def _CreateToken(self, string, token_type, line, line_number, values=None): """Creates a new Token object (or subclass). Args: string: The string of input the token represents. token_type: The type of token. line: The text of the line this token is in. line_number: The line number of the token. values: A dict of named values within the token. For instance, a function declaration may have a value called 'name' which captures the name of the function. Returns: The newly created Token object. """ return tokens.Token(string, token_type, line, line_number, values)
[ "def", "_CreateToken", "(", "self", ",", "string", ",", "token_type", ",", "line", ",", "line_number", ",", "values", "=", "None", ")", ":", "return", "tokens", ".", "Token", "(", "string", ",", "token_type", ",", "line", ",", "line_number", ",", "values...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/common/tokenizer.py#L78-L93
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Utilities/Maintenance/vtk_generate_pyi.py
python
isenum
(m)
return (isclass(m) and issubclass(m, int))
Check for enums (currently derived from int)
Check for enums (currently derived from int)
[ "Check", "for", "enums", "(", "currently", "derived", "from", "int", ")" ]
def isenum(m): """Check for enums (currently derived from int)""" return (isclass(m) and issubclass(m, int))
[ "def", "isenum", "(", "m", ")", ":", "return", "(", "isclass", "(", "m", ")", "and", "issubclass", "(", "m", ",", "int", ")", ")" ]
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Utilities/Maintenance/vtk_generate_pyi.py#L71-L73
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Tool/docbook/__init__.py
python
__extend_targets_sources
(target, source)
return target, source
Prepare the lists of target and source files.
Prepare the lists of target and source files.
[ "Prepare", "the", "lists", "of", "target", "and", "source", "files", "." ]
def __extend_targets_sources(target, source): """ Prepare the lists of target and source files. """ if not SCons.Util.is_List(target): target = [target] if not source: source = target[:] elif not SCons.Util.is_List(source): source = [source] if len(target) < len(source): target.extend(source[len(target):]) return target, source
[ "def", "__extend_targets_sources", "(", "target", ",", "source", ")", ":", "if", "not", "SCons", ".", "Util", ".", "is_List", "(", "target", ")", ":", "target", "=", "[", "target", "]", "if", "not", "source", ":", "source", "=", "target", "[", ":", "...
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/docbook/__init__.py#L71-L82