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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/client.py
python
HTTPResponse.readinto
(self, b)
return n
Read up to len(b) bytes into bytearray b and return the number of bytes read.
Read up to len(b) bytes into bytearray b and return the number of bytes read.
[ "Read", "up", "to", "len", "(", "b", ")", "bytes", "into", "bytearray", "b", "and", "return", "the", "number", "of", "bytes", "read", "." ]
def readinto(self, b): """Read up to len(b) bytes into bytearray b and return the number of bytes read. """ if self.fp is None: return 0 if self._method == "HEAD": self._close_conn() return 0 if self.chunked: return self._readinto_chunked(b) if self.length is not None: if len(b) > self.length: # clip the read to the "end of response" b = memoryview(b)[0:self.length] # we do not use _safe_read() here because this may be a .will_close # connection, and the user is reading more bytes than will be provided # (for example, reading in 1k chunks) n = self.fp.readinto(b) if not n and b: # Ideally, we would raise IncompleteRead if the content-length # wasn't satisfied, but it might break compatibility. self._close_conn() elif self.length is not None: self.length -= n if not self.length: self._close_conn() return n
[ "def", "readinto", "(", "self", ",", "b", ")", ":", "if", "self", ".", "fp", "is", "None", ":", "return", "0", "if", "self", ".", "_method", "==", "\"HEAD\"", ":", "self", ".", "_close_conn", "(", ")", "return", "0", "if", "self", ".", "chunked", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/client.py#L482-L514
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
MakeCredentialResponse.initFromTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def initFromTpm(self, buf): """ TpmMarshaller method """ self.credentialBlob = buf.createSizedObj(TPMS_ID_OBJECT) self.secret = buf.readSizedByteBuf()
[ "def", "initFromTpm", "(", "self", ",", "buf", ")", ":", "self", ".", "credentialBlob", "=", "buf", ".", "createSizedObj", "(", "TPMS_ID_OBJECT", ")", "self", ".", "secret", "=", "buf", ".", "readSizedByteBuf", "(", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9988-L9991
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/pstatbar.py
python
ProgressStatusBar._UpdateValue
(self, value)
Update the internal progress gauges value @param range: int
Update the internal progress gauges value @param range: int
[ "Update", "the", "internal", "progress", "gauges", "value", "@param", "range", ":", "int" ]
def _UpdateValue(self, value): """Update the internal progress gauges value @param range: int """ # Ensure value is within range range = self.prog.GetRange() if range != self.range: # need to scale value value = int((float(value) / float(range)) * 100) self.progress = value self.prog.SetValue(value)
[ "def", "_UpdateValue", "(", "self", ",", "value", ")", ":", "# Ensure value is within range", "range", "=", "self", ".", "prog", ".", "GetRange", "(", ")", "if", "range", "!=", "self", ".", "range", ":", "# need to scale value", "value", "=", "int", "(", "...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/pstatbar.py#L102-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py
python
GLRenderer.recursive_render
(self, node)
Main recursive rendering method.
Main recursive rendering method.
[ "Main", "recursive", "rendering", "method", "." ]
def recursive_render(self, node): """ Main recursive rendering method. """ # save model matrix and apply node transformation glPushMatrix() m = node.transformation.transpose() # OpenGL row major glMultMatrixf(m) for mesh in node.meshes: self.apply_material(mesh.material) glBindBuffer(GL_ARRAY_BUFFER, mesh.gl["vertices"]) glEnableClientState(GL_VERTEX_ARRAY) glVertexPointer(3, GL_FLOAT, 0, None) glBindBuffer(GL_ARRAY_BUFFER, mesh.gl["normals"]) glEnableClientState(GL_NORMAL_ARRAY) glNormalPointer(GL_FLOAT, 0, None) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["triangles"]) glDrawElements(GL_TRIANGLES,len(mesh.faces) * 3, GL_UNSIGNED_INT, None) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) for child in node.children: self.recursive_render(child) glPopMatrix()
[ "def", "recursive_render", "(", "self", ",", "node", ")", ":", "# save model matrix and apply node transformation", "glPushMatrix", "(", ")", "m", "=", "node", ".", "transformation", ".", "transpose", "(", ")", "# OpenGL row major", "glMultMatrixf", "(", "m", ")", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py#L251-L283
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
linked_list/split_circular_lists.py
python
split_list
(cll)
return cll1, cll2
split a circular linked list into two halves
split a circular linked list into two halves
[ "split", "a", "circular", "linked", "list", "into", "two", "halves" ]
def split_list(cll): """ split a circular linked list into two halves """ slow_ptr = cll.head fast_ptr = cll.head while (fast_ptr.next is not cll.head and fast_ptr.next.next is not cll.head): slow_ptr = slow_ptr.next fast_ptr = fast_ptr.next.next while fast_ptr.next is not cll.head: fast_ptr = fast_ptr.next cll1 = CircularLinkedList() cll2 = CircularLinkedList() cll1.head = cll.head cll2.head = slow_ptr.next slow_ptr.next = cll1.head fast_ptr.next = cll2.head return cll1, cll2
[ "def", "split_list", "(", "cll", ")", ":", "slow_ptr", "=", "cll", ".", "head", "fast_ptr", "=", "cll", ".", "head", "while", "(", "fast_ptr", ".", "next", "is", "not", "cll", ".", "head", "and", "fast_ptr", ".", "next", ".", "next", "is", "not", "...
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/split_circular_lists.py#L52-L73
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/smtpd.py
python
SMTPServer.process_message
(self, peer, mailfrom, rcpttos, data, **kwargs)
Override this abstract method to handle messages from the client. peer is a tuple containing (ipaddr, port) of the client that made the socket connection to our smtp port. mailfrom is the raw address the client claims the message is coming from. rcpttos is a list of raw addresses the client wishes to deliver the message to. data is a string containing the entire full text of the message, headers (if supplied) and all. It has been `de-transparencied' according to RFC 821, Section 4.5.2. In other words, a line containing a `.' followed by other text has had the leading dot removed. kwargs is a dictionary containing additional information. It is empty if decode_data=True was given as init parameter, otherwise it will contain the following keys: 'mail_options': list of parameters to the mail command. All elements are uppercase strings. Example: ['BODY=8BITMIME', 'SMTPUTF8']. 'rcpt_options': same, for the rcpt command. This function should return None for a normal `250 Ok' response; otherwise, it should return the desired response string in RFC 821 format.
Override this abstract method to handle messages from the client.
[ "Override", "this", "abstract", "method", "to", "handle", "messages", "from", "the", "client", "." ]
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): """Override this abstract method to handle messages from the client. peer is a tuple containing (ipaddr, port) of the client that made the socket connection to our smtp port. mailfrom is the raw address the client claims the message is coming from. rcpttos is a list of raw addresses the client wishes to deliver the message to. data is a string containing the entire full text of the message, headers (if supplied) and all. It has been `de-transparencied' according to RFC 821, Section 4.5.2. In other words, a line containing a `.' followed by other text has had the leading dot removed. kwargs is a dictionary containing additional information. It is empty if decode_data=True was given as init parameter, otherwise it will contain the following keys: 'mail_options': list of parameters to the mail command. All elements are uppercase strings. Example: ['BODY=8BITMIME', 'SMTPUTF8']. 'rcpt_options': same, for the rcpt command. This function should return None for a normal `250 Ok' response; otherwise, it should return the desired response string in RFC 821 format. """ raise NotImplementedError
[ "def", "process_message", "(", "self", ",", "peer", ",", "mailfrom", ",", "rcpttos", ",", "data", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/smtpd.py#L671-L702
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/combo.py
python
ComboCtrl.GetBitmapPressed
(*args, **kwargs)
return _combo.ComboCtrl_GetBitmapPressed(*args, **kwargs)
GetBitmapPressed(self) -> Bitmap
GetBitmapPressed(self) -> Bitmap
[ "GetBitmapPressed", "(", "self", ")", "-", ">", "Bitmap" ]
def GetBitmapPressed(*args, **kwargs): """GetBitmapPressed(self) -> Bitmap""" return _combo.ComboCtrl_GetBitmapPressed(*args, **kwargs)
[ "def", "GetBitmapPressed", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboCtrl_GetBitmapPressed", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L450-L452
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/examples/learn/wide_n_deep_tutorial.py
python
build_estimator
(model_dir)
return m
Build an estimator.
Build an estimator.
[ "Build", "an", "estimator", "." ]
def build_estimator(model_dir): """Build an estimator.""" # Sparse base columns. gender = tf.contrib.layers.sparse_column_with_keys(column_name="gender", keys=["female", "male"]) race = tf.contrib.layers.sparse_column_with_keys(column_name="race", keys=["Amer-Indian-Eskimo", "Asian-Pac-Islander", "Black", "Other", "White"]) education = tf.contrib.layers.sparse_column_with_hash_bucket( "education", hash_bucket_size=1000) marital_status = tf.contrib.layers.sparse_column_with_hash_bucket( "marital_status", hash_bucket_size=100) relationship = tf.contrib.layers.sparse_column_with_hash_bucket( "relationship", hash_bucket_size=100) workclass = tf.contrib.layers.sparse_column_with_hash_bucket( "workclass", hash_bucket_size=100) occupation = tf.contrib.layers.sparse_column_with_hash_bucket( "occupation", hash_bucket_size=1000) native_country = tf.contrib.layers.sparse_column_with_hash_bucket( "native_country", hash_bucket_size=1000) # Continuous base columns. age = tf.contrib.layers.real_valued_column("age") education_num = tf.contrib.layers.real_valued_column("education_num") capital_gain = tf.contrib.layers.real_valued_column("capital_gain") capital_loss = tf.contrib.layers.real_valued_column("capital_loss") hours_per_week = tf.contrib.layers.real_valued_column("hours_per_week") # Transformations. age_buckets = tf.contrib.layers.bucketized_column(age, boundaries=[ 18, 25, 30, 35, 40, 45, 50, 55, 60, 65 ]) # Wide columns and deep columns. wide_columns = [gender, native_country, education, occupation, workclass, marital_status, relationship, age_buckets, tf.contrib.layers.crossed_column([education, occupation], hash_bucket_size=int(1e4)), tf.contrib.layers.crossed_column( [age_buckets, race, occupation], hash_bucket_size=int(1e6)), tf.contrib.layers.crossed_column([native_country, occupation], hash_bucket_size=int(1e4))] deep_columns = [ tf.contrib.layers.embedding_column(workclass, dimension=8), tf.contrib.layers.embedding_column(education, dimension=8), tf.contrib.layers.embedding_column(marital_status, dimension=8), tf.contrib.layers.embedding_column(gender, dimension=8), tf.contrib.layers.embedding_column(relationship, dimension=8), tf.contrib.layers.embedding_column(race, dimension=8), tf.contrib.layers.embedding_column(native_country, dimension=8), tf.contrib.layers.embedding_column(occupation, dimension=8), age, education_num, capital_gain, capital_loss, hours_per_week, ] if FLAGS.model_type == "wide": m = tf.contrib.learn.LinearClassifier(model_dir=model_dir, feature_columns=wide_columns) elif FLAGS.model_type == "deep": m = tf.contrib.learn.DNNClassifier(model_dir=model_dir, feature_columns=deep_columns, hidden_units=[100, 50]) else: m = tf.contrib.learn.DNNLinearCombinedClassifier( model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=[100, 50]) return m
[ "def", "build_estimator", "(", "model_dir", ")", ":", "# Sparse base columns.", "gender", "=", "tf", ".", "contrib", ".", "layers", ".", "sparse_column_with_keys", "(", "column_name", "=", "\"gender\"", ",", "keys", "=", "[", "\"female\"", ",", "\"male\"", "]", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/examples/learn/wide_n_deep_tutorial.py#L76-L155
pgRouting/osm2pgrouting
8491929fc4037d308f271e84d59bb96da3c28aa2
tools/cpplint.py
python
CheckInvalidIncrement
(filename, clean_lines, linenum, error)
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for invalid increment *count++.
[ "Checks", "for", "invalid", "increment", "*", "count", "++", "." ]
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).')
[ "def", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "_RE_PATTERN_INVALID_INCREMENT", ".", "match", "(", "line", ")", ":", "error", ...
https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L1959-L1978
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
ParameterFunction.getparam
(self, name)
return self.params[name]
Get a parameter as parsed.
Get a parameter as parsed.
[ "Get", "a", "parameter", "as", "parsed", "." ]
def getparam(self, name): "Get a parameter as parsed." if not name in self.params: return None return self.params[name]
[ "def", "getparam", "(", "self", ",", "name", ")", ":", "if", "not", "name", "in", "self", ".", "params", ":", "return", "None", "return", "self", ".", "params", "[", "name", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4908-L4912
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py
python
HashedCategoricalColumn.transform_feature
(self, transformation_cache, state_manager)
return self._transform_input_tensor(input_tensor)
Hashes the values in the feature_column.
Hashes the values in the feature_column.
[ "Hashes", "the", "values", "in", "the", "feature_column", "." ]
def transform_feature(self, transformation_cache, state_manager): """Hashes the values in the feature_column.""" input_tensor = _to_sparse_input_and_drop_ignore_values( transformation_cache.get(self.key, state_manager)) return self._transform_input_tensor(input_tensor)
[ "def", "transform_feature", "(", "self", ",", "transformation_cache", ",", "state_manager", ")", ":", "input_tensor", "=", "_to_sparse_input_and_drop_ignore_values", "(", "transformation_cache", ".", "get", "(", "self", ".", "key", ",", "state_manager", ")", ")", "r...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L3507-L3511
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/masked/maskededit.py
python
MaskedEditMixin._getAbsValue
(self, candidate=None)
return text, signpos, right_signpos
Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s).
Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s).
[ "Return", "an", "unsigned", "value", "(", "i", ".", "e", ".", "strip", "the", "-", "prefix", "if", "any", ")", "and", "sign", "position", "(", "s", ")", "." ]
def _getAbsValue(self, candidate=None): """ Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s). """ ## dbg('MaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1) if candidate is None: text = self._GetValue() else: text = candidate right_signpos = text.find(')') if self._isInt: if self._ctrl_constraints._alignRight and self._fields[0]._fillChar == ' ': signpos = text.find('-') if signpos == -1: ## dbg('no - found; searching for (') signpos = text.find('(') elif signpos != -1: ## dbg('- found at', signpos) pass if signpos == -1: ## dbg('signpos still -1') ## dbg('len(%s) (%d) < len(%s) (%d)?' % (text, len(text), self._mask, self._masklength), len(text) < self._masklength) if len(text) < self._masklength: text = ' ' + text if len(text) < self._masklength: text += ' ' if len(text) > self._masklength and text[-1] in (')', ' '): text = text[:-1] else: ## dbg('len(%s) (%d), len(%s) (%d)' % (text, len(text), self._mask, self._masklength)) ## dbg('len(%s) - (len(%s) + 1):' % (text, text.lstrip()) , len(text) - (len(text.lstrip()) + 1)) signpos = len(text) - (len(text.lstrip()) + 1) if self._useParens and not text.strip(): signpos -= 1 # empty value; use penultimate space ## dbg('signpos:', signpos) if signpos >= 0: text = text[:signpos] + ' ' + text[signpos+1:] else: if self._signOk: signpos = 0 text = self._template[0] + text[1:] else: signpos = -1 if right_signpos != -1: if self._signOk: text = text[:right_signpos] + ' ' + text[right_signpos+1:] elif len(text) > self._masklength: text = text[:right_signpos] + text[right_signpos+1:] right_signpos = -1 elif self._useParens and self._signOk: # figure out where it ought to go: right_signpos = self._masklength - 1 # initial guess if not self._ctrl_constraints._alignRight: ## dbg('not right-aligned') if len(text.strip()) == 0: right_signpos = signpos + 1 elif len(text.strip()) < self._masklength: right_signpos = len(text.rstrip()) ## dbg('right_signpos:', right_signpos) groupchar = self._fields[0]._groupChar try: value = long(text.replace(groupchar,'').replace('(','-').replace(')','').replace(' ', '')) except: ## dbg('invalid number', indent=0) return None, signpos, right_signpos else: # float value try: groupchar = self._fields[0]._groupChar value = float(text.replace(groupchar,'').replace(self._decimalChar, '.').replace('(', '-').replace(')','').replace(' ', '')) ## dbg('value:', value) except: value = None if value < 0 and value is not None: signpos = text.find('-') if signpos == -1: signpos = text.find('(') text = text[:signpos] + self._template[signpos] + text[signpos+1:] else: # look forwards up to the decimal point for the 1st non-digit ## dbg('decimal pos:', self._decimalpos) ## dbg('text: "%s"' % text) if self._signOk: signpos = self._decimalpos - (len(text[:self._decimalpos].lstrip()) + 1) # prevent checking for empty string - Tomo - Wed 14 Jan 2004 03:19:09 PM CET if len(text) >= signpos+1 and text[signpos+1] in ('-','('): signpos += 1 else: signpos = -1 ## dbg('signpos:', signpos) if self._useParens: if self._signOk: right_signpos = self._masklength - 1 text = text[:right_signpos] + ' ' if text[signpos] == '(': text = text[:signpos] + ' ' + text[signpos+1:] else: right_signpos = text.find(')') if right_signpos != -1: text = text[:-1] right_signpos = -1 if value is None: ## dbg('invalid number') text = None ## dbg('abstext = "%s"' % text, 'signpos:', signpos, 'right_signpos:', right_signpos) ## dbg(indent=0) return text, signpos, right_signpos
[ "def", "_getAbsValue", "(", "self", ",", "candidate", "=", "None", ")", ":", "## dbg('MaskedEditMixin::_getAbsValue; candidate=\"%s\"' % candidate, indent=1)", "if", "candidate", "is", "None", ":", "text", "=", "self", ".", "_GetValue", "(", ")", "else", ":", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/maskededit.py#L4814-L4930
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/unused-symbols-report.py
python
Unyuck
(sym)
return sym
Attempt to prettify a C++ symbol by some basic heuristics.
Attempt to prettify a C++ symbol by some basic heuristics.
[ "Attempt", "to", "prettify", "a", "C", "++", "symbol", "by", "some", "basic", "heuristics", "." ]
def Unyuck(sym): """Attempt to prettify a C++ symbol by some basic heuristics.""" sym = sym.replace('std::basic_string<char, std::char_traits<char>, ' 'std::allocator<char> >', 'std::string') sym = sym.replace('std::basic_string<wchar_t, std::char_traits<wchar_t>, ' 'std::allocator<wchar_t> >', 'std::wstring') sym = sym.replace('std::basic_string<unsigned short, ' 'base::string16_char_traits, ' 'std::allocator<unsigned short> >', 'string16') sym = re.sub(r', std::allocator<\S+\s+>', '', sym) return sym
[ "def", "Unyuck", "(", "sym", ")", ":", "sym", "=", "sym", ".", "replace", "(", "'std::basic_string<char, std::char_traits<char>, '", "'std::allocator<char> >'", ",", "'std::string'", ")", "sym", "=", "sym", ".", "replace", "(", "'std::basic_string<wchar_t, std::char_tra...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/unused-symbols-report.py#L38-L48
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.start_write
(self, frame, node=None)
Yield or write into the frame buffer.
Yield or write into the frame buffer.
[ "Yield", "or", "write", "into", "the", "frame", "buffer", "." ]
def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
[ "def", "start_write", "(", "self", ",", "frame", ",", "node", "=", "None", ")", ":", "if", "frame", ".", "buffer", "is", "None", ":", "self", ".", "writeline", "(", "'yield '", ",", "node", ")", "else", ":", "self", ".", "writeline", "(", "'%s.append...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py#L353-L358
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/pyarrow/orc.py
python
ORCFile.read_stripe
(self, n, columns=None)
return self.reader.read_stripe(n, columns=columns)
Read a single stripe from the file. Parameters ---------- n : int The stripe index columns : list If not None, only these columns will be read from the stripe. A column name may be a prefix of a nested field, e.g. 'a' will select 'a.b', 'a.c', and 'a.d.e' Returns ------- pyarrow.RecordBatch Content of the stripe as a RecordBatch.
Read a single stripe from the file.
[ "Read", "a", "single", "stripe", "from", "the", "file", "." ]
def read_stripe(self, n, columns=None): """Read a single stripe from the file. Parameters ---------- n : int The stripe index columns : list If not None, only these columns will be read from the stripe. A column name may be a prefix of a nested field, e.g. 'a' will select 'a.b', 'a.c', and 'a.d.e' Returns ------- pyarrow.RecordBatch Content of the stripe as a RecordBatch. """ columns = self._select_names(columns) return self.reader.read_stripe(n, columns=columns)
[ "def", "read_stripe", "(", "self", ",", "n", ",", "columns", "=", "None", ")", ":", "columns", "=", "self", ".", "_select_names", "(", "columns", ")", "return", "self", ".", "reader", ".", "read_stripe", "(", "n", ",", "columns", "=", "columns", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/orc.py#L150-L168
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
llvm/utils/lit/lit/LitConfig.py
python
LitConfig.maxIndividualTestTime
(self, value)
Interface for setting maximum time to spend executing a single test
Interface for setting maximum time to spend executing a single test
[ "Interface", "for", "setting", "maximum", "time", "to", "spend", "executing", "a", "single", "test" ]
def maxIndividualTestTime(self, value): """ Interface for setting maximum time to spend executing a single test """ if not isinstance(value, int): self.fatal('maxIndividualTestTime must set to a value of type int.') self._maxIndividualTestTime = value if self.maxIndividualTestTime > 0: # The current implementation needs psutil on some platforms to set # a timeout per test. Check it's available. # See lit.util.killProcessAndChildren() supported, errormsg = self.maxIndividualTestTimeIsSupported if not supported: self.fatal('Setting a timeout per test not supported. ' + errormsg) elif self.maxIndividualTestTime < 0: self.fatal('The timeout per test must be >= 0 seconds')
[ "def", "maxIndividualTestTime", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "self", ".", "fatal", "(", "'maxIndividualTestTime must set to a value of type int.'", ")", "self", ".", "_maxIndividualTestTime", "...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/llvm/utils/lit/lit/LitConfig.py#L92-L109
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.__repr__
(self, _repr_running={})
od.__repr__() <==> repr(od)
od.__repr__() <==> repr(od)
[ "od", ".", "__repr__", "()", "<", "==", ">", "repr", "(", "od", ")" ]
def __repr__(self, _repr_running={}): 'od.__repr__() <==> repr(od)' call_key = id(self), _get_ident() if call_key in _repr_running: return '...' _repr_running[call_key] = 1 try: if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key]
[ "def", "__repr__", "(", "self", ",", "_repr_running", "=", "{", "}", ")", ":", "call_key", "=", "id", "(", "self", ")", ",", "_get_ident", "(", ")", "if", "call_key", "in", "_repr_running", ":", "return", "'...'", "_repr_running", "[", "call_key", "]", ...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py#L226-L237
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/server/TServer.py
python
TThreadPoolServer.serveClient
(self, client)
Process input/output from a client for as long as possible
Process input/output from a client for as long as possible
[ "Process", "input", "/", "output", "from", "a", "client", "for", "as", "long", "as", "possible" ]
def serveClient(self, client): """Process input/output from a client for as long as possible""" itrans = self.inputTransportFactory.getTransport(client) iprot = self.inputProtocolFactory.getProtocol(itrans) # for THeaderProtocol, we must use the same protocol instance for input # and output so that the response is in the same dialect that the # server detected the request was in. if isinstance(self.inputProtocolFactory, THeaderProtocolFactory): otrans = None oprot = iprot else: otrans = self.outputTransportFactory.getTransport(client) oprot = self.outputProtocolFactory.getProtocol(otrans) try: while True: self.processor.process(iprot, oprot) except TTransport.TTransportException: pass except Exception as x: logger.exception(x) itrans.close() if otrans: otrans.close()
[ "def", "serveClient", "(", "self", ",", "client", ")", ":", "itrans", "=", "self", ".", "inputTransportFactory", ".", "getTransport", "(", "client", ")", "iprot", "=", "self", ".", "inputProtocolFactory", ".", "getProtocol", "(", "itrans", ")", "# for THeaderP...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/server/TServer.py#L184-L209
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
python
ObjPanelMixin.recreate_panel_table
(self, attrconfigs=None, groupnames=None, show_groupnames=False, show_title=True, is_modal=False, immediate_apply=False, panelstyle='default', func_change_obj=None, func_choose_id=None, func_choose_attr=None, func_apply=None, is_scrolled=True, **buttonargs)
return True
Recreates panel and destroys previous contents: attr = a list ith attribute names to be shown groups = list with group names to be shown show_groupnames = the group names are shown together with the respective attributes is_modal = if true the panel will be optimized for dialog window immediate_apply = changes to widgets will be immediately applied to obj attribute without pressing apply buttonargs = a dictionary with arguments for botton creation obj = the object to be displayed func_change_obj = function to be called if user clicks on on object with obj as argument func_choose_id = function to be called when user clicks on id(table row) with id as argument func_choose_attr = function to be called when user clicks on attribute with attr as argument. In this case the attribute names of scalars turn into buttons. Array attributes are selected by clicking on the column name. func_apply = is executed when apply button is pressed, and after widget values have been applied. Arguments are: obj, id, ids
Recreates panel and destroys previous contents: attr = a list ith attribute names to be shown groups = list with group names to be shown show_groupnames = the group names are shown together with the respective attributes is_modal = if true the panel will be optimized for dialog window immediate_apply = changes to widgets will be immediately applied to obj attribute without pressing apply buttonargs = a dictionary with arguments for botton creation obj = the object to be displayed func_change_obj = function to be called if user clicks on on object with obj as argument func_choose_id = function to be called when user clicks on id(table row) with id as argument func_choose_attr = function to be called when user clicks on attribute with attr as argument. In this case the attribute names of scalars turn into buttons. Array attributes are selected by clicking on the column name. func_apply = is executed when apply button is pressed, and after widget values have been applied. Arguments are: obj, id, ids
[ "Recreates", "panel", "and", "destroys", "previous", "contents", ":", "attr", "=", "a", "list", "ith", "attribute", "names", "to", "be", "shown", "groups", "=", "list", "with", "group", "names", "to", "be", "shown", "show_groupnames", "=", "the", "group", ...
def recreate_panel_table(self, attrconfigs=None, groupnames=None, show_groupnames=False, show_title=True, is_modal=False, immediate_apply=False, panelstyle='default', func_change_obj=None, func_choose_id=None, func_choose_attr=None, func_apply=None, is_scrolled=True, **buttonargs): """ Recreates panel and destroys previous contents: attr = a list ith attribute names to be shown groups = list with group names to be shown show_groupnames = the group names are shown together with the respective attributes is_modal = if true the panel will be optimized for dialog window immediate_apply = changes to widgets will be immediately applied to obj attribute without pressing apply buttonargs = a dictionary with arguments for botton creation obj = the object to be displayed func_change_obj = function to be called if user clicks on on object with obj as argument func_choose_id = function to be called when user clicks on id(table row) with id as argument func_choose_attr = function to be called when user clicks on attribute with attr as argument. In this case the attribute names of scalars turn into buttons. Array attributes are selected by clicking on the column name. func_apply = is executed when apply button is pressed, and after widget values have been applied. Arguments are: obj, id, ids """ # # print 'recreate_panel_table:',self.obj.ident,immediate_apply, func_apply,groupnames self.func_change_obj = func_change_obj self.func_choose_id = func_choose_id self.func_choose_attr = func_choose_attr self.func_apply = func_apply self._show_title = show_title # if is_scrolled is None: # is_scrolled = not is_modal #for dialog windows use non crolled panels by default attrsman = self.obj.get_attrsman() attrconfigs_scalar = attrsman.get_configs(structs=cm.STRUCTS_SCALAR, filtergroupnames=groupnames) # print ' attrconfigs_scalar',attrconfigs_scalar # if obj.managertype=='table': # obj is a single table # print ' is_scalar_panel & is_singletab:' table = self.obj #attrconfigs_scalar = attrsman.get_configs( structs = cm.STRUCTS_SCALAR) if len(attrconfigs_scalar) > 0: # print ' create a panel with scalars and a table below' self.make_scalartablepanel(self, attrconfigs_scalar, table, objpanel=self, attrconfigs=None, immediate_apply=immediate_apply, panelstyle=panelstyle, is_modal=is_modal, show_title=show_title, is_scrolled=is_scrolled, **buttonargs) else: # print ' create only a table, without scalars'#,attrsman.get_colconfigs(filtergroupnames = groupnames) self.make_tablepanel(self, table, objpanel=self, attrconfigs=None, groupnames=groupnames, immediate_apply=immediate_apply, panelstyle=panelstyle, is_modal=is_modal, show_title=show_title, is_scrolled=is_scrolled, **buttonargs) self.restore() return True
[ "def", "recreate_panel_table", "(", "self", ",", "attrconfigs", "=", "None", ",", "groupnames", "=", "None", ",", "show_groupnames", "=", "False", ",", "show_title", "=", "True", ",", "is_modal", "=", "False", ",", "immediate_apply", "=", "False", ",", "pane...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L3113-L3184
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/rds2/layer1.py
python
RDSConnection.describe_engine_default_parameters
(self, db_parameter_group_family, max_records=None, marker=None)
return self._make_request( action='DescribeEngineDefaultParameters', verb='POST', path='/', params=params)
Returns the default engine and system parameter information for the specified database engine. :type db_parameter_group_family: string :param db_parameter_group_family: The name of the DB parameter group family. :type max_records: integer :param max_records: The maximum number of records to include in the response. If more records exist than the specified `MaxRecords` value, a pagination token called a marker is included in the response so that the remaining results may be retrieved. Default: 100 Constraints: minimum 20, maximum 100 :type marker: string :param marker: An optional pagination token provided by a previous `DescribeEngineDefaultParameters` request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by `MaxRecords`.
Returns the default engine and system parameter information for the specified database engine.
[ "Returns", "the", "default", "engine", "and", "system", "parameter", "information", "for", "the", "specified", "database", "engine", "." ]
def describe_engine_default_parameters(self, db_parameter_group_family, max_records=None, marker=None): """ Returns the default engine and system parameter information for the specified database engine. :type db_parameter_group_family: string :param db_parameter_group_family: The name of the DB parameter group family. :type max_records: integer :param max_records: The maximum number of records to include in the response. If more records exist than the specified `MaxRecords` value, a pagination token called a marker is included in the response so that the remaining results may be retrieved. Default: 100 Constraints: minimum 20, maximum 100 :type marker: string :param marker: An optional pagination token provided by a previous `DescribeEngineDefaultParameters` request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by `MaxRecords`. """ params = { 'DBParameterGroupFamily': db_parameter_group_family, } if max_records is not None: params['MaxRecords'] = max_records if marker is not None: params['Marker'] = marker return self._make_request( action='DescribeEngineDefaultParameters', verb='POST', path='/', params=params)
[ "def", "describe_engine_default_parameters", "(", "self", ",", "db_parameter_group_family", ",", "max_records", "=", "None", ",", "marker", "=", "None", ")", ":", "params", "=", "{", "'DBParameterGroupFamily'", ":", "db_parameter_group_family", ",", "}", "if", "max_...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/rds2/layer1.py#L1858-L1894
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/numbers.py
python
Complex.__rpow__
(self, base)
base ** self
base ** self
[ "base", "**", "self" ]
def __rpow__(self, base): """base ** self""" raise NotImplementedError
[ "def", "__rpow__", "(", "self", ",", "base", ")", ":", "raise", "NotImplementedError" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/numbers.py#L142-L144
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/internals/construction.py
python
_check_values_indices_shape_match
( values: np.ndarray, index: Index, columns: Index )
Check that the shape implied by our axes matches the actual shape of the data.
Check that the shape implied by our axes matches the actual shape of the data.
[ "Check", "that", "the", "shape", "implied", "by", "our", "axes", "matches", "the", "actual", "shape", "of", "the", "data", "." ]
def _check_values_indices_shape_match( values: np.ndarray, index: Index, columns: Index ) -> None: """ Check that the shape implied by our axes matches the actual shape of the data. """ if values.shape[1] != len(columns) or values.shape[0] != len(index): # Could let this raise in Block constructor, but we get a more # helpful exception message this way. if values.shape[0] == 0: raise ValueError("Empty data passed with indices specified.") passed = values.shape implied = (len(index), len(columns)) raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
[ "def", "_check_values_indices_shape_match", "(", "values", ":", "np", ".", "ndarray", ",", "index", ":", "Index", ",", "columns", ":", "Index", ")", "->", "None", ":", "if", "values", ".", "shape", "[", "1", "]", "!=", "len", "(", "columns", ")", "or",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/construction.py#L378-L393
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/_base_index.py
python
BaseIndex.to_dlpack
(self)
return cudf.io.dlpack.to_dlpack(self)
{docstring}
{docstring}
[ "{", "docstring", "}" ]
def to_dlpack(self): """{docstring}""" return cudf.io.dlpack.to_dlpack(self)
[ "def", "to_dlpack", "(", "self", ")", ":", "return", "cudf", ".", "io", ".", "dlpack", ".", "to_dlpack", "(", "self", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/_base_index.py#L566-L569
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/examples/python/gdbremote.py
python
TerminalColors.bold
(self, on=True)
return ''
Enable or disable bold depending on the "on" parameter.
Enable or disable bold depending on the "on" parameter.
[ "Enable", "or", "disable", "bold", "depending", "on", "the", "on", "parameter", "." ]
def bold(self, on=True): '''Enable or disable bold depending on the "on" parameter.''' if self.enabled: if on: return "\x1b[1m" else: return "\x1b[22m" return ''
[ "def", "bold", "(", "self", ",", "on", "=", "True", ")", ":", "if", "self", ".", "enabled", ":", "if", "on", ":", "return", "\"\\x1b[1m\"", "else", ":", "return", "\"\\x1b[22m\"", "return", "''" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/examples/python/gdbremote.py#L55-L62
bryanyzhu/Hidden-Two-Stream
f7f684adbdacb6df6b1cf196c3a476cd23484a0f
scripts/cpp_lint.py
python
ReplaceAll
(pattern, rep, s)
return _regexp_compile_cache[pattern].sub(rep, s)
Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements)
Replaces instances of pattern in a string with a replacement.
[ "Replaces", "instances", "of", "pattern", "in", "a", "string", "with", "a", "replacement", "." ]
def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s)
[ "def", "ReplaceAll", "(", "pattern", ",", "rep", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_c...
https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L525-L540
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/charset.py
python
Charset.encoded_header_len
(self, s)
Return the length of the encoded header string.
Return the length of the encoded header string.
[ "Return", "the", "length", "of", "the", "encoded", "header", "string", "." ]
def encoded_header_len(self, s): """Return the length of the encoded header string.""" cset = self.get_output_charset() # The len(s) of a 7bit encoding is len(s) if self.header_encoding == BASE64: return email.base64mime.base64_len(s) + len(cset) + MISC_LEN elif self.header_encoding == QP: return email.quoprimime.header_quopri_len(s) + len(cset) + MISC_LEN elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) return min(lenb64, lenqp) + len(cset) + MISC_LEN else: return len(s)
[ "def", "encoded_header_len", "(", "self", ",", "s", ")", ":", "cset", "=", "self", ".", "get_output_charset", "(", ")", "# The len(s) of a 7bit encoding is len(s)", "if", "self", ".", "header_encoding", "==", "BASE64", ":", "return", "email", ".", "base64mime", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/charset.py#L332-L345
apache/trafodion
8455c839ad6b6d7b6e04edda5715053095b78046
core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py
python
Client.get
(self, tableName, row, column, attributes)
return self.recv_get()
Get a single TCell for the specified table, row, and column at the latest timestamp. Returns an empty list if no such value exists. @return value for specified row/column Parameters: - tableName: name of table - row: row key - column: column name - attributes: Get attributes
Get a single TCell for the specified table, row, and column at the latest timestamp. Returns an empty list if no such value exists.
[ "Get", "a", "single", "TCell", "for", "the", "specified", "table", "row", "and", "column", "at", "the", "latest", "timestamp", ".", "Returns", "an", "empty", "list", "if", "no", "such", "value", "exists", "." ]
def get(self, tableName, row, column, attributes): """ Get a single TCell for the specified table, row, and column at the latest timestamp. Returns an empty list if no such value exists. @return value for specified row/column Parameters: - tableName: name of table - row: row key - column: column name - attributes: Get attributes """ self.send_get(tableName, row, column, attributes) return self.recv_get()
[ "def", "get", "(", "self", ",", "tableName", ",", "row", ",", "column", ",", "attributes", ")", ":", "self", ".", "send_get", "(", "tableName", ",", "row", ",", "column", ",", "attributes", ")", "return", "self", ".", "recv_get", "(", ")" ]
https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py#L965-L979
electron/electron
8dfcf817e4182c48cd7e9d3471319c61224677e3
script/lib/git.py
python
join_patch
(patch)
return ''.join(remove_patch_filename(patch)).rstrip('\n') + '\n'
Joins and formats patch contents
Joins and formats patch contents
[ "Joins", "and", "formats", "patch", "contents" ]
def join_patch(patch): """Joins and formats patch contents""" return ''.join(remove_patch_filename(patch)).rstrip('\n') + '\n'
[ "def", "join_patch", "(", "patch", ")", ":", "return", "''", ".", "join", "(", "remove_patch_filename", "(", "patch", ")", ")", ".", "rstrip", "(", "'\\n'", ")", "+", "'\\n'" ]
https://github.com/electron/electron/blob/8dfcf817e4182c48cd7e9d3471319c61224677e3/script/lib/git.py#L210-L212
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/p4util/text.py
python
levenshtein
(seq1, seq2)
return thisrow[len(seq2) - 1]
Compute the Levenshtein distance between two strings.
Compute the Levenshtein distance between two strings.
[ "Compute", "the", "Levenshtein", "distance", "between", "two", "strings", "." ]
def levenshtein(seq1, seq2): """Compute the Levenshtein distance between two strings.""" oneago = None thisrow = list(range(1, len(seq2) + 1)) + [0] for x in range(len(seq1)): twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1] for y in range(len(seq2)): delcost = oneago[y] + 1 addcost = thisrow[y - 1] + 1 subcost = oneago[y - 1] + (seq1[x] != seq2[y]) thisrow[y] = min(delcost, addcost, subcost) return thisrow[len(seq2) - 1]
[ "def", "levenshtein", "(", "seq1", ",", "seq2", ")", ":", "oneago", "=", "None", "thisrow", "=", "list", "(", "range", "(", "1", ",", "len", "(", "seq2", ")", "+", "1", ")", ")", "+", "[", "0", "]", "for", "x", "in", "range", "(", "len", "(",...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/text.py#L211-L223
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/ccompiler.py
python
CCompiler._setup_compile
(self, outdir, macros, incdirs, sources, depends, extra)
return macros, objects, extra, pp_opts, build
Process arguments and decide which source files to compile.
Process arguments and decide which source files to compile.
[ "Process", "arguments", "and", "decide", "which", "source", "files", "to", "compile", "." ]
def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): """Process arguments and decide which source files to compile.""" if outdir is None: outdir = self.output_dir elif not isinstance(outdir, str): raise TypeError, "'output_dir' must be a string or None" if macros is None: macros = self.macros elif isinstance(macros, list): macros = macros + (self.macros or []) else: raise TypeError, "'macros' (if supplied) must be a list of tuples" if incdirs is None: incdirs = self.include_dirs elif isinstance(incdirs, (list, tuple)): incdirs = list(incdirs) + (self.include_dirs or []) else: raise TypeError, \ "'include_dirs' (if supplied) must be a list of strings" if extra is None: extra = [] # Get the list of expected output (object) files objects = self.object_filenames(sources, strip_dir=0, output_dir=outdir) assert len(objects) == len(sources) pp_opts = gen_preprocess_options(macros, incdirs) build = {} for i in range(len(sources)): src = sources[i] obj = objects[i] ext = os.path.splitext(src)[1] self.mkpath(os.path.dirname(obj)) build[obj] = (src, ext) return macros, objects, extra, pp_opts, build
[ "def", "_setup_compile", "(", "self", ",", "outdir", ",", "macros", ",", "incdirs", ",", "sources", ",", "depends", ",", "extra", ")", ":", "if", "outdir", "is", "None", ":", "outdir", "=", "self", ".", "output_dir", "elif", "not", "isinstance", "(", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/ccompiler.py#L329-L371
sunpinyin/sunpinyin
8a2c96e51ca7020398c26feab0af2afdfbbee8a6
wrapper/ibus/setup/main.py
python
MultiCheckDialog.dummy
(self)
a dummy func, i don't initialize myself upon other's request. instead, i will do it by myself.
a dummy func, i don't initialize myself upon other's request. instead, i will do it by myself.
[ "a", "dummy", "func", "i", "don", "t", "initialize", "myself", "upon", "other", "s", "request", ".", "instead", "i", "will", "do", "it", "by", "myself", "." ]
def dummy(self): """a dummy func, i don't initialize myself upon other's request. instead, i will do it by myself. """ pass
[ "def", "dummy", "(", "self", ")", ":", "pass" ]
https://github.com/sunpinyin/sunpinyin/blob/8a2c96e51ca7020398c26feab0af2afdfbbee8a6/wrapper/ibus/setup/main.py#L315-L319
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/activation.py
python
CELU.__init__
(self, alpha=1.0)
Initialize CELU.
Initialize CELU.
[ "Initialize", "CELU", "." ]
def __init__(self, alpha=1.0): """Initialize CELU.""" super(CELU, self).__init__() self.celu = P.CeLU(alpha=alpha)
[ "def", "__init__", "(", "self", ",", "alpha", "=", "1.0", ")", ":", "super", "(", "CELU", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "celu", "=", "P", ".", "CeLU", "(", "alpha", "=", "alpha", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/activation.py#L89-L92
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/distributions/distribution.py
python
_copy_fn
(fn)
return types.FunctionType( code=fn.__code__, globals=fn.__globals__, name=fn.__name__, argdefs=fn.__defaults__, closure=fn.__closure__)
Create a deep copy of fn. Args: fn: a callable Returns: A `FunctionType`: a deep copy of fn. Raises: TypeError: if `fn` is not a callable.
Create a deep copy of fn.
[ "Create", "a", "deep", "copy", "of", "fn", "." ]
def _copy_fn(fn): """Create a deep copy of fn. Args: fn: a callable Returns: A `FunctionType`: a deep copy of fn. Raises: TypeError: if `fn` is not a callable. """ if not callable(fn): raise TypeError("fn is not callable: %s" % fn) # The blessed way to copy a function. copy.deepcopy fails to create a # non-reference copy. Since: # types.FunctionType == type(lambda: None), # and the docstring for the function type states: # # function(code, globals[, name[, argdefs[, closure]]]) # # Create a function object from a code object and a dictionary. # ... # # Here we can use this to create a new function with the old function's # code, globals, closure, etc. return types.FunctionType( code=fn.__code__, globals=fn.__globals__, name=fn.__name__, argdefs=fn.__defaults__, closure=fn.__closure__)
[ "def", "_copy_fn", "(", "fn", ")", ":", "if", "not", "callable", "(", "fn", ")", ":", "raise", "TypeError", "(", "\"fn is not callable: %s\"", "%", "fn", ")", "# The blessed way to copy a function. copy.deepcopy fails to create a", "# non-reference copy. Since:", "# typ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/distributions/distribution.py#L58-L87
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/busco/BuscoAnalysis.py
python
BuscoAnalysis._set_checkpoint
(self, nb=None)
This function update the checkpoint file with the provided id or delete it if none is provided :param nb: the id of the checkpoint :type nb: int
This function update the checkpoint file with the provided id or delete it if none is provided :param nb: the id of the checkpoint :type nb: int
[ "This", "function", "update", "the", "checkpoint", "file", "with", "the", "provided", "id", "or", "delete", "it", "if", "none", "is", "provided", ":", "param", "nb", ":", "the", "id", "of", "the", "checkpoint", ":", "type", "nb", ":", "int" ]
def _set_checkpoint(self, nb=None): """ This function update the checkpoint file with the provided id or delete it if none is provided :param nb: the id of the checkpoint :type nb: int """ if nb: open('%scheckpoint.tmp' % self.mainout, 'w').write('%s.%s.%s' % (nb, self._mode, self._random)) else: if os.path.exists('%scheckpoint.tmp' % self.mainout): os.remove('%scheckpoint.tmp' % self.mainout)
[ "def", "_set_checkpoint", "(", "self", ",", "nb", "=", "None", ")", ":", "if", "nb", ":", "open", "(", "'%scheckpoint.tmp'", "%", "self", ".", "mainout", ",", "'w'", ")", ".", "write", "(", "'%s.%s.%s'", "%", "(", "nb", ",", "self", ".", "_mode", "...
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/busco/BuscoAnalysis.py#L802-L815
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pythonapi.py
python
PythonAPI.serialize_uncached
(self, obj)
return struct
Same as serialize_object(), but don't create a global variable, simply return a literal {i8* data, i32 length} structure.
Same as serialize_object(), but don't create a global variable, simply return a literal {i8* data, i32 length} structure.
[ "Same", "as", "serialize_object", "()", "but", "don", "t", "create", "a", "global", "variable", "simply", "return", "a", "literal", "{", "i8", "*", "data", "i32", "length", "}", "structure", "." ]
def serialize_uncached(self, obj): """ Same as serialize_object(), but don't create a global variable, simply return a literal {i8* data, i32 length} structure. """ # First make the array constant data = pickle.dumps(obj, protocol=-1) assert len(data) < 2**31 name = ".const.pickledata.%s" % (id(obj) if config.DIFF_IR == 0 else "DIFF_IR") bdata = cgutils.make_bytearray(data) arr = self.context.insert_unique_const(self.module, name, bdata) # Then populate the structure constant struct = ir.Constant.literal_struct([ arr.bitcast(self.voidptr), ir.Constant(ir.IntType(32), arr.type.pointee.count), ]) return struct
[ "def", "serialize_uncached", "(", "self", ",", "obj", ")", ":", "# First make the array constant", "data", "=", "pickle", ".", "dumps", "(", "obj", ",", "protocol", "=", "-", "1", ")", "assert", "len", "(", "data", ")", "<", "2", "**", "31", "name", "=...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pythonapi.py#L1379-L1395
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/input.py
python
DependencyGraphNode.DirectDependencies
(self, dependencies=None)
return dependencies
Returns a list of just direct dependencies.
Returns a list of just direct dependencies.
[ "Returns", "a", "list", "of", "just", "direct", "dependencies", "." ]
def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies
[ "def", "DirectDependencies", "(", "self", ",", "dependencies", "=", "None", ")", ":", "if", "dependencies", "==", "None", ":", "dependencies", "=", "[", "]", "for", "dependency", "in", "self", ".", "dependencies", ":", "# Check for None, corresponding to the root ...
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/input.py#L1302-L1312
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py
python
MockMethod.GetPossibleGroup
(self)
return group
Returns a possible group from the end of the call queue or None if no other methods are on the stack.
Returns a possible group from the end of the call queue or None if no other methods are on the stack.
[ "Returns", "a", "possible", "group", "from", "the", "end", "of", "the", "call", "queue", "or", "None", "if", "no", "other", "methods", "are", "on", "the", "stack", "." ]
def GetPossibleGroup(self): """Returns a possible group from the end of the call queue or None if no other methods are on the stack. """ # Remove this method from the tail of the queue so we can add it to a group. this_method = self._call_queue.pop() assert this_method == self # Determine if the tail of the queue is a group, or just a regular ordered # mock method. group = None try: group = self._call_queue[-1] except IndexError: pass return group
[ "def", "GetPossibleGroup", "(", "self", ")", ":", "# Remove this method from the tail of the queue so we can add it to a group.", "this_method", "=", "self", ".", "_call_queue", ".", "pop", "(", ")", "assert", "this_method", "==", "self", "# Determine if the tail of the queue...
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py#L645-L662
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/generator/msvs.py
python
_GenerateMSBuildFiltersFile
(filters_path, source_files, extension_to_rule_name)
Generate the filters file. This file is used by Visual Studio to organize the presentation of source files into folders. Arguments: filters_path: The path of the file to be created. source_files: The hierarchical structure of all the sources. extension_to_rule_name: A dictionary mapping file extensions to rules.
Generate the filters file.
[ "Generate", "the", "filters", "file", "." ]
def _GenerateMSBuildFiltersFile(filters_path, source_files, extension_to_rule_name): """Generate the filters file. This file is used by Visual Studio to organize the presentation of source files into folders. Arguments: filters_path: The path of the file to be created. source_files: The hierarchical structure of all the sources. extension_to_rule_name: A dictionary mapping file extensions to rules. """ filter_group = [] source_group = [] _AppendFiltersForMSBuild('', source_files, extension_to_rule_name, filter_group, source_group) if filter_group: content = ['Project', {'ToolsVersion': '4.0', 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003' }, ['ItemGroup'] + filter_group, ['ItemGroup'] + source_group ] easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True) elif os.path.exists(filters_path): # We don't need this filter anymore. Delete the old filter file. os.unlink(filters_path)
[ "def", "_GenerateMSBuildFiltersFile", "(", "filters_path", ",", "source_files", ",", "extension_to_rule_name", ")", ":", "filter_group", "=", "[", "]", "source_group", "=", "[", "]", "_AppendFiltersForMSBuild", "(", "''", ",", "source_files", ",", "extension_to_rule_n...
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/generator/msvs.py#L1876-L1903
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/linalg/decomp_svd.py
python
diagsvd
(s, M, N)
Construct the sigma matrix in SVD from singular values and size M, N. Parameters ---------- s : (M,) or (N,) array_like Singular values M : int Size of the matrix whose singular values are `s`. N : int Size of the matrix whose singular values are `s`. Returns ------- S : (M, N) ndarray The S-matrix in the singular value decomposition See Also -------- svd : Singular value decomposition of a matrix svdvals : Compute singular values of a matrix. Examples -------- >>> from scipy.linalg import diagsvd >>> vals = np.array([1, 2, 3]) # The array representing the computed svd >>> diagsvd(vals, 3, 4) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0]]) >>> diagsvd(vals, 4, 3) array([[1, 0, 0], [0, 2, 0], [0, 0, 3], [0, 0, 0]])
Construct the sigma matrix in SVD from singular values and size M, N.
[ "Construct", "the", "sigma", "matrix", "in", "SVD", "from", "singular", "values", "and", "size", "M", "N", "." ]
def diagsvd(s, M, N): """ Construct the sigma matrix in SVD from singular values and size M, N. Parameters ---------- s : (M,) or (N,) array_like Singular values M : int Size of the matrix whose singular values are `s`. N : int Size of the matrix whose singular values are `s`. Returns ------- S : (M, N) ndarray The S-matrix in the singular value decomposition See Also -------- svd : Singular value decomposition of a matrix svdvals : Compute singular values of a matrix. Examples -------- >>> from scipy.linalg import diagsvd >>> vals = np.array([1, 2, 3]) # The array representing the computed svd >>> diagsvd(vals, 3, 4) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0]]) >>> diagsvd(vals, 4, 3) array([[1, 0, 0], [0, 2, 0], [0, 0, 3], [0, 0, 0]]) """ part = diag(s) typ = part.dtype.char MorN = len(s) if MorN == M: return r_['-1', part, zeros((M, N-M), typ)] elif MorN == N: return r_[part, zeros((M-N, N), typ)] else: raise ValueError("Length of s must be M or N.")
[ "def", "diagsvd", "(", "s", ",", "M", ",", "N", ")", ":", "part", "=", "diag", "(", "s", ")", "typ", "=", "part", ".", "dtype", ".", "char", "MorN", "=", "len", "(", "s", ")", "if", "MorN", "==", "M", ":", "return", "r_", "[", "'-1'", ",", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/decomp_svd.py#L235-L281
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/nfs/module.py
python
Module._cmd_nfs_cluster_create
(self, cluster_id: str, placement: Optional[str] = None, ingress: Optional[bool] = None, virtual_ip: Optional[str] = None, port: Optional[int] = None)
return self.nfs.create_nfs_cluster(cluster_id=cluster_id, placement=placement, virtual_ip=virtual_ip, ingress=ingress, port=port)
Create an NFS Cluster
Create an NFS Cluster
[ "Create", "an", "NFS", "Cluster" ]
def _cmd_nfs_cluster_create(self, cluster_id: str, placement: Optional[str] = None, ingress: Optional[bool] = None, virtual_ip: Optional[str] = None, port: Optional[int] = None) -> Tuple[int, str, str]: """Create an NFS Cluster""" return self.nfs.create_nfs_cluster(cluster_id=cluster_id, placement=placement, virtual_ip=virtual_ip, ingress=ingress, port=port)
[ "def", "_cmd_nfs_cluster_create", "(", "self", ",", "cluster_id", ":", "str", ",", "placement", ":", "Optional", "[", "str", "]", "=", "None", ",", "ingress", ":", "Optional", "[", "bool", "]", "=", "None", ",", "virtual_ip", ":", "Optional", "[", "str",...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/nfs/module.py#L94-L103
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
Decimal.logical_xor
(self, other, context=None)
return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Applies an 'xor' operation between self and other's digits.
Applies an 'xor' operation between self and other's digits.
[ "Applies", "an", "xor", "operation", "between", "self", "and", "other", "s", "digits", "." ]
def logical_xor(self, other, context=None): """Applies an 'xor' operation between self and other's digits.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) if not self._islogical() or not other._islogical(): return context._raise_error(InvalidOperation) # fill to context.prec (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) return _dec_from_triple(0, result.lstrip('0') or '0', 0)
[ "def", "logical_xor", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "other", "=", "_convert_other", "(", "other", ",", "raiseit", "=", "True", ")", "if", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L3315-L3330
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/dtypes/common.py
python
is_bool_dtype
(arr_or_dtype)
return issubclass(dtype.type, np.bool_)
Check whether the provided array or dtype is of a boolean dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean : Whether or not the array or dtype is of a boolean dtype. Notes ----- An ExtensionArray is considered boolean when the ``_is_boolean`` attribute is set to True. Examples -------- >>> is_bool_dtype(str) False >>> is_bool_dtype(int) False >>> is_bool_dtype(bool) True >>> is_bool_dtype(np.bool) True >>> is_bool_dtype(np.array(['a', 'b'])) False >>> is_bool_dtype(pd.Series([1, 2])) False >>> is_bool_dtype(np.array([True, False])) True >>> is_bool_dtype(pd.Categorical([True, False])) True >>> is_bool_dtype(pd.SparseArray([True, False])) True
Check whether the provided array or dtype is of a boolean dtype.
[ "Check", "whether", "the", "provided", "array", "or", "dtype", "is", "of", "a", "boolean", "dtype", "." ]
def is_bool_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of a boolean dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean : Whether or not the array or dtype is of a boolean dtype. Notes ----- An ExtensionArray is considered boolean when the ``_is_boolean`` attribute is set to True. Examples -------- >>> is_bool_dtype(str) False >>> is_bool_dtype(int) False >>> is_bool_dtype(bool) True >>> is_bool_dtype(np.bool) True >>> is_bool_dtype(np.array(['a', 'b'])) False >>> is_bool_dtype(pd.Series([1, 2])) False >>> is_bool_dtype(np.array([True, False])) True >>> is_bool_dtype(pd.Categorical([True, False])) True >>> is_bool_dtype(pd.SparseArray([True, False])) True """ if arr_or_dtype is None: return False try: dtype = _get_dtype(arr_or_dtype) except TypeError: return False if isinstance(arr_or_dtype, CategoricalDtype): arr_or_dtype = arr_or_dtype.categories # now we use the special definition for Index if isinstance(arr_or_dtype, ABCIndexClass): # TODO(jreback) # we don't have a boolean Index class # so its object, we need to infer to # guess this return (arr_or_dtype.is_object and arr_or_dtype.inferred_type == 'boolean') elif is_extension_array_dtype(arr_or_dtype): dtype = getattr(arr_or_dtype, 'dtype', arr_or_dtype) return dtype._is_boolean return issubclass(dtype.type, np.bool_)
[ "def", "is_bool_dtype", "(", "arr_or_dtype", ")", ":", "if", "arr_or_dtype", "is", "None", ":", "return", "False", "try", ":", "dtype", "=", "_get_dtype", "(", "arr_or_dtype", ")", "except", "TypeError", ":", "return", "False", "if", "isinstance", "(", "arr_...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/common.py#L1578-L1640
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-digital/python/digital/psk_constellations.py
python
sd_psk_4_0x2_0_1
(x, Es=1)
return [-dist * x_im, dist * x_re]
| 00 | 01 | ------- | 10 | 11
| 00 | 01 | ------- | 10 | 11
[ "|", "00", "|", "01", "|", "-------", "|", "10", "|", "11" ]
def sd_psk_4_0x2_0_1(x, Es=1): ''' | 00 | 01 | ------- | 10 | 11 ''' x_re = x.real x_im = x.imag dist = Es * numpy.sqrt(2) return [-dist * x_im, dist * x_re]
[ "def", "sd_psk_4_0x2_0_1", "(", "x", ",", "Es", "=", "1", ")", ":", "x_re", "=", "x", ".", "real", "x_im", "=", "x", ".", "imag", "dist", "=", "Es", "*", "numpy", ".", "sqrt", "(", "2", ")", "return", "[", "-", "dist", "*", "x_im", ",", "dist...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-digital/python/digital/psk_constellations.py#L263-L272
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/basic_session_run_hooks.py
python
CheckpointSaverHook.__init__
(self, checkpoint_dir, save_secs=None, save_steps=None, saver=None, checkpoint_basename="model.ckpt", scaffold=None)
Initialize CheckpointSaverHook monitor. Args: checkpoint_dir: `str`, base directory for the checkpoint files. save_secs: `int`, save every N secs. save_steps: `int`, save every N steps. saver: `Saver` object, used for saving. checkpoint_basename: `str`, base name for the checkpoint files. scaffold: `Scaffold`, use to get saver object. Raises: ValueError: One of `save_steps` or `save_secs` should be set.
Initialize CheckpointSaverHook monitor.
[ "Initialize", "CheckpointSaverHook", "monitor", "." ]
def __init__(self, checkpoint_dir, save_secs=None, save_steps=None, saver=None, checkpoint_basename="model.ckpt", scaffold=None): """Initialize CheckpointSaverHook monitor. Args: checkpoint_dir: `str`, base directory for the checkpoint files. save_secs: `int`, save every N secs. save_steps: `int`, save every N steps. saver: `Saver` object, used for saving. checkpoint_basename: `str`, base name for the checkpoint files. scaffold: `Scaffold`, use to get saver object. Raises: ValueError: One of `save_steps` or `save_secs` should be set. """ logging.info("Create CheckpointSaverHook.") self._saver = saver self._checkpoint_dir = checkpoint_dir self._summary_writer = SummaryWriterCache.get(checkpoint_dir) self._save_path = os.path.join(checkpoint_dir, checkpoint_basename) self._scaffold = scaffold self._save_secs = save_secs self._save_steps = save_steps self._last_saved_time = None self._last_saved_step = None if save_steps is None and save_secs is None: raise ValueError("Either save_steps or save_secs should be provided") if (save_steps is not None) and (save_secs is not None): raise ValueError("Can not provide both save_steps and save_secs.")
[ "def", "__init__", "(", "self", ",", "checkpoint_dir", ",", "save_secs", "=", "None", ",", "save_steps", "=", "None", ",", "saver", "=", "None", ",", "checkpoint_basename", "=", "\"model.ckpt\"", ",", "scaffold", "=", "None", ")", ":", "logging", ".", "inf...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/basic_session_run_hooks.py#L142-L176
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/bench/jsmin_2_0_9.py
python
jsmin
(js)
return outs.getvalue()
returns a minified version of the javascript string
returns a minified version of the javascript string
[ "returns", "a", "minified", "version", "of", "the", "javascript", "string" ]
def jsmin(js): """ returns a minified version of the javascript string """ if not is_3: if cStringIO and not isinstance(js, unicode): # strings can use cStringIO for a 3x performance # improvement, but unicode (in python2) cannot klass = cStringIO.StringIO else: klass = StringIO.StringIO else: klass = io.StringIO ins = klass(js) outs = klass() JavascriptMinify(ins, outs).minify() return outs.getvalue()
[ "def", "jsmin", "(", "js", ")", ":", "if", "not", "is_3", ":", "if", "cStringIO", "and", "not", "isinstance", "(", "js", ",", "unicode", ")", ":", "# strings can use cStringIO for a 3x performance", "# improvement, but unicode (in python2) cannot", "klass", "=", "cS...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/bench/jsmin_2_0_9.py#L43-L59
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/util/profiler.py
python
Profiler.__enter__
(self)
Activate data collection.
Activate data collection.
[ "Activate", "data", "collection", "." ]
def __enter__(self): """ Activate data collection. """ self.enable()
[ "def", "__enter__", "(", "self", ")", ":", "self", ".", "enable", "(", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/profiler.py#L35-L39
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Token.spelling
(self)
return conf.lib.clang_getTokenSpelling(self._tu, self)
The spelling of this token. This is the textual representation of the token in source.
The spelling of this token.
[ "The", "spelling", "of", "this", "token", "." ]
def spelling(self): """The spelling of this token. This is the textual representation of the token in source. """ return conf.lib.clang_getTokenSpelling(self._tu, self)
[ "def", "spelling", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTokenSpelling", "(", "self", ".", "_tu", ",", "self", ")" ]
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2668-L2673
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/data/python/ops/grouping.py
python
GroupByWindowDataset._make_reduce_func
(self, reduce_func, input_dataset)
Make wrapping Defun for reduce_func.
Make wrapping Defun for reduce_func.
[ "Make", "wrapping", "Defun", "for", "reduce_func", "." ]
def _make_reduce_func(self, reduce_func, input_dataset): """Make wrapping Defun for reduce_func.""" @function.Defun(dtypes.int64, dtypes.variant) def tf_reduce_func(key, window_dataset_variant): """A wrapper for Defun that facilitates shape inference.""" key.set_shape([]) window_dataset = _VariantDataset(window_dataset_variant, input_dataset.output_types, input_dataset.output_shapes) if not isinstance(window_dataset, dataset_ops.Dataset): raise TypeError("`window_dataset` must return a `Dataset` object.") output_dataset = reduce_func(key, window_dataset) if not isinstance(output_dataset, dataset_ops.Dataset): raise TypeError("`reduce_func` must return a `Dataset` object.") self._output_types = output_dataset.output_types self._output_shapes = output_dataset.output_shapes return output_dataset._as_variant_tensor() # pylint: disable=protected-access self._reduce_func = tf_reduce_func self._reduce_func.add_to_graph(ops.get_default_graph())
[ "def", "_make_reduce_func", "(", "self", ",", "reduce_func", ",", "input_dataset", ")", ":", "@", "function", ".", "Defun", "(", "dtypes", ".", "int64", ",", "dtypes", ".", "variant", ")", "def", "tf_reduce_func", "(", "key", ",", "window_dataset_variant", "...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/data/python/ops/grouping.py#L161-L181
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/tools/release/common_includes.py
python
Step.Retry
(self, cb, retry_on=None, wait_plan=None)
Retry a function. Params: cb: The function to retry. retry_on: A callback that takes the result of the function and returns True if the function should be retried. A function throwing an exception is always retried. wait_plan: A list of waiting delays between retries in seconds. The maximum number of retries is len(wait_plan).
Retry a function. Params: cb: The function to retry. retry_on: A callback that takes the result of the function and returns True if the function should be retried. A function throwing an exception is always retried. wait_plan: A list of waiting delays between retries in seconds. The maximum number of retries is len(wait_plan).
[ "Retry", "a", "function", ".", "Params", ":", "cb", ":", "The", "function", "to", "retry", ".", "retry_on", ":", "A", "callback", "that", "takes", "the", "result", "of", "the", "function", "and", "returns", "True", "if", "the", "function", "should", "be"...
def Retry(self, cb, retry_on=None, wait_plan=None): """ Retry a function. Params: cb: The function to retry. retry_on: A callback that takes the result of the function and returns True if the function should be retried. A function throwing an exception is always retried. wait_plan: A list of waiting delays between retries in seconds. The maximum number of retries is len(wait_plan). """ retry_on = retry_on or (lambda x: False) wait_plan = list(wait_plan or []) wait_plan.reverse() while True: got_exception = False try: result = cb() except NoRetryException as e: raise e except Exception as e: got_exception = e if got_exception or retry_on(result): if not wait_plan: # pragma: no cover raise Exception("Retried too often. Giving up. Reason: %s" % str(got_exception)) wait_time = wait_plan.pop() print("Waiting for %f seconds." % wait_time) self._side_effect_handler.Sleep(wait_time) print("Retrying...") else: return result
[ "def", "Retry", "(", "self", ",", "cb", ",", "retry_on", "=", "None", ",", "wait_plan", "=", "None", ")", ":", "retry_on", "=", "retry_on", "or", "(", "lambda", "x", ":", "False", ")", "wait_plan", "=", "list", "(", "wait_plan", "or", "[", "]", ")"...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/tools/release/common_includes.py#L464-L494
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
BooleanVar.get
(self)
Return the value of the variable as a bool.
Return the value of the variable as a bool.
[ "Return", "the", "value", "of", "the", "variable", "as", "a", "bool", "." ]
def get(self): """Return the value of the variable as a bool.""" try: return self._tk.getboolean(self._tk.globalgetvar(self._name)) except TclError: raise ValueError("invalid literal for getboolean()")
[ "def", "get", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_tk", ".", "getboolean", "(", "self", ".", "_tk", ".", "globalgetvar", "(", "self", ".", "_name", ")", ")", "except", "TclError", ":", "raise", "ValueError", "(", "\"invalid liter...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L551-L556
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/tensorboard/plugins/trace/trace.py
python
find_multiline_statements
(source)
return line2start
Parses the python source and finds multiline statements. Based on counting the number of open and closed parenthesis on each line. Args: source: The source code string. Returns: A dict that maps a line index A to a line index B, where A is the end of a multiline statement and B is the start. Line indexing is 0-based.
Parses the python source and finds multiline statements.
[ "Parses", "the", "python", "source", "and", "finds", "multiline", "statements", "." ]
def find_multiline_statements(source): """Parses the python source and finds multiline statements. Based on counting the number of open and closed parenthesis on each line. Args: source: The source code string. Returns: A dict that maps a line index A to a line index B, where A is the end of a multiline statement and B is the start. Line indexing is 0-based. """ # Get the AST. tree = parser.suite(source) line2paren_count = [0] * (source.count('\n') + 1) _count_brackets_braces_parenthesis(tree.totuple(True), line2paren_count) line2start = {} for end in range(len(line2paren_count)): if line2paren_count[end] >= 0: # This is not the end of a multiline statement. continue cumulative_paren_count = 0 for start in range(end, -1, -1): cumulative_paren_count += line2paren_count[start] if cumulative_paren_count == 0: line2start[end] = start break return line2start
[ "def", "find_multiline_statements", "(", "source", ")", ":", "# Get the AST.", "tree", "=", "parser", ".", "suite", "(", "source", ")", "line2paren_count", "=", "[", "0", "]", "*", "(", "source", ".", "count", "(", "'\\n'", ")", "+", "1", ")", "_count_br...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tensorboard/plugins/trace/trace.py#L105-L133
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/multi.py
python
MultiIndex.is_monotonic_decreasing
(self)
return self[::-1].is_monotonic_increasing
return if the index is monotonic decreasing (only equal or decreasing) values.
return if the index is monotonic decreasing (only equal or decreasing) values.
[ "return", "if", "the", "index", "is", "monotonic", "decreasing", "(", "only", "equal", "or", "decreasing", ")", "values", "." ]
def is_monotonic_decreasing(self) -> bool: """ return if the index is monotonic decreasing (only equal or decreasing) values. """ # monotonic decreasing if and only if reverse is monotonic increasing return self[::-1].is_monotonic_increasing
[ "def", "is_monotonic_decreasing", "(", "self", ")", "->", "bool", ":", "# monotonic decreasing if and only if reverse is monotonic increasing", "return", "self", "[", ":", ":", "-", "1", "]", ".", "is_monotonic_increasing" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/multi.py#L1576-L1582
fengbingchun/NN_Test
d6305825d5273e4569ccd1eda9ffa2a9c72e18d2
src/libsvm/python/svmutil.py
python
svm_read_problem
(data_file_name)
return (prob_y, prob_x)
svm_read_problem(data_file_name) -> [y, x] Read LIBSVM-format data from data_file_name and return labels y and data instances x.
svm_read_problem(data_file_name) -> [y, x]
[ "svm_read_problem", "(", "data_file_name", ")", "-", ">", "[", "y", "x", "]" ]
def svm_read_problem(data_file_name): """ svm_read_problem(data_file_name) -> [y, x] Read LIBSVM-format data from data_file_name and return labels y and data instances x. """ prob_y = [] prob_x = [] for line in open(data_file_name): line = line.split(None, 1) # In case an instance with all zero features if len(line) == 1: line += [''] label, features = line xi = {} for e in features.split(): ind, val = e.split(":") xi[int(ind)] = float(val) prob_y += [float(label)] prob_x += [xi] return (prob_y, prob_x)
[ "def", "svm_read_problem", "(", "data_file_name", ")", ":", "prob_y", "=", "[", "]", "prob_x", "=", "[", "]", "for", "line", "in", "open", "(", "data_file_name", ")", ":", "line", "=", "line", ".", "split", "(", "None", ",", "1", ")", "# In case an ins...
https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/libsvm/python/svmutil.py#L14-L34
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/markupsafe/__init__.py
python
Markup.unescape
(self)
return _entity_re.sub(handle_match, text_type(self))
r"""Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>'
r"""Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities:
[ "r", "Unescape", "markup", "again", "into", "an", "text_type", "string", ".", "This", "also", "resolves", "known", "HTML4", "and", "XHTML", "entities", ":" ]
def unescape(self): r"""Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>' """ from markupsafe._constants import HTML_ENTITIES def handle_match(m): name = m.group(1) if name in HTML_ENTITIES: return unichr(HTML_ENTITIES[name]) try: if name[:2] in ('#x', '#X'): return unichr(int(name[2:], 16)) elif name.startswith('#'): return unichr(int(name[1:])) except ValueError: pass return u'' return _entity_re.sub(handle_match, text_type(self))
[ "def", "unescape", "(", "self", ")", ":", "from", "markupsafe", ".", "_constants", "import", "HTML_ENTITIES", "def", "handle_match", "(", "m", ")", ":", "name", "=", "m", ".", "group", "(", "1", ")", "if", "name", "in", "HTML_ENTITIES", ":", "return", ...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/markupsafe/__init__.py#L123-L143
stan-dev/math
5fd79f89933269a4ca4d8dd1fde2a36d53d4768c
lib/boost_1.75.0/tools/build/src/build/generators.py
python
register_standard
(id, source_types, target_types, requirements = [])
return g
Creates new instance of the 'generator' class and registers it. Returns the creates instance. Rationale: the instance is returned so that it's possible to first register a generator and then call 'run' method on that generator, bypassing all generator selection.
Creates new instance of the 'generator' class and registers it. Returns the creates instance. Rationale: the instance is returned so that it's possible to first register a generator and then call 'run' method on that generator, bypassing all generator selection.
[ "Creates", "new", "instance", "of", "the", "generator", "class", "and", "registers", "it", ".", "Returns", "the", "creates", "instance", ".", "Rationale", ":", "the", "instance", "is", "returned", "so", "that", "it", "s", "possible", "to", "first", "register...
def register_standard (id, source_types, target_types, requirements = []): """ Creates new instance of the 'generator' class and registers it. Returns the creates instance. Rationale: the instance is returned so that it's possible to first register a generator and then call 'run' method on that generator, bypassing all generator selection. """ g = Generator (id, False, source_types, target_types, requirements) register (g) return g
[ "def", "register_standard", "(", "id", ",", "source_types", ",", "target_types", ",", "requirements", "=", "[", "]", ")", ":", "g", "=", "Generator", "(", "id", ",", "False", ",", "source_types", ",", "target_types", ",", "requirements", ")", "register", "...
https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/generators.py#L723-L732
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
PlatformInformation.GetOperatingSystemFamilyName
(*args, **kwargs)
return _misc_.PlatformInformation_GetOperatingSystemFamilyName(*args, **kwargs)
GetOperatingSystemFamilyName(self) -> String
GetOperatingSystemFamilyName(self) -> String
[ "GetOperatingSystemFamilyName", "(", "self", ")", "-", ">", "String" ]
def GetOperatingSystemFamilyName(*args, **kwargs): """GetOperatingSystemFamilyName(self) -> String""" return _misc_.PlatformInformation_GetOperatingSystemFamilyName(*args, **kwargs)
[ "def", "GetOperatingSystemFamilyName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "PlatformInformation_GetOperatingSystemFamilyName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L1109-L1111
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py
python
sum_gradients_all_reduce
(dev_prefixes, replica_grads, num_workers, alg, num_shards, gpu_indices)
return new_replica_grads
Apply all-reduce algorithm over specified gradient tensors. Args: dev_prefixes: list of prefix strings to use to generate PS device names. replica_grads: the gradients to reduce. num_workers: number of worker processes across entire job. alg: the all-reduce algorithm to apply. num_shards: alg-specific sharding factor. gpu_indices: indices of local GPUs in order usable for ring-reduce. Returns: list of reduced tensors
Apply all-reduce algorithm over specified gradient tensors.
[ "Apply", "all", "-", "reduce", "algorithm", "over", "specified", "gradient", "tensors", "." ]
def sum_gradients_all_reduce(dev_prefixes, replica_grads, num_workers, alg, num_shards, gpu_indices): """Apply all-reduce algorithm over specified gradient tensors. Args: dev_prefixes: list of prefix strings to use to generate PS device names. replica_grads: the gradients to reduce. num_workers: number of worker processes across entire job. alg: the all-reduce algorithm to apply. num_shards: alg-specific sharding factor. gpu_indices: indices of local GPUs in order usable for ring-reduce. Returns: list of reduced tensors """ alg_contains_shuffle = any(n in alg for n in ['pscpu', 'psgpu']) is_hierarchical = '/' in alg if 'pscpu' in alg: aux_devices = [prefix + '/cpu:0' for prefix in dev_prefixes] elif 'psgpu' in alg: aux_devices = [ prefix + '/gpu:%d' % i for i in range(len(gpu_indices)) for prefix in dev_prefixes ] else: aux_devices = ['/job:localhost/cpu:0'] # Auxiliary devices for hierarchical all-reduces. aux_device_groups = group_device_names( aux_devices, num_shards if alg_contains_shuffle else 1) group_index = 0 reduced_gv_list = [] for grad_and_vars in zip(*replica_grads): reduced_gv_list.append( sum_grad_and_var_all_reduce( grad_and_vars, num_workers, alg, gpu_indices, aux_devices if is_hierarchical else aux_device_groups[group_index], num_shards)) group_index = (group_index + 1) % len(aux_device_groups) new_replica_grads = [list(x) for x in zip(*reduced_gv_list)] return new_replica_grads
[ "def", "sum_gradients_all_reduce", "(", "dev_prefixes", ",", "replica_grads", ",", "num_workers", ",", "alg", ",", "num_shards", ",", "gpu_indices", ")", ":", "alg_contains_shuffle", "=", "any", "(", "n", "in", "alg", "for", "n", "in", "[", "'pscpu'", ",", "...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py#L452-L491
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf_kafka/versioneer.py
python
get_cmdclass
()
return cmds
Get the custom setuptools/distutils subclasses used by Versioneer.
Get the custom setuptools/distutils subclasses used by Versioneer.
[ "Get", "the", "custom", "setuptools", "/", "distutils", "subclasses", "used", "by", "Versioneer", "." ]
def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join( self.build_lib, cfg.versionfile_build ) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write( LONG % { "DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, } ) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if "py2exe" in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write( LONG % { "DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, } ) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file( target_versionfile, self._versioneer_generated_versions ) cmds["sdist"] = cmd_sdist return cmds
[ "def", "get_cmdclass", "(", ")", ":", "if", "\"versioneer\"", "in", "sys", ".", "modules", ":", "del", "sys", ".", "modules", "[", "\"versioneer\"", "]", "# this fixes the \"python setup.py develop\" case (also 'install' and", "# 'easy_install .'), in which subdependencies of...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf_kafka/versioneer.py#L1540-L1721
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/DecisionTree.py
python
DecisionTreeClassificationModel.classify
(self, X)
return self.internal.classify(*get_data(x))
Gets the classification results for the input sample. :param X: the input vectors, put into a matrix. The values will be converted to ``dtype=np.float32``. If a sparse matrix is passed in, it will be converted to a sparse ``csr_matrix``. :type X: {array-like, sparse matrix} of shape (n_samples, n_features) :return: the predictions of class probability for each input vector. :rtype: *generator of ndarray of shape (n_samples, n_classes)*
Gets the classification results for the input sample.
[ "Gets", "the", "classification", "results", "for", "the", "input", "sample", "." ]
def classify(self, X): """Gets the classification results for the input sample. :param X: the input vectors, put into a matrix. The values will be converted to ``dtype=np.float32``. If a sparse matrix is passed in, it will be converted to a sparse ``csr_matrix``. :type X: {array-like, sparse matrix} of shape (n_samples, n_features) :return: the predictions of class probability for each input vector. :rtype: *generator of ndarray of shape (n_samples, n_classes)* """ x = convert_data(X) return self.internal.classify(*get_data(x))
[ "def", "classify", "(", "self", ",", "X", ")", ":", "x", "=", "convert_data", "(", "X", ")", "return", "self", ".", "internal", ".", "classify", "(", "*", "get_data", "(", "x", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/DecisionTree.py#L30-L42
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/data_flow_ops.py
python
QueueBase._scope_vals
(self, vals)
Return a list of values to pass to `name_scope()`. Args: vals: A tensor, a list or tuple of tensors, or a dictionary. Returns: The values in vals as a list.
Return a list of values to pass to `name_scope()`.
[ "Return", "a", "list", "of", "values", "to", "pass", "to", "name_scope", "()", "." ]
def _scope_vals(self, vals): """Return a list of values to pass to `name_scope()`. Args: vals: A tensor, a list or tuple of tensors, or a dictionary. Returns: The values in vals as a list. """ if isinstance(vals, (list, tuple)): return vals elif isinstance(vals, dict): return vals.values() else: return [vals]
[ "def", "_scope_vals", "(", "self", ",", "vals", ")", ":", "if", "isinstance", "(", "vals", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "vals", "elif", "isinstance", "(", "vals", ",", "dict", ")", ":", "return", "vals", ".", "values", "...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L282-L296
xiaolonw/caffe-video_triplet
c39ea1ad6e937ccf7deba4510b7e555165abf05f
scripts/cpp_lint.py
python
IsBlankLine
(line)
return not line or line.isspace()
Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank.
Returns true if the given line is blank.
[ "Returns", "true", "if", "the", "given", "line", "is", "blank", "." ]
def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace()
[ "def", "IsBlankLine", "(", "line", ")", ":", "return", "not", "line", "or", "line", ".", "isspace", "(", ")" ]
https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/scripts/cpp_lint.py#L2369-L2381
taskflow/taskflow
f423a100a70b275f6e7331bc96537a3fe172e8d7
3rd-party/tbb/python/tbb/pool.py
python
Pool.apply_async
(self, func, args=(), kwds=dict(), callback=None)
return apply_result
A variant of the apply() method which returns an ApplyResult object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready, callback is applied to it (unless the call failed). callback should complete immediately since otherwise the thread which handles the results will get blocked.
A variant of the apply() method which returns an ApplyResult object.
[ "A", "variant", "of", "the", "apply", "()", "method", "which", "returns", "an", "ApplyResult", "object", "." ]
def apply_async(self, func, args=(), kwds=dict(), callback=None): """A variant of the apply() method which returns an ApplyResult object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready, callback is applied to it (unless the call failed). callback should complete immediately since otherwise the thread which handles the results will get blocked.""" assert not self._closed # No lock here. We assume it's atomic... apply_result = ApplyResult(callback=callback) job = Job(func, args, kwds, apply_result) self._tasks.run(job) return apply_result
[ "def", "apply_async", "(", "self", ",", "func", ",", "args", "=", "(", ")", ",", "kwds", "=", "dict", "(", ")", ",", "callback", "=", "None", ")", ":", "assert", "not", "self", ".", "_closed", "# No lock here. We assume it's atomic...", "apply_result", "="...
https://github.com/taskflow/taskflow/blob/f423a100a70b275f6e7331bc96537a3fe172e8d7/3rd-party/tbb/python/tbb/pool.py#L143-L156
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sarray.py
python
SArray.filter
(self, fn, skip_undefined=True, seed=None)
Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element to true, this element is copied to the new SArray. If not, it isn't. Throws an exception if the return type of `fn` is not castable to a boolean value. Parameters ---------- fn : function Function that filters the SArray. Must evaluate to bool or int. skip_undefined : bool, optional If True, will not apply fn to any undefined values. seed : int, optional Used as the seed if a random number generator is included in fn. Returns ------- out : SArray The SArray filtered by fn. Each element of the SArray is of type int. Examples -------- >>> sa = graphlab.SArray([1,2,3]) >>> sa.filter(lambda x: x < 3) dtype: int Rows: 2 [1, 2]
Filter this SArray by a function.
[ "Filter", "this", "SArray", "by", "a", "function", "." ]
def filter(self, fn, skip_undefined=True, seed=None): """ Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element to true, this element is copied to the new SArray. If not, it isn't. Throws an exception if the return type of `fn` is not castable to a boolean value. Parameters ---------- fn : function Function that filters the SArray. Must evaluate to bool or int. skip_undefined : bool, optional If True, will not apply fn to any undefined values. seed : int, optional Used as the seed if a random number generator is included in fn. Returns ------- out : SArray The SArray filtered by fn. Each element of the SArray is of type int. Examples -------- >>> sa = graphlab.SArray([1,2,3]) >>> sa.filter(lambda x: x < 3) dtype: int Rows: 2 [1, 2] """ assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) with cython_context(): return SArray(_proxy=self.__proxy__.filter(fn, skip_undefined, seed))
[ "def", "filter", "(", "self", ",", "fn", ",", "skip_undefined", "=", "True", ",", "seed", "=", "None", ")", ":", "assert", "callable", "(", "fn", ")", ",", "\"Input must be callable\"", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", ...
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L1897-L1937
kitao/pyxel
f58bd6fe84153219a1e5edc506ae9606614883dc
pyxel/examples/07_snake.py
python
Snake.check_apple
(self)
Check whether the snake is on an apple.
Check whether the snake is on an apple.
[ "Check", "whether", "the", "snake", "is", "on", "an", "apple", "." ]
def check_apple(self): """Check whether the snake is on an apple.""" if self.snake[0] == self.apple: self.score += 1 self.snake.append(self.popped_point) self.generate_apple() pyxel.play(0, 0)
[ "def", "check_apple", "(", "self", ")", ":", "if", "self", ".", "snake", "[", "0", "]", "==", "self", ".", "apple", ":", "self", ".", "score", "+=", "1", "self", ".", "snake", ".", "append", "(", "self", ".", "popped_point", ")", "self", ".", "ge...
https://github.com/kitao/pyxel/blob/f58bd6fe84153219a1e5edc506ae9606614883dc/pyxel/examples/07_snake.py#L124-L132
godlikepanos/anki-3d-engine
e2f65e5045624492571ea8527a4dbf3fad8d2c0a
ThirdParty/Glslang/build_info.py
python
deduce_software_version
(directory)
Returns a software version number parsed from the CHANGES.md file in the given directory. The CHANGES.md file describes most recent versions first.
Returns a software version number parsed from the CHANGES.md file in the given directory.
[ "Returns", "a", "software", "version", "number", "parsed", "from", "the", "CHANGES", ".", "md", "file", "in", "the", "given", "directory", "." ]
def deduce_software_version(directory): """Returns a software version number parsed from the CHANGES.md file in the given directory. The CHANGES.md file describes most recent versions first. """ # Match the first well-formed version-and-date line. # Allow trailing whitespace in the checked-out source code has # unexpected carriage returns on a linefeed-only system such as # Linux. pattern = re.compile(r'^#* +(\d+)\.(\d+)\.(\d+)(-\w+)? (\d\d\d\d-\d\d-\d\d)? *$') changes_file = os.path.join(directory, 'CHANGES.md') with open(changes_file, mode='r') as f: for line in f.readlines(): match = pattern.match(line) if match: flavor = match.group(4) if flavor == None: flavor = "" return { "major": match.group(1), "minor": match.group(2), "patch": match.group(3), "flavor": flavor.lstrip("-"), "-flavor": flavor, "date": match.group(5), } raise Exception('No version number found in {}'.format(changes_file))
[ "def", "deduce_software_version", "(", "directory", ")", ":", "# Match the first well-formed version-and-date line.", "# Allow trailing whitespace in the checked-out source code has", "# unexpected carriage returns on a linefeed-only system such as", "# Linux.", "pattern", "=", "re", ".", ...
https://github.com/godlikepanos/anki-3d-engine/blob/e2f65e5045624492571ea8527a4dbf3fad8d2c0a/ThirdParty/Glslang/build_info.py#L86-L114
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/bindings/python/clang/cindex.py
python
TranslationUnit.from_ast_file
(cls, filename, index=None)
return cls(ptr=ptr, index=index)
Create a TranslationUnit instance from a saved AST file. A previously-saved AST file (provided with -emit-ast or TranslationUnit.save()) is loaded from the filename specified. If the file cannot be loaded, a TranslationUnitLoadError will be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created.
Create a TranslationUnit instance from a saved AST file.
[ "Create", "a", "TranslationUnit", "instance", "from", "a", "saved", "AST", "file", "." ]
def from_ast_file(cls, filename, index=None): """Create a TranslationUnit instance from a saved AST file. A previously-saved AST file (provided with -emit-ast or TranslationUnit.save()) is loaded from the filename specified. If the file cannot be loaded, a TranslationUnitLoadError will be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created. """ if index is None: index = Index.create() ptr = conf.lib.clang_createTranslationUnit(index, filename) if not ptr: raise TranslationUnitLoadError(filename) return cls(ptr=ptr, index=index)
[ "def", "from_ast_file", "(", "cls", ",", "filename", ",", "index", "=", "None", ")", ":", "if", "index", "is", "None", ":", "index", "=", "Index", ".", "create", "(", ")", "ptr", "=", "conf", ".", "lib", ".", "clang_createTranslationUnit", "(", "index"...
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L2806-L2825
NVIDIAGameWorks/kaolin
e5148d05e9c1e2ce92a07881ce3593b1c5c3f166
kaolin/ops/mesh/check_sign.py
python
check_sign
(verts, faces, points, hash_resolution=512)
return torch.stack(results)
r"""Checks if a set of points is contained inside a mesh. Each batch takes in v vertices, f faces of a watertight trimesh, and p points to check if they are inside the mesh. Shoots a ray from each point to be checked and calculates the number of intersections between the ray and triangles in the mesh. Uses the parity of the number of intersections to determine if the point is inside the mesh. Args: verts (torch.Tensor): vertices, of shape :math:`(\text{batch_size}, \text{num_vertices}, 3)`. faces (torch.Tensor): faces, of shape :math:`(\text{num_faces}, 3)`. points (torch.Tensor): points to check, of shape :math:`(\text{batch_size}, \text{num_points}, 3)`. hash_resolution (int): resolution used to check the points sign. Returns: (torch.BoolTensor): Tensor indicating whether each point is inside the mesh, of shape :math:`(\text{batch_size}, \text{num_vertices})`. Example: >>> device = 'cuda' if torch.cuda.is_available() else 'cpu' >>> verts = torch.tensor([[[0., 0., 0.], ... [1., 0.5, 1.], ... [0.5, 1., 1.], ... [1., 1., 0.5]]], device = device) >>> faces = torch.tensor([[0, 3, 1], ... [0, 1, 2], ... [0, 2, 3], ... [3, 2, 1]], device = device) >>> axis = torch.linspace(0.1, 0.9, 3, device = device) >>> p_x, p_y, p_z = torch.meshgrid(axis + 0.01, axis + 0.02, axis + 0.03) >>> points = torch.cat((p_x.unsqueeze(-1), p_y.unsqueeze(-1), p_z.unsqueeze(-1)), dim=3) >>> points = points.view(1, -1, 3) >>> check_sign(verts, faces, points) tensor([[ True, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, True, False, False, False, False, False, True, False, True, False]], device='cuda:0')
r"""Checks if a set of points is contained inside a mesh.
[ "r", "Checks", "if", "a", "set", "of", "points", "is", "contained", "inside", "a", "mesh", "." ]
def check_sign(verts, faces, points, hash_resolution=512): r"""Checks if a set of points is contained inside a mesh. Each batch takes in v vertices, f faces of a watertight trimesh, and p points to check if they are inside the mesh. Shoots a ray from each point to be checked and calculates the number of intersections between the ray and triangles in the mesh. Uses the parity of the number of intersections to determine if the point is inside the mesh. Args: verts (torch.Tensor): vertices, of shape :math:`(\text{batch_size}, \text{num_vertices}, 3)`. faces (torch.Tensor): faces, of shape :math:`(\text{num_faces}, 3)`. points (torch.Tensor): points to check, of shape :math:`(\text{batch_size}, \text{num_points}, 3)`. hash_resolution (int): resolution used to check the points sign. Returns: (torch.BoolTensor): Tensor indicating whether each point is inside the mesh, of shape :math:`(\text{batch_size}, \text{num_vertices})`. Example: >>> device = 'cuda' if torch.cuda.is_available() else 'cpu' >>> verts = torch.tensor([[[0., 0., 0.], ... [1., 0.5, 1.], ... [0.5, 1., 1.], ... [1., 1., 0.5]]], device = device) >>> faces = torch.tensor([[0, 3, 1], ... [0, 1, 2], ... [0, 2, 3], ... [3, 2, 1]], device = device) >>> axis = torch.linspace(0.1, 0.9, 3, device = device) >>> p_x, p_y, p_z = torch.meshgrid(axis + 0.01, axis + 0.02, axis + 0.03) >>> points = torch.cat((p_x.unsqueeze(-1), p_y.unsqueeze(-1), p_z.unsqueeze(-1)), dim=3) >>> points = points.view(1, -1, 3) >>> check_sign(verts, faces, points) tensor([[ True, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, True, False, False, False, False, False, True, False, True, False]], device='cuda:0') """ assert verts.device == points.device assert faces.device == points.device device = points.device if not verts.dtype == torch.float32: raise TypeError(f"Expected verts entries to be torch.float32 " f"but got {verts.dtype}.") if not faces.dtype == torch.int64: raise TypeError(f"Expected faces entries to be torch.int64 " f"but got {faces.dtype}.") if not points.dtype == torch.float32: raise TypeError(f"Expected points entries to be torch.float32 " f"but got {points.dtype}.") if not isinstance(hash_resolution, int): raise TypeError(f"Expected hash_resolution to be int " f"but got {type(hash_resolution)}.") if verts.ndim != 3: verts_dim = verts.ndim raise ValueError(f"Expected verts to have 3 dimensions " f"but got {verts_dim} dimensions.") if faces.ndim != 2: faces_dim = faces.ndim raise ValueError(f"Expected faces to have 2 dimensions " f"but got {faces_dim} dimensions.") if points.ndim != 3: points_dim = points.ndim raise ValueError(f"Expected points to have 3 dimensions " f"but got {points_dim} dimensions.") if verts.shape[2] != 3: raise ValueError(f"Expected verts to have 3 coordinates " f"but got {verts.shape[2]} coordinates.") if faces.shape[1] != 3: raise ValueError(f"Expected faces to have 3 vertices " f"but got {faces.shape[1]} vertices.") if points.shape[2] != 3: raise ValueError(f"Expected points to have 3 coordinates " f"but got {points.shape[2]} coordinates.") xlen = verts[..., 0].max(-1)[0] - verts[..., 0].min(-1)[0] ylen = verts[..., 1].max(-1)[0] - verts[..., 1].min(-1)[0] zlen = verts[..., 2].max(-1)[0] - verts[..., 2].min(-1)[0] maxlen = torch.max(torch.stack([xlen, ylen, zlen]), 0)[0] verts = verts / maxlen.view(-1, 1, 1) points = points / maxlen.view(-1, 1, 1) results = [] if device.type == 'cuda': for i_batch in range(verts.shape[0]): contains = _unbatched_check_sign_cuda(verts[i_batch], faces, points[i_batch]) results.append(contains) else: for i_batch in range(verts.shape[0]): intersector = _UnbatchedMeshIntersector(verts[i_batch], faces, hash_resolution) contains = intersector.query(points[i_batch].data.cpu().numpy()) results.append(torch.tensor(contains).to(device)) return torch.stack(results)
[ "def", "check_sign", "(", "verts", ",", "faces", ",", "points", ",", "hash_resolution", "=", "512", ")", ":", "assert", "verts", ".", "device", "==", "points", ".", "device", "assert", "faces", ".", "device", "==", "points", ".", "device", "device", "=",...
https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/ops/mesh/check_sign.py#L61-L163
flexflow/FlexFlow
581fad8ba8d10a16a3102ee2b406b0319586df24
examples/python/pytorch/resnet_torch.py
python
wide_resnet50_2
(pretrained: bool = False, progress: bool = True, **kwargs: Any)
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 channels, and in Wide ResNet-50-2 has 2048-1024-2048. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
[ "r", "Wide", "ResNet", "-", "50", "-", "2", "model", "from", "Wide", "Residual", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1605", ".", "07146", ".", "pdf", ">", "_", "." ]
def wide_resnet50_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 channels, and in Wide ResNet-50-2 has 2048-1024-2048. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ kwargs['width_per_group'] = 64 * 2 return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
[ "def", "wide_resnet50_2", "(", "pretrained", ":", "bool", "=", "False", ",", "progress", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "ResNet", ":", "kwargs", "[", "'width_per_group'", "]", "=", "64", "*", "2", "return", ...
https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/examples/python/pytorch/resnet_torch.py#L333-L348
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
native_client_sdk/src/build_tools/buildbot_common.py
python
Archive
(filename, bucket_path, cwd=None, step_link=True)
Upload the given filename to Google Store.
Upload the given filename to Google Store.
[ "Upload", "the", "given", "filename", "to", "Google", "Store", "." ]
def Archive(filename, bucket_path, cwd=None, step_link=True): """Upload the given filename to Google Store.""" full_dst = 'gs://%s/%s' % (bucket_path, filename) # Since GetGsutil() might just return 'gsutil' and expect it to be looked # up in the PATH, we must pass shell=True on windows. # Without shell=True the windows implementation of subprocess.call will not # search the PATH for the executable: http://bugs.python.org/issue8557 shell = getos.GetPlatform() == 'win' cmd = [GetGsutil(), 'cp', '-a', 'public-read', filename, full_dst] Run(cmd, shell=shell, cwd=cwd) url = 'https://storage.googleapis.com/%s/%s' % (bucket_path, filename) if step_link: print '@@@STEP_LINK@download@%s@@@' % url sys.stdout.flush()
[ "def", "Archive", "(", "filename", ",", "bucket_path", ",", "cwd", "=", "None", ",", "step_link", "=", "True", ")", ":", "full_dst", "=", "'gs://%s/%s'", "%", "(", "bucket_path", ",", "filename", ")", "# Since GetGsutil() might just return 'gsutil' and expect it to ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/build_tools/buildbot_common.py#L196-L211
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/collector.py
python
PyTracer._trace
(self, frame, event, arg_unused)
return self._trace
The trace function passed to sys.settrace.
The trace function passed to sys.settrace.
[ "The", "trace", "function", "passed", "to", "sys", ".", "settrace", "." ]
def _trace(self, frame, event, arg_unused): """The trace function passed to sys.settrace.""" #print("trace event: %s %r @%d" % ( # event, frame.f_code.co_filename, frame.f_lineno)) if self.last_exc_back: if frame == self.last_exc_back: # Someone forgot a return event. if self.arcs and self.cur_file_data: pair = (self.last_line, -self.last_exc_firstlineno) self.cur_file_data[pair] = None self.cur_file_data, self.last_line = self.data_stack.pop() self.last_exc_back = None if event == 'call': # Entering a new function context. Decide if we should trace # in this file. self.data_stack.append((self.cur_file_data, self.last_line)) filename = frame.f_code.co_filename tracename = self.should_trace_cache.get(filename) if tracename is None: tracename = self.should_trace(filename, frame) self.should_trace_cache[filename] = tracename #print("called, stack is %d deep, tracename is %r" % ( # len(self.data_stack), tracename)) if tracename: if tracename not in self.data: self.data[tracename] = {} self.cur_file_data = self.data[tracename] else: self.cur_file_data = None # Set the last_line to -1 because the next arc will be entering a # code block, indicated by (-1, n). self.last_line = -1 elif event == 'line': # Record an executed line. if self.cur_file_data is not None: if self.arcs: #print("lin", self.last_line, frame.f_lineno) self.cur_file_data[(self.last_line, frame.f_lineno)] = None else: #print("lin", frame.f_lineno) self.cur_file_data[frame.f_lineno] = None self.last_line = frame.f_lineno elif event == 'return': if self.arcs and self.cur_file_data: first = frame.f_code.co_firstlineno self.cur_file_data[(self.last_line, -first)] = None # Leaving this function, pop the filename stack. self.cur_file_data, self.last_line = self.data_stack.pop() #print("returned, stack is %d deep" % (len(self.data_stack))) elif event == 'exception': #print("exc", self.last_line, frame.f_lineno) self.last_exc_back = frame.f_back self.last_exc_firstlineno = frame.f_code.co_firstlineno return self._trace
[ "def", "_trace", "(", "self", ",", "frame", ",", "event", ",", "arg_unused", ")", ":", "#print(\"trace event: %s %r @%d\" % (", "# event, frame.f_code.co_filename, frame.f_lineno))", "if", "self", ".", "last_exc_back", ":", "if", "frame", "==", "self", ".", ...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/collector.py#L44-L100
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
python/caffe/draw.py
python
draw_net_to_file
(caffe_net, filename, rankdir='LR', phase=None)
Draws a caffe net, and saves it to file using the format given as the file extension. Use '.raw' to output raw text that you can manually feed to graphviz to draw graphs. Parameters ---------- caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer. filename : string The path to a file where the networks visualization will be stored. rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional Include layers from this network phase. If None, include all layers. (the default is None)
Draws a caffe net, and saves it to file using the format given as the file extension. Use '.raw' to output raw text that you can manually feed to graphviz to draw graphs.
[ "Draws", "a", "caffe", "net", "and", "saves", "it", "to", "file", "using", "the", "format", "given", "as", "the", "file", "extension", ".", "Use", ".", "raw", "to", "output", "raw", "text", "that", "you", "can", "manually", "feed", "to", "graphviz", "t...
def draw_net_to_file(caffe_net, filename, rankdir='LR', phase=None): """Draws a caffe net, and saves it to file using the format given as the file extension. Use '.raw' to output raw text that you can manually feed to graphviz to draw graphs. Parameters ---------- caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer. filename : string The path to a file where the networks visualization will be stored. rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional Include layers from this network phase. If None, include all layers. (the default is None) """ ext = filename[filename.rfind('.')+1:] with open(filename, 'wb') as fid: fid.write(draw_net(caffe_net, rankdir, ext, phase))
[ "def", "draw_net_to_file", "(", "caffe_net", ",", "filename", ",", "rankdir", "=", "'LR'", ",", "phase", "=", "None", ")", ":", "ext", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "with", "open", "(", "filename...
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/python/caffe/draw.py#L226-L244
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/__init__.py
python
get_axes_names_dict
(fig, curves_only=False, images_only=False)
return axes_names
Return dictionary mapping axes names to the corresponding Axes object. :param fig: A matplotlib Figure object :param curves_only: Bool. If True only add axes to dict if it contains a curve :param images_only: Bool. If True only add axes to dict if it contains an image
Return dictionary mapping axes names to the corresponding Axes object. :param fig: A matplotlib Figure object :param curves_only: Bool. If True only add axes to dict if it contains a curve :param images_only: Bool. If True only add axes to dict if it contains an image
[ "Return", "dictionary", "mapping", "axes", "names", "to", "the", "corresponding", "Axes", "object", ".", ":", "param", "fig", ":", "A", "matplotlib", "Figure", "object", ":", "param", "curves_only", ":", "Bool", ".", "If", "True", "only", "add", "axes", "t...
def get_axes_names_dict(fig, curves_only=False, images_only=False): """ Return dictionary mapping axes names to the corresponding Axes object. :param fig: A matplotlib Figure object :param curves_only: Bool. If True only add axes to dict if it contains a curve :param images_only: Bool. If True only add axes to dict if it contains an image """ if curves_only and images_only: return ValueError("Only one of 'curves_only' and 'images_only' may be " "True.") axes_names = {} for ax in fig.get_axes(): if ax not in [img.axes for img in get_colorbars_from_fig(fig)]: if curves_only and curve_in_ax(ax): axes_names[generate_ax_name(ax)] = ax elif images_only and image_in_ax(ax): axes_names[generate_ax_name(ax)] = ax elif not curves_only and not images_only: axes_names[generate_ax_name(ax)] = ax return axes_names
[ "def", "get_axes_names_dict", "(", "fig", ",", "curves_only", "=", "False", ",", "images_only", "=", "False", ")", ":", "if", "curves_only", "and", "images_only", ":", "return", "ValueError", "(", "\"Only one of 'curves_only' and 'images_only' may be \"", "\"True.\"", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/__init__.py#L28-L48
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AzCodeGenerator/bin/linux/az_code_gen/clang_cpp.py
python
promote_field_tags_to_class
(json_object)
Promote field annotations to the class object if they contain the "class_attribute" attribute
Promote field annotations to the class object if they contain the "class_attribute" attribute
[ "Promote", "field", "annotations", "to", "the", "class", "object", "if", "they", "contain", "the", "class_attribute", "attribute" ]
def promote_field_tags_to_class(json_object): """ Promote field annotations to the class object if they contain the "class_attribute" attribute """ remove_virtual_fields = True tag = "class_attribute" for object in json_object.get('objects', []): if object['type'] in ('class', 'struct'): fields_to_remove = [] for field in object.get('fields', []): for annotation_key, annotation_value in field['annotations'].items(): for attribute_name, attribute_value in annotation_value.items(): if attribute_name.lower() == tag.lower(): fields_to_remove.append(field) if annotation_key in object["annotations"]: raise ValueError( "Warning - Duplicate class_attribute tag: {} " "in object {}".format(annotation_key, object['qualified_name'])) object["annotations"][annotation_key].update(annotation_value) else: object["annotations"][annotation_key] = annotation_value if remove_virtual_fields and len(fields_to_remove) > 0: for remove_field in fields_to_remove: if remove_field in object.get('fields', []): object["fields"].remove(remove_field)
[ "def", "promote_field_tags_to_class", "(", "json_object", ")", ":", "remove_virtual_fields", "=", "True", "tag", "=", "\"class_attribute\"", "for", "object", "in", "json_object", ".", "get", "(", "'objects'", ",", "[", "]", ")", ":", "if", "object", "[", "'typ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AzCodeGenerator/bin/linux/az_code_gen/clang_cpp.py#L171-L198
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/packaging/msi.py
python
generate_guids
(root)
generates globally unique identifiers for parts of the xml which need them. Component tags have a special requirement. Their UUID is only allowed to change if the list of their contained resources has changed. This allows for clean removal and proper updates. To handle this requirement, the uuid is generated with an md5 hashing the whole subtree of a xml node.
generates globally unique identifiers for parts of the xml which need them.
[ "generates", "globally", "unique", "identifiers", "for", "parts", "of", "the", "xml", "which", "need", "them", "." ]
def generate_guids(root): """ generates globally unique identifiers for parts of the xml which need them. Component tags have a special requirement. Their UUID is only allowed to change if the list of their contained resources has changed. This allows for clean removal and proper updates. To handle this requirement, the uuid is generated with an md5 hashing the whole subtree of a xml node. """ from hashlib import md5 # specify which tags need a guid and in which attribute this should be stored. needs_id = { 'Product' : 'Id', 'Package' : 'Id', 'Component' : 'Guid', } # find all XMl nodes matching the key, retrieve their attribute, hash their # subtree, convert hash to string and add as a attribute to the xml node. for (key,value) in needs_id.items(): node_list = root.getElementsByTagName(key) attribute = value for node in node_list: hash = md5(node.toxml()).hexdigest() hash_str = '%s-%s-%s-%s-%s' % ( hash[:8], hash[8:12], hash[12:16], hash[16:20], hash[20:] ) node.attributes[attribute] = hash_str
[ "def", "generate_guids", "(", "root", ")", ":", "from", "hashlib", "import", "md5", "# specify which tags need a guid and in which attribute this should be stored.", "needs_id", "=", "{", "'Product'", ":", "'Id'", ",", "'Package'", ":", "'Id'", ",", "'Component'", ":", ...
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/packaging/msi.py#L154-L181
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/math_grad.py
python
_ConjGrad
(_, grad)
return math_ops.conj(grad)
Returns the complex conjugate of grad.
Returns the complex conjugate of grad.
[ "Returns", "the", "complex", "conjugate", "of", "grad", "." ]
def _ConjGrad(_, grad): """Returns the complex conjugate of grad.""" return math_ops.conj(grad)
[ "def", "_ConjGrad", "(", "_", ",", "grad", ")", ":", "return", "math_ops", ".", "conj", "(", "grad", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/math_grad.py#L762-L764
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
ArtProvider_PushBack
(*args, **kwargs)
return _misc_.ArtProvider_PushBack(*args, **kwargs)
ArtProvider_PushBack(wxArtProvider provider) Add new provider to the bottom of providers stack (i.e. the provider will be queried as the last one).
ArtProvider_PushBack(wxArtProvider provider)
[ "ArtProvider_PushBack", "(", "wxArtProvider", "provider", ")" ]
def ArtProvider_PushBack(*args, **kwargs): """ ArtProvider_PushBack(wxArtProvider provider) Add new provider to the bottom of providers stack (i.e. the provider will be queried as the last one). """ return _misc_.ArtProvider_PushBack(*args, **kwargs)
[ "def", "ArtProvider_PushBack", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ArtProvider_PushBack", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2970-L2977
xapian/xapian
2b803ea5e3904a6e0cd7d111b2ff38a704c21041
xapian-maintainer-tools/buildbot/xapian_factories.py
python
gen_git_clean_dist_factory
(repourl)
return f
Factory for doing build from a clean checkout of git master. This build also performs a "make distcheck", so should catch problems with files which have been missed from the distribution. This one is much more expensive, so should be run with a higher stable time.
Factory for doing build from a clean checkout of git master. This build also performs a "make distcheck", so should catch problems with files which have been missed from the distribution. This one is much more expensive, so should be run with a higher stable time.
[ "Factory", "for", "doing", "build", "from", "a", "clean", "checkout", "of", "git", "master", ".", "This", "build", "also", "performs", "a", "make", "distcheck", "so", "should", "catch", "problems", "with", "files", "which", "have", "been", "missed", "from", ...
def gen_git_clean_dist_factory(repourl): """ Factory for doing build from a clean checkout of git master. This build also performs a "make distcheck", so should catch problems with files which have been missed from the distribution. This one is much more expensive, so should be run with a higher stable time. """ f = factory.BuildFactory() f.addStep(MakeWritable, workdir='.') f.addStep(source.Git(repourl=repourl, mode="clobber")) f.addStep(Bootstrap()) f.addStep(step.Configure, command = ["xapian-maintainer-tools/buildbot/scripts/configure_with_prefix.sh"]) extraargs = ( "XAPIAN_TESTSUITE_OUTPUT=plain", "VALGRIND=", "AUTOMATED_TESTING=1" ) f.addStep(step.Compile, command = ["make",] + extraargs) # Don't bother running check as a separate step - all the checks will be # done by distcheck, anyway. (Running it as a separate step _does_ check # that the tests work in a non-VPATH build, but this is tested by other # factories, anyway.) #f.addStep(step.Test, name="check", command = ["make", "check"] + extraargs) f.addStep(step.Test, name="distcheck", command = ["make", "distcheck"] + extraargs, workdir='build/xapian-core') f.addStep(step.Test, name="distcheck", command = ["make", "distcheck"] + extraargs, workdir='build/xapian-applications/omega') # Have to install the core for distcheck to pass on the bindings. f.addStep(step.Test, name="install", command = ["make", "install"] + extraargs, workdir='build/xapian-core') f.addStep(step.Test, name="distcheck", command = ["make", "distcheck"] + extraargs, workdir='build/xapian-bindings') return f
[ "def", "gen_git_clean_dist_factory", "(", "repourl", ")", ":", "f", "=", "factory", ".", "BuildFactory", "(", ")", "f", ".", "addStep", "(", "MakeWritable", ",", "workdir", "=", "'.'", ")", "f", ".", "addStep", "(", "source", ".", "Git", "(", "repourl", ...
https://github.com/xapian/xapian/blob/2b803ea5e3904a6e0cd7d111b2ff38a704c21041/xapian-maintainer-tools/buildbot/xapian_factories.py#L210-L237
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/ssd/dataset/yolo_format.py
python
YoloFormat._load_image_set_index
(self, shuffle)
return image_set_index
find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting
find out which indexes correspond to given image set (train or val)
[ "find", "out", "which", "indexes", "correspond", "to", "given", "image", "set", "(", "train", "or", "val", ")" ]
def _load_image_set_index(self, shuffle): """ find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting """ assert os.path.exists(self.list_file), 'Path does not exists: {}'.format(self.list_file) with open(self.list_file, 'r') as f: image_set_index = [x.strip() for x in f.readlines()] if shuffle: np.random.shuffle(image_set_index) return image_set_index
[ "def", "_load_image_set_index", "(", "self", ",", "shuffle", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "self", ".", "list_file", ")", ",", "'Path does not exists: {}'", ".", "format", "(", "self", ".", "list_file", ")", "with", "open", "("...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/dataset/yolo_format.py#L72-L89
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PGProperty.GetColumnEditor
(*args, **kwargs)
return _propgrid.PGProperty_GetColumnEditor(*args, **kwargs)
GetColumnEditor(self, int column) -> PGEditor
GetColumnEditor(self, int column) -> PGEditor
[ "GetColumnEditor", "(", "self", "int", "column", ")", "-", ">", "PGEditor" ]
def GetColumnEditor(*args, **kwargs): """GetColumnEditor(self, int column) -> PGEditor""" return _propgrid.PGProperty_GetColumnEditor(*args, **kwargs)
[ "def", "GetColumnEditor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_GetColumnEditor", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L563-L565
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
build/fbcode_builder/getdeps/cargo.py
python
CargoBuilder._resolve_dep_to_git
(self)
return dep_to_git
For each direct dependency of the currently build manifest check if it is also cargo-builded and if yes then extract it's git configs and install dir
For each direct dependency of the currently build manifest check if it is also cargo-builded and if yes then extract it's git configs and install dir
[ "For", "each", "direct", "dependency", "of", "the", "currently", "build", "manifest", "check", "if", "it", "is", "also", "cargo", "-", "builded", "and", "if", "yes", "then", "extract", "it", "s", "git", "configs", "and", "install", "dir" ]
def _resolve_dep_to_git(self): """ For each direct dependency of the currently build manifest check if it is also cargo-builded and if yes then extract it's git configs and install dir """ dependencies = self.manifest.get_dependencies(self.ctx) if not dependencies: return [] dep_to_git = {} for dep in dependencies: dep_manifest = self.loader.load_manifest(dep) dep_builder = dep_manifest.get("build", "builder", ctx=self.ctx) if dep_builder not in ["cargo", "nop"] or dep == "rust": # This is a direct dependency, but it is not build with cargo # and it is not simply copying files with nop, so ignore it. # The "rust" dependency is an exception since it contains the # toolchain. continue git_conf = dep_manifest.get_section_as_dict("git", self.ctx) if "repo_url" not in git_conf: raise Exception( "A cargo dependency requires git.repo_url to be defined." ) source_dir = self.loader.get_project_install_dir(dep_manifest) if dep_builder == "cargo": source_dir = os.path.join(source_dir, "source") git_conf["source_dir"] = source_dir dep_to_git[dep] = git_conf return dep_to_git
[ "def", "_resolve_dep_to_git", "(", "self", ")", ":", "dependencies", "=", "self", ".", "manifest", ".", "get_dependencies", "(", "self", ".", "ctx", ")", "if", "not", "dependencies", ":", "return", "[", "]", "dep_to_git", "=", "{", "}", "for", "dep", "in...
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/build/fbcode_builder/getdeps/cargo.py#L220-L251
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/intelc.py
python
get_all_compiler_versions
()
return sorted(SCons.Util.unique(versions), key=keyfunc, reverse=True)
Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first.
Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first.
[ "Returns", "a", "sorted", "list", "of", "strings", "like", "70", "or", "80", "or", "9", ".", "0", "with", "most", "recent", "compiler", "version", "first", "." ]
def get_all_compiler_versions(): """Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first. """ versions=[] if is_windows: if is_win64: keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++' else: keyname = 'Software\\Intel\\Compilers\\C++' try: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, keyname) except SCons.Util.WinError: # For version 13 or later, check for default instance UUID if is_win64: keyname = 'Software\\WoW6432Node\\Intel\\Suites' else: keyname = 'Software\\Intel\\Suites' try: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, keyname) except SCons.Util.WinError: return [] i = 0 versions = [] try: while i < 100: subkey = SCons.Util.RegEnumKey(k, i) # raises EnvironmentError # Check that this refers to an existing dir. # This is not 100% perfect but should catch common # installation issues like when the compiler was installed # and then the install directory deleted or moved (rather # than uninstalling properly), so the registry values # are still there. if subkey == 'Defaults': # Ignore default instances i = i + 1 continue ok = False for try_abi in ('IA32', 'IA32e', 'IA64', 'EM64T'): try: d = get_intel_registry_value('ProductDir', subkey, try_abi) except MissingRegistryError: continue # not found in reg, keep going if os.path.exists(d): ok = True if ok: versions.append(subkey) else: try: # Registry points to nonexistent dir. Ignore this # version. value = get_intel_registry_value('ProductDir', subkey, 'IA32') except MissingRegistryError, e: # Registry key is left dangling (potentially # after uninstalling). print \ "scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \ "scons: *** It seems that the compiler was uninstalled and that the registry\n" \ "scons: *** was not cleaned up properly.\n" % subkey else: print "scons: *** Ignoring "+str(value) i = i + 1 except EnvironmentError: # no more subkeys pass elif is_linux or is_mac: for d in glob.glob('/opt/intel_cc_*'): # Typical dir here is /opt/intel_cc_80. m = re.search(r'cc_(.*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/cc*/*'): # Typical dir here is /opt/intel/cc/9.0 for IA32, # /opt/intel/cce/9.0 for EMT64 (AMD64) m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/Compiler/*'): # Typical dir here is /opt/intel/Compiler/11.1 m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/composerxe-*'): # Typical dir here is /opt/intel/composerxe-2011.4.184 m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/composer_xe_*'): # Typical dir here is /opt/intel/composer_xe_2011_sp1.11.344 # The _sp1 is useless, the installers are named 2011.9.x, 2011.10.x, 2011.11.x m = re.search(r'([0-9]{0,4})(?:_sp\d*)?\.([0-9][0-9.]*)$', d) if m: versions.append("%s.%s"%(m.group(1), m.group(2))) for d in glob.glob('/opt/intel/compilers_and_libraries_*'): # JPA: For the new version of Intel compiler 2016.1. m = re.search(r'([0-9]{0,4})(?:_sp\d*)?\.([0-9][0-9.]*)$', d) if m: versions.append("%s.%s"%(m.group(1), m,group(2))) def keyfunc(str): """Given a dot-separated version string, return a tuple of ints representing it.""" return [int(x) for x in str.split('.')] # split into ints, sort, then remove dups return sorted(SCons.Util.unique(versions), key=keyfunc, reverse=True)
[ "def", "get_all_compiler_versions", "(", ")", ":", "versions", "=", "[", "]", "if", "is_windows", ":", "if", "is_win64", ":", "keyname", "=", "'Software\\\\WoW6432Node\\\\Intel\\\\Compilers\\\\C++'", "else", ":", "keyname", "=", "'Software\\\\Intel\\\\Compilers\\\\C++'", ...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/intelc.py#L196-L302
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pickletools.py
python
read_unicodestring4
(f)
r""" >>> import io >>> s = 'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc b'abcd\xea\xaf\x8d' >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk')) >>> s == t True >>> read_unicodestring4(io.BytesIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
r""" >>> import io >>> s = 'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc b'abcd\xea\xaf\x8d' >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk')) >>> s == t True
[ "r", ">>>", "import", "io", ">>>", "s", "=", "abcd", "\\", "uabcd", ">>>", "enc", "=", "s", ".", "encode", "(", "utf", "-", "8", ")", ">>>", "enc", "b", "abcd", "\\", "xea", "\\", "xaf", "\\", "x8d", ">>>", "n", "=", "bytes", "(", "[", "len",...
def read_unicodestring4(f): r""" >>> import io >>> s = 'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc b'abcd\xea\xaf\x8d' >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk')) >>> s == t True >>> read_unicodestring4(io.BytesIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring4, but only 6 remain """ n = read_uint4(f) assert n >= 0 if n > sys.maxsize: raise ValueError("unicodestring4 byte count > sys.maxsize: %d" % n) data = f.read(n) if len(data) == n: return str(data, 'utf-8', 'surrogatepass') raise ValueError("expected %d bytes in a unicodestring4, but only %d " "remain" % (n, len(data)))
[ "def", "read_unicodestring4", "(", "f", ")", ":", "n", "=", "read_uint4", "(", "f", ")", "assert", "n", ">=", "0", "if", "n", ">", "sys", ".", "maxsize", ":", "raise", "ValueError", "(", "\"unicodestring4 byte count > sys.maxsize: %d\"", "%", "n", ")", "da...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pickletools.py#L668-L694
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/more-itertools/py2/more_itertools/more.py
python
lstrip
(iterable, pred)
return dropwhile(pred, iterable)
Yield the items from *iterable*, but strip any from the beginning for which *pred* returns ``True``. For example, to remove a set of items from the start of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(lstrip(iterable, pred)) [1, 2, None, 3, False, None] This function is analogous to to :func:`str.lstrip`, and is essentially an wrapper for :func:`itertools.dropwhile`.
Yield the items from *iterable*, but strip any from the beginning for which *pred* returns ``True``.
[ "Yield", "the", "items", "from", "*", "iterable", "*", "but", "strip", "any", "from", "the", "beginning", "for", "which", "*", "pred", "*", "returns", "True", "." ]
def lstrip(iterable, pred): """Yield the items from *iterable*, but strip any from the beginning for which *pred* returns ``True``. For example, to remove a set of items from the start of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(lstrip(iterable, pred)) [1, 2, None, 3, False, None] This function is analogous to to :func:`str.lstrip`, and is essentially an wrapper for :func:`itertools.dropwhile`. """ return dropwhile(pred, iterable)
[ "def", "lstrip", "(", "iterable", ",", "pred", ")", ":", "return", "dropwhile", "(", "pred", ",", "iterable", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py2/more_itertools/more.py#L1638-L1653
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/util.py
python
zip_dir
(directory)
return result
zip a directory tree into a BytesIO object
zip a directory tree into a BytesIO object
[ "zip", "a", "directory", "tree", "into", "a", "BytesIO", "object" ]
def zip_dir(directory): """zip a directory tree into a BytesIO object""" result = io.BytesIO() dlen = len(directory) with ZipFile(result, "w") as zf: for root, dirs, files in os.walk(directory): for name in files: full = os.path.join(root, name) rel = root[dlen:] dest = os.path.join(rel, name) zf.write(full, dest) return result
[ "def", "zip_dir", "(", "directory", ")", ":", "result", "=", "io", ".", "BytesIO", "(", ")", "dlen", "=", "len", "(", "directory", ")", "with", "ZipFile", "(", "result", ",", "\"w\"", ")", "as", "zf", ":", "for", "root", ",", "dirs", ",", "files", ...
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/util.py#L1249-L1260
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/pycodegen.py
python
CodeGenerator.initClass
(self)
This method is called once for each class
This method is called once for each class
[ "This", "method", "is", "called", "once", "for", "each", "class" ]
def initClass(self): """This method is called once for each class"""
[ "def", "initClass", "(", "self", ")", ":" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/pycodegen.py#L225-L226
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Base/Python/slicer/util.py
python
arrayFromVolumeModified
(volumeNode)
Indicate that modification of a numpy array returned by :py:meth:`arrayFromVolume` has been completed.
Indicate that modification of a numpy array returned by :py:meth:`arrayFromVolume` has been completed.
[ "Indicate", "that", "modification", "of", "a", "numpy", "array", "returned", "by", ":", "py", ":", "meth", ":", "arrayFromVolume", "has", "been", "completed", "." ]
def arrayFromVolumeModified(volumeNode): """Indicate that modification of a numpy array returned by :py:meth:`arrayFromVolume` has been completed.""" imageData = volumeNode.GetImageData() pointData = imageData.GetPointData() if imageData else None if pointData: if pointData.GetScalars(): pointData.GetScalars().Modified() if pointData.GetTensors(): pointData.GetTensors().Modified() volumeNode.Modified()
[ "def", "arrayFromVolumeModified", "(", "volumeNode", ")", ":", "imageData", "=", "volumeNode", ".", "GetImageData", "(", ")", "pointData", "=", "imageData", ".", "GetPointData", "(", ")", "if", "imageData", "else", "None", "if", "pointData", ":", "if", "pointD...
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L1485-L1494
QMCPACK/qmcpack
d0948ab455e38364458740cc8e2239600a14c5cd
nexus/lib/gaussian_process.py
python
GaussianProcessOptimizer.write_energy_file
(self,energy_file,energies,errors=None,iter='cur')
Writes an energy file to the current iteration's output directory.
Writes an energy file to the current iteration's output directory.
[ "Writes", "an", "energy", "file", "to", "the", "current", "iteration", "s", "output", "directory", "." ]
def write_energy_file(self,energy_file,energies,errors=None,iter='cur'): """ Writes an energy file to the current iteration's output directory. """ path = self.make_output_dir(iter) filepath = os.path.join(path,energy_file) self.vlog('writing energies to {0}'.format(filepath),n=3) energies = energies.ravel() s = '' if errors is None: for e in energies: s += '{0: 16.12f}\n'.format(e) #end for else: errors = errors.ravel() for e,ee in zip(energies,errors): s += '{0: 16.12f} {1: 16.12f}\n'.format(e,ee) #end for #end if f = open(filepath,'w') f.write(s) f.close()
[ "def", "write_energy_file", "(", "self", ",", "energy_file", ",", "energies", ",", "errors", "=", "None", ",", "iter", "=", "'cur'", ")", ":", "path", "=", "self", ".", "make_output_dir", "(", "iter", ")", "filepath", "=", "os", ".", "path", ".", "join...
https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/nexus/lib/gaussian_process.py#L1672-L1693
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/quopri.py
python
encode
(input, output, quotetabs, header=False)
Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are binary file objects. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. The 'header' flag indicates whether we are encoding spaces as _ as per RFC 1522.
Read 'input', apply quoted-printable encoding, and write to 'output'.
[ "Read", "input", "apply", "quoted", "-", "printable", "encoding", "and", "write", "to", "output", "." ]
def encode(input, output, quotetabs, header=False): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are binary file objects. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. The 'header' flag indicates whether we are encoding spaces as _ as per RFC 1522.""" if b2a_qp is not None: data = input.read() odata = b2a_qp(data, quotetabs=quotetabs, header=header) output.write(odata) return def write(s, output=output, lineEnd=b'\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in b' \t': output.write(s[:-1] + quote(s[-1:]) + lineEnd) elif s == b'.': output.write(quote(s) + lineEnd) else: output.write(s + lineEnd) prevline = None while 1: line = input.readline() if not line: break outline = [] # Strip off any readline induced trailing newline stripped = b'' if line[-1:] == b'\n': line = line[:-1] stripped = b'\n' # Calculate the un-length-limited encoded line for c in line: c = bytes((c,)) if needsquoting(c, quotetabs, header): c = quote(c) if header and c == b' ': outline.append(b'_') else: outline.append(c) # First, write out the previous line if prevline is not None: write(prevline) # Now see if we need any soft line breaks because of RFC-imposed # length limitations. Then do the thisline->prevline dance. thisline = EMPTYSTRING.join(outline) while len(thisline) > MAXLINESIZE: # Don't forget to include the soft line break `=' sign in the # length calculation! write(thisline[:MAXLINESIZE-1], lineEnd=b'=\n') thisline = thisline[MAXLINESIZE-1:] # Write out the current line prevline = thisline # Write out the last line, without a trailing newline if prevline is not None: write(prevline, lineEnd=stripped)
[ "def", "encode", "(", "input", ",", "output", ",", "quotetabs", ",", "header", "=", "False", ")", ":", "if", "b2a_qp", "is", "not", "None", ":", "data", "=", "input", ".", "read", "(", ")", "odata", "=", "b2a_qp", "(", "data", ",", "quotetabs", "="...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/quopri.py#L44-L104
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/abins/input/dmol3loader.py
python
DMOL3Loader._convert_to_angstroms
(self, string=None)
return float(string) * au2ang
:param string: string with number :returns: converted coordinate of lattice vector to Angstroms
:param string: string with number :returns: converted coordinate of lattice vector to Angstroms
[ ":", "param", "string", ":", "string", "with", "number", ":", "returns", ":", "converted", "coordinate", "of", "lattice", "vector", "to", "Angstroms" ]
def _convert_to_angstroms(self, string=None): """ :param string: string with number :returns: converted coordinate of lattice vector to Angstroms """ au2ang = ATOMIC_LENGTH_2_ANGSTROM return float(string) * au2ang
[ "def", "_convert_to_angstroms", "(", "self", ",", "string", "=", "None", ")", ":", "au2ang", "=", "ATOMIC_LENGTH_2_ANGSTROM", "return", "float", "(", "string", ")", "*", "au2ang" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/input/dmol3loader.py#L93-L99
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiManager.SetManagedWindow
(*args, **kwargs)
return _aui.AuiManager_SetManagedWindow(*args, **kwargs)
SetManagedWindow(self, Window managedWnd)
SetManagedWindow(self, Window managedWnd)
[ "SetManagedWindow", "(", "self", "Window", "managedWnd", ")" ]
def SetManagedWindow(*args, **kwargs): """SetManagedWindow(self, Window managedWnd)""" return _aui.AuiManager_SetManagedWindow(*args, **kwargs)
[ "def", "SetManagedWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_SetManagedWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L606-L608
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pyparsing/py2/pyparsing.py
python
makeHTMLTags
(tagStr)
return _makeTags(tagStr, False)
Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. Example:: text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>' # makeHTMLTags returns pyparsing expressions for the opening and # closing tags as a 2-tuple a, a_end = makeHTMLTags("A") link_expr = a + SkipTo(a_end)("link_text") + a_end for link in link_expr.searchString(text): # attributes in the <A> tag (like "href" shown here) are # also accessible as named results print(link.link_text, '->', link.href) prints:: pyparsing -> https://github.com/pyparsing/pyparsing/wiki
Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values.
[ "Helper", "to", "construct", "opening", "and", "closing", "tag", "expressions", "for", "HTML", "given", "a", "tag", "name", ".", "Matches", "tags", "in", "either", "upper", "or", "lower", "case", "attributes", "with", "namespaces", "and", "with", "quoted", "...
def makeHTMLTags(tagStr): """Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. Example:: text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>' # makeHTMLTags returns pyparsing expressions for the opening and # closing tags as a 2-tuple a, a_end = makeHTMLTags("A") link_expr = a + SkipTo(a_end)("link_text") + a_end for link in link_expr.searchString(text): # attributes in the <A> tag (like "href" shown here) are # also accessible as named results print(link.link_text, '->', link.href) prints:: pyparsing -> https://github.com/pyparsing/pyparsing/wiki """ return _makeTags(tagStr, False)
[ "def", "makeHTMLTags", "(", "tagStr", ")", ":", "return", "_makeTags", "(", "tagStr", ",", "False", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py2/pyparsing.py#L5843-L5865
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/handlers.py
python
MapperWorkerCallbackHandler._maintain_LC
(self, obj, slice_id, last_slice=False, begin_slice=True, shard_ctx=None, slice_ctx=None)
Makes sure shard life cycle interface are respected. Args: obj: the obj that may have implemented _ShardLifeCycle. slice_id: current slice_id last_slice: whether this is the last slice. begin_slice: whether this is the beginning or the end of a slice. shard_ctx: shard ctx for dependency injection. If None, it will be read from self. slice_ctx: slice ctx for dependency injection. If None, it will be read from self.
Makes sure shard life cycle interface are respected.
[ "Makes", "sure", "shard", "life", "cycle", "interface", "are", "respected", "." ]
def _maintain_LC(self, obj, slice_id, last_slice=False, begin_slice=True, shard_ctx=None, slice_ctx=None): """Makes sure shard life cycle interface are respected. Args: obj: the obj that may have implemented _ShardLifeCycle. slice_id: current slice_id last_slice: whether this is the last slice. begin_slice: whether this is the beginning or the end of a slice. shard_ctx: shard ctx for dependency injection. If None, it will be read from self. slice_ctx: slice ctx for dependency injection. If None, it will be read from self. """ if obj is None or not isinstance(obj, shard_life_cycle._ShardLifeCycle): return shard_context = shard_ctx or self.shard_context slice_context = slice_ctx or self.slice_context if begin_slice: if slice_id == 0: obj.begin_shard(shard_context) obj.begin_slice(slice_context) else: obj.end_slice(slice_context) if last_slice: obj.end_shard(shard_context)
[ "def", "_maintain_LC", "(", "self", ",", "obj", ",", "slice_id", ",", "last_slice", "=", "False", ",", "begin_slice", "=", "True", ",", "shard_ctx", "=", "None", ",", "slice_ctx", "=", "None", ")", ":", "if", "obj", "is", "None", "or", "not", "isinstan...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/handlers.py#L378-L404
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/clangxx.py
python
generate
(env)
Add Builders and construction variables for clang++ to an Environment.
Add Builders and construction variables for clang++ to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "clang", "++", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for clang++ to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) SCons.Tool.cxx.generate(env) env['CXX'] = env.Detect(compilers) or 'clang++' # platform specific settings if env['PLATFORM'] == 'aix': env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -mminimal-toc') env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['SHOBJSUFFIX'] = '$OBJSUFFIX' elif env['PLATFORM'] == 'hpux': env['SHOBJSUFFIX'] = '.pic.o' elif env['PLATFORM'] == 'sunos': env['SHOBJSUFFIX'] = '.pic.o' # determine compiler version if env['CXX']: pipe = SCons.Action._subproc(env, [env['CXX'], '--version'], stdin='devnull', stderr='devnull', stdout=subprocess.PIPE) if pipe.wait() != 0: return # clang -dumpversion is of no use line = pipe.stdout.readline() if sys.version_info[0] > 2: line = line.decode() match = re.search(r'clang +version +([0-9]+(?:\.[0-9]+)+)', line) if match: env['CXXVERSION'] = match.group(1)
[ "def", "generate", "(", "env", ")", ":", "static_obj", ",", "shared_obj", "=", "SCons", ".", "Tool", ".", "createObjBuilders", "(", "env", ")", "SCons", ".", "Tool", ".", "cxx", ".", "generate", "(", "env", ")", "env", "[", "'CXX'", "]", "=", "env", ...
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/clangxx.py#L52-L82
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/tensor_shape.py
python
as_dimension
(value)
Converts the given value to a Dimension. A Dimension input will be returned unmodified. An input of `None` will be converted to an unknown Dimension. An integer input will be converted to a Dimension with that value. Args: value: The value to be converted. Returns: A Dimension corresponding to the given value.
Converts the given value to a Dimension.
[ "Converts", "the", "given", "value", "to", "a", "Dimension", "." ]
def as_dimension(value): """Converts the given value to a Dimension. A Dimension input will be returned unmodified. An input of `None` will be converted to an unknown Dimension. An integer input will be converted to a Dimension with that value. Args: value: The value to be converted. Returns: A Dimension corresponding to the given value. """ if isinstance(value, Dimension): return value else: return Dimension(value)
[ "def", "as_dimension", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Dimension", ")", ":", "return", "value", "else", ":", "return", "Dimension", "(", "value", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/tensor_shape.py#L365-L381
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/plan/robotcspace.py
python
ImplicitManifoldRobotCSpace.interpolate
(self,a,b,u)
return self.solveManifold(x)
Interpolates on the manifold. Used by edge collision checking
Interpolates on the manifold. Used by edge collision checking
[ "Interpolates", "on", "the", "manifold", ".", "Used", "by", "edge", "collision", "checking" ]
def interpolate(self,a,b,u): """Interpolates on the manifold. Used by edge collision checking""" x = RobotCSpace.interpolate(self,a,b,u) return self.solveManifold(x)
[ "def", "interpolate", "(", "self", ",", "a", ",", "b", ",", "u", ")", ":", "x", "=", "RobotCSpace", ".", "interpolate", "(", "self", ",", "a", ",", "b", ",", "u", ")", "return", "self", ".", "solveManifold", "(", "x", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/plan/robotcspace.py#L309-L312
ducha-aiki/LSUVinit
a42ecdc0d44c217a29b65e98748d80b90d5c6279
scripts/cpp_lint.py
python
CleanseRawStrings
(raw_lines)
return lines_without_raw_strings
Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings.
Removes C++11 raw strings from lines.
[ "Removes", "C", "++", "11", "raw", "strings", "from", "lines", "." ]
def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '' else: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if matched: delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings
[ "def", "CleanseRawStrings", "(", "raw_lines", ")", ":", "delimiter", "=", "None", "lines_without_raw_strings", "=", "[", "]", "for", "line", "in", "raw_lines", ":", "if", "delimiter", ":", "# Inside a raw string, look for the end", "end", "=", "line", ".", "find",...
https://github.com/ducha-aiki/LSUVinit/blob/a42ecdc0d44c217a29b65e98748d80b90d5c6279/scripts/cpp_lint.py#L1062-L1120
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py
python
Base.__getattr__
(self, attr)
Together with the node_bwcomp dict defined below, this method provides a simple backward compatibility layer for the Node attributes 'abspath', 'labspath', 'path', 'tpath', 'suffix' and 'path_elements'. These Node attributes used to be directly available in v2.3 and earlier, but have been replaced by getter methods that initialize the single variables lazily when required, in order to save memory. The redirection to the getters lets older Tools and SConstruct continue to work without any additional changes, fully transparent to the user. Note, that __getattr__ is only called as fallback when the requested attribute can't be found, so there should be no speed performance penalty involved for standard builds.
Together with the node_bwcomp dict defined below, this method provides a simple backward compatibility layer for the Node attributes 'abspath', 'labspath', 'path', 'tpath', 'suffix' and 'path_elements'. These Node attributes used to be directly available in v2.3 and earlier, but have been replaced by getter methods that initialize the single variables lazily when required, in order to save memory. The redirection to the getters lets older Tools and SConstruct continue to work without any additional changes, fully transparent to the user. Note, that __getattr__ is only called as fallback when the requested attribute can't be found, so there should be no speed performance penalty involved for standard builds.
[ "Together", "with", "the", "node_bwcomp", "dict", "defined", "below", "this", "method", "provides", "a", "simple", "backward", "compatibility", "layer", "for", "the", "Node", "attributes", "abspath", "labspath", "path", "tpath", "suffix", "and", "path_elements", "...
def __getattr__(self, attr): """ Together with the node_bwcomp dict defined below, this method provides a simple backward compatibility layer for the Node attributes 'abspath', 'labspath', 'path', 'tpath', 'suffix' and 'path_elements'. These Node attributes used to be directly available in v2.3 and earlier, but have been replaced by getter methods that initialize the single variables lazily when required, in order to save memory. The redirection to the getters lets older Tools and SConstruct continue to work without any additional changes, fully transparent to the user. Note, that __getattr__ is only called as fallback when the requested attribute can't be found, so there should be no speed performance penalty involved for standard builds. """ if attr in node_bwcomp: return node_bwcomp[attr](self) raise AttributeError("%r object has no attribute %r" % (self.__class__, attr))
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", "in", "node_bwcomp", ":", "return", "node_bwcomp", "[", "attr", "]", "(", "self", ")", "raise", "AttributeError", "(", "\"%r object has no attribute %r\"", "%", "(", "self", ".", "__clas...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L672-L691
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
ThreadEvent.SetExtraLong
(*args, **kwargs)
return _core_.ThreadEvent_SetExtraLong(*args, **kwargs)
SetExtraLong(self, long extraLong)
SetExtraLong(self, long extraLong)
[ "SetExtraLong", "(", "self", "long", "extraLong", ")" ]
def SetExtraLong(*args, **kwargs): """SetExtraLong(self, long extraLong)""" return _core_.ThreadEvent_SetExtraLong(*args, **kwargs)
[ "def", "SetExtraLong", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "ThreadEvent_SetExtraLong", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L5394-L5396
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/decent_q/python/decent_q.py
python
_parse_nodes_bit
(input_graph_def, nodes_bit_str)
return nodes_bit
Parse nodes_bit configurations
Parse nodes_bit configurations
[ "Parse", "nodes_bit", "configurations" ]
def _parse_nodes_bit(input_graph_def, nodes_bit_str): """Parse nodes_bit configurations""" nodes_bit = [] if nodes_bit_str: nodes_bit = nodes_bit_str.split(",") for param in nodes_bit: node_name = [param.strip().split(":")[0]] check_node_names(input_graph_def, node_name) bit = int(param.strip().split(":")[-1]) if bit < 1: raise ValueError("Error mehtod number, method must be \ >=1 but got ", bit) return nodes_bit
[ "def", "_parse_nodes_bit", "(", "input_graph_def", ",", "nodes_bit_str", ")", ":", "nodes_bit", "=", "[", "]", "if", "nodes_bit_str", ":", "nodes_bit", "=", "nodes_bit_str", ".", "split", "(", "\",\"", ")", "for", "param", "in", "nodes_bit", ":", "node_name", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/decent_q/python/decent_q.py#L184-L196
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Region.Subtract
(*args, **kwargs)
return _gdi_.Region_Subtract(*args, **kwargs)
Subtract(self, int x, int y, int width, int height) -> bool
Subtract(self, int x, int y, int width, int height) -> bool
[ "Subtract", "(", "self", "int", "x", "int", "y", "int", "width", "int", "height", ")", "-", ">", "bool" ]
def Subtract(*args, **kwargs): """Subtract(self, int x, int y, int width, int height) -> bool""" return _gdi_.Region_Subtract(*args, **kwargs)
[ "def", "Subtract", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Region_Subtract", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1696-L1698