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
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/openpgp/sap/list.py
python
deliteralize
(msgs)
return outlist
String-ify literal messages. :Parameters: - `msgs`: list of message instances :Returns: list of same messages, except that all literals will have been magically converted to strings Sample literal output:: Filename: the_file.txt Modified: 1234567890 Format: t This is the literal text found in the_file.txt. Filename: the_next_file.txt Modified: 1234567891 Format: t And now some literal text found in the_next_file.txt. :note: Debate whether or not this should function should be encapsulated in `list_as_signed()`. It's not since this one is more of an output-only convenience. :TODO: ADD TESTS!
String-ify literal messages. :Parameters: - `msgs`: list of message instances
[ "String", "-", "ify", "literal", "messages", ".", ":", "Parameters", ":", "-", "msgs", ":", "list", "of", "message", "instances" ]
def deliteralize(msgs): """String-ify literal messages. :Parameters: - `msgs`: list of message instances :Returns: list of same messages, except that all literals will have been magically converted to strings Sample literal output:: Filename: the_file.txt Modified: 1234567890 Format: t This is the literal text found in the_file.txt. Filename: the_next_file.txt Modified: 1234567891 Format: t And now some literal text found in the_next_file.txt. :note: Debate whether or not this should function should be encapsulated in `list_as_signed()`. It's not since this one is more of an output-only convenience. :TODO: ADD TESTS! """ outlist = [] for msg in msgs: if hasattr(msg, 'literals'): for pkt in msg.literals: msg = linesep.join(["Filename: %s" % pkt.body.filename, "Modified: %s" % pkt.body.modified, "Format: %s%s" % (pkt.body.format, linesep), pkt.body.data, linesep]) # leave enough room for next one outlist.append(msg) return outlist
[ "def", "deliteralize", "(", "msgs", ")", ":", "outlist", "=", "[", "]", "for", "msg", "in", "msgs", ":", "if", "hasattr", "(", "msg", ",", "'literals'", ")", ":", "for", "pkt", "in", "msg", ".", "literals", ":", "msg", "=", "linesep", ".", "join", ...
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/list.py#L32-L78
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/reductions/complex2real/atom_canonicalizers/psd_canon.py
python
psd_canon
(expr, real_args, imag_args, real2imag)
return [expr.copy([matrix])], None
Canonicalize functions that take a Hermitian matrix.
Canonicalize functions that take a Hermitian matrix.
[ "Canonicalize", "functions", "that", "take", "a", "Hermitian", "matrix", "." ]
def psd_canon(expr, real_args, imag_args, real2imag): """Canonicalize functions that take a Hermitian matrix. """ if imag_args[0] is None: matrix = real_args[0] else: if real_args[0] is None: real_args[0] = np.zeros(imag_args[0].shape) matrix = bmat([[real_args[0], -imag_args[0]], [imag_args[0], real_args[0]]]) return [expr.copy([matrix])], None
[ "def", "psd_canon", "(", "expr", ",", "real_args", ",", "imag_args", ",", "real2imag", ")", ":", "if", "imag_args", "[", "0", "]", "is", "None", ":", "matrix", "=", "real_args", "[", "0", "]", "else", ":", "if", "real_args", "[", "0", "]", "is", "N...
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/reductions/complex2real/atom_canonicalizers/psd_canon.py#L22-L32
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/summary/summary.py
python
tensor_summary
(name, tensor, summary_description=None, collections=None, summary_metadata=None, family=None, display_name=None)
return val
Outputs a `Summary` protocol buffer with a serialized tensor.proto. Args: name: A name for the generated node. If display_name is not set, it will also serve as the tag name in TensorBoard. (In that case, the tag name will inherit tf name scopes.) tensor: A tensor of any type and shape to serialize. summary_description: A long description of the summary sequence. Markdown is supported. collections: Optional list of graph collections keys. The new summary op is added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. summary_metadata: Optional SummaryMetadata proto (which describes which plugins may use the summary value). family: Optional; if provided, used as the prefix of the summary tag, which controls the name used for display on TensorBoard when display_name is not set. display_name: A string used to name this data in TensorBoard. If this is not set, then the node name will be used instead. Returns: A scalar `Tensor` of type `string`. The serialized `Summary` protocol buffer.
Outputs a `Summary` protocol buffer with a serialized tensor.proto.
[ "Outputs", "a", "Summary", "protocol", "buffer", "with", "a", "serialized", "tensor", ".", "proto", "." ]
def tensor_summary(name, tensor, summary_description=None, collections=None, summary_metadata=None, family=None, display_name=None): """Outputs a `Summary` protocol buffer with a serialized tensor.proto. Args: name: A name for the generated node. If display_name is not set, it will also serve as the tag name in TensorBoard. (In that case, the tag name will inherit tf name scopes.) tensor: A tensor of any type and shape to serialize. summary_description: A long description of the summary sequence. Markdown is supported. collections: Optional list of graph collections keys. The new summary op is added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. summary_metadata: Optional SummaryMetadata proto (which describes which plugins may use the summary value). family: Optional; if provided, used as the prefix of the summary tag, which controls the name used for display on TensorBoard when display_name is not set. display_name: A string used to name this data in TensorBoard. If this is not set, then the node name will be used instead. Returns: A scalar `Tensor` of type `string`. The serialized `Summary` protocol buffer. """ if summary_metadata is None: summary_metadata = _SummaryMetadata() if summary_description is not None: summary_metadata.summary_description = summary_description if display_name is not None: summary_metadata.display_name = display_name serialized_summary_metadata = summary_metadata.SerializeToString() if _distribute_summary_op_util.skip_summary(): return _constant_op.constant('') with _summary_op_util.summary_scope( name, family, values=[tensor]) as (tag, scope): val = _gen_logging_ops.tensor_summary_v2( tensor=tensor, tag=tag, name=scope, serialized_summary_metadata=serialized_summary_metadata) _summary_op_util.collect(val, collections, [_ops.GraphKeys.SUMMARIES]) return val
[ "def", "tensor_summary", "(", "name", ",", "tensor", ",", "summary_description", "=", "None", ",", "collections", "=", "None", ",", "summary_metadata", "=", "None", ",", "family", "=", "None", ",", "display_name", "=", "None", ")", ":", "if", "summary_metada...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/summary/summary.py#L275-L327
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/websockify/websockify/websocket.py
python
WebSocketServer.poll
(self)
Run periodically while waiting for connections.
Run periodically while waiting for connections.
[ "Run", "periodically", "while", "waiting", "for", "connections", "." ]
def poll(self): """ Run periodically while waiting for connections. """ #self.vmsg("Running poll()") pass
[ "def", "poll", "(", "self", ")", ":", "#self.vmsg(\"Running poll()\")", "pass" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/websockify/websockify/websocket.py#L889-L892
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/ShipDesignAI.py
python
ShipDesigner._calc_rating_for_name
(self)
return self.design_stats.structure
Return a rough rating for the design independent of special requirements and species. The design name should not depend on the strength of the enemy or upon some additional requests we have for the design but only compare the basic functionality. If not overloaded in the subclass, this function returns the structure of the design. :return: float - a rough approximation of the strength of this design
Return a rough rating for the design independent of special requirements and species.
[ "Return", "a", "rough", "rating", "for", "the", "design", "independent", "of", "special", "requirements", "and", "species", "." ]
def _calc_rating_for_name(self): """Return a rough rating for the design independent of special requirements and species. The design name should not depend on the strength of the enemy or upon some additional requests we have for the design but only compare the basic functionality. If not overloaded in the subclass, this function returns the structure of the design. :return: float - a rough approximation of the strength of this design """ self.update_stats(ignore_species=True) return self.design_stats.structure
[ "def", "_calc_rating_for_name", "(", "self", ")", ":", "self", ".", "update_stats", "(", "ignore_species", "=", "True", ")", "return", "self", ".", "design_stats", ".", "structure" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/ShipDesignAI.py#L1366-L1376
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/dfxml.py
python
registry_value_object.__init__
(self)
List for the string-list type of value.
List for the string-list type of value.
[ "List", "for", "the", "string", "-", "list", "type", "of", "value", "." ]
def __init__(self): registry_cell_object.__init__(self) self.value_data = None self._cell_type = "registry_value_object" #TODO Replace to be in line with fileobjects: fileobject.hashdigest is a dictionary self._hashcache = dict() """List for the string-list type of value.""" self.strings = None
[ "def", "__init__", "(", "self", ")", ":", "registry_cell_object", ".", "__init__", "(", "self", ")", "self", ".", "value_data", "=", "None", "self", ".", "_cell_type", "=", "\"registry_value_object\"", "#TODO Replace to be in line with fileobjects: fileobject.hashdigest i...
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L550-L560
p4lang/behavioral-model
81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9
mininet/p4_mininet.py
python
P4Switch.check_switch_started
(self, pid)
While the process is running (pid exists), we check if the Thrift server has been started. If the Thrift server is ready, we assume that the switch was started successfully. This is only reliable if the Thrift server is started at the end of the init process
While the process is running (pid exists), we check if the Thrift server has been started. If the Thrift server is ready, we assume that the switch was started successfully. This is only reliable if the Thrift server is started at the end of the init process
[ "While", "the", "process", "is", "running", "(", "pid", "exists", ")", "we", "check", "if", "the", "Thrift", "server", "has", "been", "started", ".", "If", "the", "Thrift", "server", "is", "ready", "we", "assume", "that", "the", "switch", "was", "started...
def check_switch_started(self, pid): """While the process is running (pid exists), we check if the Thrift server has been started. If the Thrift server is ready, we assume that the switch was started successfully. This is only reliable if the Thrift server is started at the end of the init process""" while True: if not os.path.exists(os.path.join("/proc", str(pid))): return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.settimeout(0.5) result = sock.connect_ex(("localhost", self.thrift_port)) finally: sock.close() if result == 0: return True
[ "def", "check_switch_started", "(", "self", ",", "pid", ")", ":", "while", "True", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "\"/proc\"", ",", "str", "(", "pid", ")", ")", ")", ":", "return", "F...
https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/mininet/p4_mininet.py#L94-L109
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/push/search/util/search_schema_table_util.py
python
SearchSchemaTableUtil.__init__
(self, poi_db_connection)
Inits SearchSchemaTableUtil. Args: poi_db_connection: gepoi database coneection.
Inits SearchSchemaTableUtil.
[ "Inits", "SearchSchemaTableUtil", "." ]
def __init__(self, poi_db_connection): """Inits SearchSchemaTableUtil. Args: poi_db_connection: gepoi database coneection. """ self._poi_db_connection = poi_db_connection
[ "def", "__init__", "(", "self", ",", "poi_db_connection", ")", ":", "self", ".", "_poi_db_connection", "=", "poi_db_connection" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/push/search/util/search_schema_table_util.py#L37-L43
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/ragged/ragged_shape.py
python
RaggedShape._with_num_row_partitions
(self, num_row_partitions)
Creates an identical shape with the given num_row_partitions. Note that the shape must be statically refactorable to this rank. In particular: * rank must be known. * num_row_partitions must be a nonnegative int. * num_row_partitions must be less than the rank of the shape * num_row_partitions must be greater or equal to the index of any ragged dimension. Note that if the num_row_partitions is the same, self is returned. Args: num_row_partitions: the target num_row_partitions (must be a nonnegative int). Returns: a shape with a (possibly) different num_row_partitions. Raises: ValueError: if the rank is unknown, the argument is not a nonnegative int, or there is a dimension that is nonuniform.
Creates an identical shape with the given num_row_partitions.
[ "Creates", "an", "identical", "shape", "with", "the", "given", "num_row_partitions", "." ]
def _with_num_row_partitions(self, num_row_partitions): """Creates an identical shape with the given num_row_partitions. Note that the shape must be statically refactorable to this rank. In particular: * rank must be known. * num_row_partitions must be a nonnegative int. * num_row_partitions must be less than the rank of the shape * num_row_partitions must be greater or equal to the index of any ragged dimension. Note that if the num_row_partitions is the same, self is returned. Args: num_row_partitions: the target num_row_partitions (must be a nonnegative int). Returns: a shape with a (possibly) different num_row_partitions. Raises: ValueError: if the rank is unknown, the argument is not a nonnegative int, or there is a dimension that is nonuniform. """ rank = self.rank if rank is None: raise ValueError("Rank must be known to adjust num_row_partitions") if not isinstance(num_row_partitions, int): raise ValueError("num_row_partitions must be an int") if num_row_partitions < 0: raise ValueError("num_row_partitions must be nonnegative") if num_row_partitions == self.num_row_partitions: return self if num_row_partitions >= rank: raise ValueError("num_row_partitions must be less than rank") if num_row_partitions > self.num_row_partitions: num_row_partitions_diff = num_row_partitions - self.num_row_partitions new_inner_rank = self.rank - num_row_partitions nvals = self._inner_shape_dim(0) more_rp = [] for i in range(num_row_partitions_diff): nrows = nvals row_length = self._inner_shape_dim(i + 1) nvals = nrows * row_length rp = RowPartition.from_uniform_row_length( row_length, nrows=nrows, dtype=self.dtype) more_rp.append(rp) alt_inner = self._alt_inner_shape(new_inner_rank) return RaggedShape( list(self.row_partitions) + more_rp, alt_inner) else: assert num_row_partitions < self.num_row_partitions return RaggedShape(self.row_partitions[:num_row_partitions], self._alt_inner_shape(self.rank - num_row_partitions))
[ "def", "_with_num_row_partitions", "(", "self", ",", "num_row_partitions", ")", ":", "rank", "=", "self", ".", "rank", "if", "rank", "is", "None", ":", "raise", "ValueError", "(", "\"Rank must be known to adjust num_row_partitions\"", ")", "if", "not", "isinstance",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_shape.py#L677-L730
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Tools/pybench/pybench.py
python
Test.compatible
(self, other)
return 1
Return 1/0 depending on whether the test is compatible with the other Test instance or not.
Return 1/0 depending on whether the test is compatible with the other Test instance or not.
[ "Return", "1", "/", "0", "depending", "on", "whether", "the", "test", "is", "compatible", "with", "the", "other", "Test", "instance", "or", "not", "." ]
def compatible(self, other): """ Return 1/0 depending on whether the test is compatible with the other Test instance or not. """ if self.version != other.version: return 0 if self.rounds != other.rounds: return 0 return 1
[ "def", "compatible", "(", "self", ",", "other", ")", ":", "if", "self", ".", "version", "!=", "other", ".", "version", ":", "return", "0", "if", "self", ".", "rounds", "!=", "other", ".", "rounds", ":", "return", "0", "return", "1" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/pybench/pybench.py#L252-L262
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/training/coordinator.py
python
LooperThread.start_loop
(self)
Called when the thread starts.
Called when the thread starts.
[ "Called", "when", "the", "thread", "starts", "." ]
def start_loop(self): """Called when the thread starts.""" pass
[ "def", "start_loop", "(", "self", ")", ":", "pass" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/coordinator.py#L497-L499
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py
python
Maildir.flush
(self)
Write any pending changes to disk.
Write any pending changes to disk.
[ "Write", "any", "pending", "changes", "to", "disk", "." ]
def flush(self): """Write any pending changes to disk.""" # Maildir changes are always written immediately, so there's nothing # to do. pass
[ "def", "flush", "(", "self", ")", ":", "# Maildir changes are always written immediately, so there's nothing", "# to do.", "pass" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py#L395-L399
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
ConfigBase.WriteInt
(*args, **kwargs)
return _misc_.ConfigBase_WriteInt(*args, **kwargs)
WriteInt(self, String key, long value) -> bool write the value (return True on success)
WriteInt(self, String key, long value) -> bool
[ "WriteInt", "(", "self", "String", "key", "long", "value", ")", "-", ">", "bool" ]
def WriteInt(*args, **kwargs): """ WriteInt(self, String key, long value) -> bool write the value (return True on success) """ return _misc_.ConfigBase_WriteInt(*args, **kwargs)
[ "def", "WriteInt", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_WriteInt", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3295-L3301
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/re.py
python
escape
(pattern)
Escape special characters in a string.
Escape special characters in a string.
[ "Escape", "special", "characters", "in", "a", "string", "." ]
def escape(pattern): """ Escape special characters in a string. """ if isinstance(pattern, str): return pattern.translate(_special_chars_map) else: pattern = str(pattern, 'latin1') return pattern.translate(_special_chars_map).encode('latin1')
[ "def", "escape", "(", "pattern", ")", ":", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "return", "pattern", ".", "translate", "(", "_special_chars_map", ")", "else", ":", "pattern", "=", "str", "(", "pattern", ",", "'latin1'", ")", "return"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/re.py#L270-L278
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/constraints/nonpos.py
python
Inequality.size
(self)
return self.expr.size
int : The size of the constrained expression.
int : The size of the constrained expression.
[ "int", ":", "The", "size", "of", "the", "constrained", "expression", "." ]
def size(self): """int : The size of the constrained expression.""" return self.expr.size
[ "def", "size", "(", "self", ")", ":", "return", "self", ".", "expr", ".", "size" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/constraints/nonpos.py#L176-L178
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
_AddWinLinkRules
(master_ninja, embed_manifest)
Adds link rules for Windows platform to |master_ninja|.
Adds link rules for Windows platform to |master_ninja|.
[ "Adds", "link", "rules", "for", "Windows", "platform", "to", "|master_ninja|", "." ]
def _AddWinLinkRules(master_ninja, embed_manifest): """Adds link rules for Windows platform to |master_ninja|.""" def FullLinkCommand(ldcmd, out, binary_type): resource_name = {"exe": "1", "dll": "2"}[binary_type] return ( "%(python)s gyp-win-tool link-with-manifests $arch %(embed)s " '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' "$manifests" % { "python": sys.executable, "out": out, "ldcmd": ldcmd, "resname": resource_name, "embed": embed_manifest, } ) rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest) use_separate_mspdbsrv = int(os.environ.get("GYP_USE_SEPARATE_MSPDBSRV", "0")) != 0 dlldesc = "LINK%s(DLL) $binary" % rule_name_suffix.upper() dllcmd = ( "%s gyp-win-tool link-wrapper $arch %s " "$ld /nologo $implibflag /DLL /OUT:$binary " "@$binary.rsp" % (sys.executable, use_separate_mspdbsrv) ) dllcmd = FullLinkCommand(dllcmd, "$binary", "dll") master_ninja.rule( "solink" + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile="$binary.rsp", rspfile_content="$libs $in_newline $ldflags", restat=True, pool="link_pool", ) master_ninja.rule( "solink_module" + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile="$binary.rsp", rspfile_content="$libs $in_newline $ldflags", restat=True, pool="link_pool", ) # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. exe_cmd = ( "%s gyp-win-tool link-wrapper $arch %s " "$ld /nologo /OUT:$binary @$binary.rsp" % (sys.executable, use_separate_mspdbsrv) ) exe_cmd = FullLinkCommand(exe_cmd, "$binary", "exe") master_ninja.rule( "link" + rule_name_suffix, description="LINK%s $binary" % rule_name_suffix.upper(), command=exe_cmd, rspfile="$binary.rsp", rspfile_content="$in_newline $libs $ldflags", pool="link_pool", )
[ "def", "_AddWinLinkRules", "(", "master_ninja", ",", "embed_manifest", ")", ":", "def", "FullLinkCommand", "(", "ldcmd", ",", "out", ",", "binary_type", ")", ":", "resource_name", "=", "{", "\"exe\"", ":", "\"1\"", ",", "\"dll\"", ":", "\"2\"", "}", "[", "...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L2149-L2209
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsmolecule.py
python
LibmintsMolecule.set_basis_all_atoms
(self, name, role="BASIS")
Assigns basis *name* to all atoms.
Assigns basis *name* to all atoms.
[ "Assigns", "basis", "*", "name", "*", "to", "all", "atoms", "." ]
def set_basis_all_atoms(self, name, role="BASIS"): """Assigns basis *name* to all atoms.""" for atom in self.full_atoms: atom.set_basisset(name, role)
[ "def", "set_basis_all_atoms", "(", "self", ",", "name", ",", "role", "=", "\"BASIS\"", ")", ":", "for", "atom", "in", "self", ".", "full_atoms", ":", "atom", ".", "set_basisset", "(", "name", ",", "role", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L1634-L1637
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/signaltools.py
python
_numeric_arrays
(arrays, kinds='buifc')
return True
See if a list of arrays are all numeric. Parameters ---------- ndarrays : array or list of arrays arrays to check if numeric. numeric_kinds : string-like The dtypes of the arrays to be checked. If the dtype.kind of the ndarrays are not in this string the function returns False and otherwise returns True.
See if a list of arrays are all numeric.
[ "See", "if", "a", "list", "of", "arrays", "are", "all", "numeric", "." ]
def _numeric_arrays(arrays, kinds='buifc'): """ See if a list of arrays are all numeric. Parameters ---------- ndarrays : array or list of arrays arrays to check if numeric. numeric_kinds : string-like The dtypes of the arrays to be checked. If the dtype.kind of the ndarrays are not in this string the function returns False and otherwise returns True. """ if type(arrays) == ndarray: return arrays.dtype.kind in kinds for array_ in arrays: if array_.dtype.kind not in kinds: return False return True
[ "def", "_numeric_arrays", "(", "arrays", ",", "kinds", "=", "'buifc'", ")", ":", "if", "type", "(", "arrays", ")", "==", "ndarray", ":", "return", "arrays", ".", "dtype", ".", "kind", "in", "kinds", "for", "array_", "in", "arrays", ":", "if", "array_",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/signaltools.py#L443-L461
daijifeng001/caffe-rfcn
543f8f6a4b7c88256ea1445ae951a12d1ad9cffd
scripts/cpp_lint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on compound # literals. closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or Search(r'\s+=\s*$', line_prefix)): match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", ...
https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/scripts/cpp_lint.py#L3069-L3240
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/cachecontrol/heuristics.py
python
BaseHeuristic.update_headers
(self, response)
return {}
Update the response headers with any new headers. NOTE: This SHOULD always include some Warning header to signify that the response was cached by the client, not by way of the provided headers.
Update the response headers with any new headers.
[ "Update", "the", "response", "headers", "with", "any", "new", "headers", "." ]
def update_headers(self, response): """Update the response headers with any new headers. NOTE: This SHOULD always include some Warning header to signify that the response was cached by the client, not by way of the provided headers. """ return {}
[ "def", "update_headers", "(", "self", ",", "response", ")", ":", "return", "{", "}" ]
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/cachecontrol/heuristics.py#L33-L40
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
SizerFlags.GetBorderInPixels
(*args, **kwargs)
return _core_.SizerFlags_GetBorderInPixels(*args, **kwargs)
GetBorderInPixels(self) -> int Returns the border value in pixels to be used in the sizer item.
GetBorderInPixels(self) -> int
[ "GetBorderInPixels", "(", "self", ")", "-", ">", "int" ]
def GetBorderInPixels(*args, **kwargs): """ GetBorderInPixels(self) -> int Returns the border value in pixels to be used in the sizer item. """ return _core_.SizerFlags_GetBorderInPixels(*args, **kwargs)
[ "def", "GetBorderInPixels", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SizerFlags_GetBorderInPixels", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13943-L13949
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/httplib.py
python
HTTP.getfile
(self)
return self.file
Provide a getfile, since the superclass' does not use this concept.
Provide a getfile, since the superclass' does not use this concept.
[ "Provide", "a", "getfile", "since", "the", "superclass", "does", "not", "use", "this", "concept", "." ]
def getfile(self): "Provide a getfile, since the superclass' does not use this concept." return self.file
[ "def", "getfile", "(", "self", ")", ":", "return", "self", ".", "file" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/httplib.py#L1103-L1105
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/utils/misc/grep-svn-log.py
python
Log.add_line
(self, a_line)
Add a line to the content, if there is a previous line, commit it.
Add a line to the content, if there is a previous line, commit it.
[ "Add", "a", "line", "to", "the", "content", "if", "there", "is", "a", "previous", "line", "commit", "it", "." ]
def add_line(self, a_line): """Add a line to the content, if there is a previous line, commit it.""" global separator if self.prev_line is not None: print >> self, self.prev_line self.prev_line = a_line self.separator_added = (a_line == separator)
[ "def", "add_line", "(", "self", ",", "a_line", ")", ":", "global", "separator", "if", "self", ".", "prev_line", "is", "not", "None", ":", "print", ">>", "self", ",", "self", ".", "prev_line", "self", ".", "prev_line", "=", "a_line", "self", ".", "separ...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/misc/grep-svn-log.py#L31-L37
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/ctc/captcha_generator.py
python
CaptchaGen.__init__
(self, h, w, font_paths)
Parameters ---------- h: int Height of the generated images w: int Width of the generated images font_paths: list of str List of all fonts in ttf format
Parameters ---------- h: int Height of the generated images w: int Width of the generated images font_paths: list of str List of all fonts in ttf format
[ "Parameters", "----------", "h", ":", "int", "Height", "of", "the", "generated", "images", "w", ":", "int", "Width", "of", "the", "generated", "images", "font_paths", ":", "list", "of", "str", "List", "of", "all", "fonts", "in", "ttf", "format" ]
def __init__(self, h, w, font_paths): """ Parameters ---------- h: int Height of the generated images w: int Width of the generated images font_paths: list of str List of all fonts in ttf format """ self.captcha = ImageCaptcha(fonts=font_paths) self.h = h self.w = w
[ "def", "__init__", "(", "self", ",", "h", ",", "w", ",", "font_paths", ")", ":", "self", ".", "captcha", "=", "ImageCaptcha", "(", "fonts", "=", "font_paths", ")", "self", ".", "h", "=", "h", "self", ".", "w", "=", "w" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/ctc/captcha_generator.py#L33-L46
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/tracking/data_structures.py
python
wrap_or_unwrap
(value)
Wraps input value into trackable data structures. This is mostly useful for containers like list, dict, etc, which could contain trackable objects in it. Wrapped data structure will be tracked when associated with a `tf.Module`, so that save model/checkpoint can properly track the dependency. It will also unwrap NoDependency objects. Args: value: the input object to be wrapped. Returns: Wrapped trackable data structure.
Wraps input value into trackable data structures.
[ "Wraps", "input", "value", "into", "trackable", "data", "structures", "." ]
def wrap_or_unwrap(value): """Wraps input value into trackable data structures. This is mostly useful for containers like list, dict, etc, which could contain trackable objects in it. Wrapped data structure will be tracked when associated with a `tf.Module`, so that save model/checkpoint can properly track the dependency. It will also unwrap NoDependency objects. Args: value: the input object to be wrapped. Returns: Wrapped trackable data structure. """ # pylint: disable=unidiomatic-typecheck # Exact type checking to avoid mucking up custom logic in list/dict # subclasses, e.g. collections.Counter. if isinstance(value, NoDependency): return value.value if isinstance(value, base.Trackable): return value # Skip conversion for already trackable objects. elif type(value) == dict: return _DictWrapper(value) elif type(value) == collections.OrderedDict: return _DictWrapper(value) elif type(value) == list: return ListWrapper(value) elif isinstance(value, tuple) and _should_wrap_tuple(value): # There are trackable elements or data structures. Wrap the tuple. return _TupleWrapper(value) else: return value
[ "def", "wrap_or_unwrap", "(", "value", ")", ":", "# pylint: disable=unidiomatic-typecheck", "# Exact type checking to avoid mucking up custom logic in list/dict", "# subclasses, e.g. collections.Counter.", "if", "isinstance", "(", "value", ",", "NoDependency", ")", ":", "return", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/tracking/data_structures.py#L95-L128
brndnmtthws/conky
8f5014b90f1bc9f999beff752a9b369e4885f0d6
cmake/scripts/clang-format-check-changed.py
python
get_changed_files
(git_bin, excludes, file_extensions)
return output, returncode
Run git status and return the list of changed files
Run git status and return the list of changed files
[ "Run", "git", "status", "and", "return", "the", "list", "of", "changed", "files" ]
def get_changed_files(git_bin, excludes, file_extensions): """ Run git status and return the list of changed files """ extensions = file_extensions.split(",") # arguments coming from cmake will be *.xx. We want to remove the * for i, extension in enumerate(extensions): if extension[0] == '*': extensions[i] = extension[1:] git_root = get_git_root(git_bin) cmd = [git_bin, "status", "--porcelain", "--ignore-submodules"] print("git cmd = {}".format(cmd)) output = [] returncode = 0 try: cmd_output = subprocess.check_output(cmd) for line in cmd_output.split('\n'): if len(line) > 0: file = clean_git_filename(line) if not file: continue file = os.path.join(git_root, file) if file[-1] == "/": directory_files = check_directory( file, excludes, file_extensions) output = output + directory_files else: if check_file(file, excludes, file_extensions): print("Will check file [{}]".format(file)) output.append(file) except subprocess.CalledProcessError, e: print("Error calling git [{}]".format(e)) returncode = e.returncode return output, returncode
[ "def", "get_changed_files", "(", "git_bin", ",", "excludes", ",", "file_extensions", ")", ":", "extensions", "=", "file_extensions", ".", "split", "(", "\",\"", ")", "# arguments coming from cmake will be *.xx. We want to remove the *", "for", "i", ",", "extension", "in...
https://github.com/brndnmtthws/conky/blob/8f5014b90f1bc9f999beff752a9b369e4885f0d6/cmake/scripts/clang-format-check-changed.py#L76-L114
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/fractions.py
python
Fraction._richcmp
(self, other, op)
Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators.
Helper for comparison operators, for internal use only.
[ "Helper", "for", "comparison", "operators", "for", "internal", "use", "only", "." ]
def _richcmp(self, other, op): """Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. """ # convert other to a Rational instance where reasonable. if isinstance(other, numbers.Rational): return op(self._numerator * other.denominator, self._denominator * other.numerator) if isinstance(other, float): if math.isnan(other) or math.isinf(other): return op(0.0, other) else: return op(self, self.from_float(other)) else: return NotImplemented
[ "def", "_richcmp", "(", "self", ",", "other", ",", "op", ")", ":", "# convert other to a Rational instance where reasonable.", "if", "isinstance", "(", "other", ",", "numbers", ".", "Rational", ")", ":", "return", "op", "(", "self", ".", "_numerator", "*", "ot...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/fractions.py#L588-L608
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_edit_arch_objects.py
python
ArchWallGuiTools.update_object_from_edit_points
(self, obj, node_idx, v, alt_edit_mode=0)
if node_idx == 0: edit_arch.updateWall(obj, node_idx, v) elif node_idx > 0: if obj.Base: if utils.get_type(obj.Base) in ["Wire", "Circle", "Rectangle", "Polygon", "Sketch"]: self.update(obj.Base, node_idx - 1, v)
if node_idx == 0: edit_arch.updateWall(obj, node_idx, v) elif node_idx > 0: if obj.Base: if utils.get_type(obj.Base) in ["Wire", "Circle", "Rectangle", "Polygon", "Sketch"]: self.update(obj.Base, node_idx - 1, v)
[ "if", "node_idx", "==", "0", ":", "edit_arch", ".", "updateWall", "(", "obj", "node_idx", "v", ")", "elif", "node_idx", ">", "0", ":", "if", "obj", ".", "Base", ":", "if", "utils", ".", "get_type", "(", "obj", ".", "Base", ")", "in", "[", "Wire", ...
def update_object_from_edit_points(self, obj, node_idx, v, alt_edit_mode=0): ''' if node_idx == 0: edit_arch.updateWall(obj, node_idx, v) elif node_idx > 0: if obj.Base: if utils.get_type(obj.Base) in ["Wire", "Circle", "Rectangle", "Polygon", "Sketch"]: self.update(obj.Base, node_idx - 1, v)''' if node_idx == 0: vz = DraftVecUtils.project(v, App.Vector(0, 0, 1)) if vz.Length > 0: obj.Height = vz.Length
[ "def", "update_object_from_edit_points", "(", "self", ",", "obj", ",", "node_idx", ",", "v", ",", "alt_edit_mode", "=", "0", ")", ":", "if", "node_idx", "==", "0", ":", "vz", "=", "DraftVecUtils", ".", "project", "(", "v", ",", "App", ".", "Vector", "(...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_edit_arch_objects.py#L63-L74
mandliya/algorithms_and_data_structures
60f95dae236d13bd17f20df63268b524a776c8e1
tree_problems/level_order_tree_traversal_recursive.py
python
Tree.height
(self)
return self.height_util(self.root)
Height of the tree
Height of the tree
[ "Height", "of", "the", "tree" ]
def height(self): """Height of the tree""" return self.height_util(self.root)
[ "def", "height", "(", "self", ")", ":", "return", "self", ".", "height_util", "(", "self", ".", "root", ")" ]
https://github.com/mandliya/algorithms_and_data_structures/blob/60f95dae236d13bd17f20df63268b524a776c8e1/tree_problems/level_order_tree_traversal_recursive.py#L42-L44
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/_header_value_parser.py
python
parse_content_transfer_encoding_header
(value)
return cte_header
mechanism
mechanism
[ "mechanism" ]
def parse_content_transfer_encoding_header(value): """ mechanism """ # We should probably validate the values, since the list is fixed. cte_header = ContentTransferEncoding() if not value: cte_header.defects.append(errors.HeaderMissingRequiredValue( "Missing content transfer encoding")) return cte_header try: token, value = get_token(value) except errors.HeaderParseError: cte_header.defects.append(errors.InvalidHeaderDefect( "Expected content transfer encoding but found {!r}".format(value))) else: cte_header.append(token) cte_header.cte = token.value.strip().lower() if not value: return cte_header while value: cte_header.defects.append(errors.InvalidHeaderDefect( "Extra text after content transfer encoding")) if value[0] in PHRASE_ENDS: cte_header.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] else: token, value = get_phrase(value) cte_header.append(token) return cte_header
[ "def", "parse_content_transfer_encoding_header", "(", "value", ")", ":", "# We should probably validate the values, since the list is fixed.", "cte_header", "=", "ContentTransferEncoding", "(", ")", "if", "not", "value", ":", "cte_header", ".", "defects", ".", "append", "("...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/_header_value_parser.py#L2589-L2618
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/ilink.py
python
generate
(env)
Add Builders and construction variables for ilink to an Environment.
Add Builders and construction variables for ilink to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "ilink", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for ilink to an Environment.""" SCons.Tool.createProgBuilder(env) env['LINK'] = 'ilink' env['LINKFLAGS'] = SCons.Util.CLVar('') env['LINKCOM'] = '$LINK $LINKFLAGS /O:$TARGET $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' env['LIBDIRPREFIX']='/LIBPATH:' env['LIBDIRSUFFIX']='' env['LIBLINKPREFIX']='' env['LIBLINKSUFFIX']='$LIBSUFFIX'
[ "def", "generate", "(", "env", ")", ":", "SCons", ".", "Tool", ".", "createProgBuilder", "(", "env", ")", "env", "[", "'LINK'", "]", "=", "'ilink'", "env", "[", "'LINKFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "env", "["...
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/Tool/ilink.py#L40-L50
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py
python
SpawnBase.flush
(self)
This does nothing. It is here to support the interface for a File-like object.
This does nothing. It is here to support the interface for a File-like object.
[ "This", "does", "nothing", ".", "It", "is", "here", "to", "support", "the", "interface", "for", "a", "File", "-", "like", "object", "." ]
def flush(self): '''This does nothing. It is here to support the interface for a File-like object. ''' pass
[ "def", "flush", "(", "self", ")", ":", "pass" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L506-L509
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/bindings/python/clang/cindex.py
python
Type.is_pod
(self)
return conf.lib.clang_isPODType(self)
Determine whether this Type represents plain old data (POD).
Determine whether this Type represents plain old data (POD).
[ "Determine", "whether", "this", "Type", "represents", "plain", "old", "data", "(", "POD", ")", "." ]
def is_pod(self): """Determine whether this Type represents plain old data (POD).""" return conf.lib.clang_isPODType(self)
[ "def", "is_pod", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isPODType", "(", "self", ")" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L2326-L2328
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/boosted_trees/python/ops/quantile_ops.py
python
QuantileAccumulator.get_buckets
(self, stamp_token)
return are_buckets_ready[0], buckets[0]
Returns quantile buckets created during previous flush.
Returns quantile buckets created during previous flush.
[ "Returns", "quantile", "buckets", "created", "during", "previous", "flush", "." ]
def get_buckets(self, stamp_token): """Returns quantile buckets created during previous flush.""" are_buckets_ready, buckets = ( gen_quantile_ops.quantile_accumulator_get_buckets( quantile_accumulator_handles=[self._quantile_accumulator_handle], stamp_token=stamp_token)) return are_buckets_ready[0], buckets[0]
[ "def", "get_buckets", "(", "self", ",", "stamp_token", ")", ":", "are_buckets_ready", ",", "buckets", "=", "(", "gen_quantile_ops", ".", "quantile_accumulator_get_buckets", "(", "quantile_accumulator_handles", "=", "[", "self", ".", "_quantile_accumulator_handle", "]", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/boosted_trees/python/ops/quantile_ops.py#L120-L126
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
MirrorDC.__init__
(self, *args, **kwargs)
__init__(self, DC dc, bool mirror) -> MirrorDC Creates a mirrored DC associated with the real *dc*. Everything drawn on the wx.MirrorDC will appear on the *dc*, and will be mirrored if *mirror* is True.
__init__(self, DC dc, bool mirror) -> MirrorDC
[ "__init__", "(", "self", "DC", "dc", "bool", "mirror", ")", "-", ">", "MirrorDC" ]
def __init__(self, *args, **kwargs): """ __init__(self, DC dc, bool mirror) -> MirrorDC Creates a mirrored DC associated with the real *dc*. Everything drawn on the wx.MirrorDC will appear on the *dc*, and will be mirrored if *mirror* is True. """ _gdi_.MirrorDC_swiginit(self,_gdi_.new_MirrorDC(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "MirrorDC_swiginit", "(", "self", ",", "_gdi_", ".", "new_MirrorDC", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L5345-L5353
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/numpy/math_ops.py
python
average
(x, axis=None, weights=None, returned=False)
return x_avg
Computes the weighted average along the specified axis. Args: x (Tensor): A Tensor to be averaged. axis (Union[None, int, tuple(int)]): Axis along which to average `x`. Default: `None`. If the axis is `None`, it will average over all of the elements of the tensor `x`. If the axis is negative, it counts from the last to the first axis. weights (Union[None, Tensor]): Weights associated with the values in `x`. Default: `None`. If `weights` is `None`, all the data in `x` are assumed to have a weight equal to one. If `weights` is 1-D tensor, the length must be the same as the given axis. Otherwise, `weights` should have the same shape as `x`. returned (bool): Default: `False`. If `True`, the tuple (average, sum_of_weights) is returned. If `False`, only the average is returned. Returns: Averaged Tensor. If returned is `True`, return tuple. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import mindspore.numpy as np >>> input_x = np.array([[1., 2.], [3., 4.]]) >>> output = np.average(input_x, axis=0, weights=input_x, returned=True) >>> print(output) (Tensor(shape=[2], dtype=Float32, value= [ 2.50000000e+00, 3.33333325e+00]), Tensor(shape=[2], dtype=Float32, value= [ 4.00000000e+00, 6.00000000e+00]))
Computes the weighted average along the specified axis.
[ "Computes", "the", "weighted", "average", "along", "the", "specified", "axis", "." ]
def average(x, axis=None, weights=None, returned=False): """ Computes the weighted average along the specified axis. Args: x (Tensor): A Tensor to be averaged. axis (Union[None, int, tuple(int)]): Axis along which to average `x`. Default: `None`. If the axis is `None`, it will average over all of the elements of the tensor `x`. If the axis is negative, it counts from the last to the first axis. weights (Union[None, Tensor]): Weights associated with the values in `x`. Default: `None`. If `weights` is `None`, all the data in `x` are assumed to have a weight equal to one. If `weights` is 1-D tensor, the length must be the same as the given axis. Otherwise, `weights` should have the same shape as `x`. returned (bool): Default: `False`. If `True`, the tuple (average, sum_of_weights) is returned. If `False`, only the average is returned. Returns: Averaged Tensor. If returned is `True`, return tuple. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import mindspore.numpy as np >>> input_x = np.array([[1., 2.], [3., 4.]]) >>> output = np.average(input_x, axis=0, weights=input_x, returned=True) >>> print(output) (Tensor(shape=[2], dtype=Float32, value= [ 2.50000000e+00, 3.33333325e+00]), Tensor(shape=[2], dtype=Float32, value= [ 4.00000000e+00, 6.00000000e+00])) """ _check_input_tensor(x) if axis is not None: _check_axis_type(axis, True, True, False) axis = _canonicalize_axis(axis, x.ndim) x_avg = full((), nan, F.dtype(x)) sum_of_weights = None if weights is None: x_avg = mean(x, axis) sum_of_weights = compute_weights_for_mean(x, x_avg, axis) else: _check_input_tensor(weights) if x.shape == weights.shape: x_avg, sum_of_weights = comput_avg(x, axis, weights) elif F.rank(weights) == 1: if not isinstance(axis, int): _raise_type_error("Axis must be specified when shapes of x and weights differ.") perm = _expanded_shape(x.ndim, weights.shape[0], axis) weights = weights.reshape(perm) x_avg, sum_of_weights = comput_avg(x, axis, weights) else: _raise_type_error("Weights should be None, 1-D or the same shape as input x.") if returned: if x_avg.shape != sum_of_weights.shape: sum_of_weights = _broadcast_to(sum_of_weights, sum_of_weights.shape, x_avg.shape, x_avg.ndim) return (x_avg, sum_of_weights) return x_avg
[ "def", "average", "(", "x", ",", "axis", "=", "None", ",", "weights", "=", "None", ",", "returned", "=", "False", ")", ":", "_check_input_tensor", "(", "x", ")", "if", "axis", "is", "not", "None", ":", "_check_axis_type", "(", "axis", ",", "True", ",...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L1000-L1059
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/resmokelib/sighandler.py
python
_dump_stacks
(logger, header_msg)
Signal handler that will dump the stacks of all threads.
Signal handler that will dump the stacks of all threads.
[ "Signal", "handler", "that", "will", "dump", "the", "stacks", "of", "all", "threads", "." ]
def _dump_stacks(logger, header_msg): """ Signal handler that will dump the stacks of all threads. """ sb = [] sb.append(header_msg) frames = sys._current_frames() sb.append("Total threads: %d" % (len(frames))) sb.append("") for thread_id in frames: stack = frames[thread_id] sb.append("Thread %d:" % (thread_id)) sb.append("".join(traceback.format_stack(stack))) logger.info("\n".join(sb))
[ "def", "_dump_stacks", "(", "logger", ",", "header_msg", ")", ":", "sb", "=", "[", "]", "sb", ".", "append", "(", "header_msg", ")", "frames", "=", "sys", ".", "_current_frames", "(", ")", "sb", ".", "append", "(", "\"Total threads: %d\"", "%", "(", "l...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/sighandler.py#L102-L119
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/name.py
python
Name.canonicalize
(self)
return Name([x.lower() for x in self.labels])
Return a name which is equal to the current name, but is in DNSSEC canonical form. @rtype: dns.name.Name object
Return a name which is equal to the current name, but is in DNSSEC canonical form.
[ "Return", "a", "name", "which", "is", "equal", "to", "the", "current", "name", "but", "is", "in", "DNSSEC", "canonical", "form", "." ]
def canonicalize(self): """Return a name which is equal to the current name, but is in DNSSEC canonical form. @rtype: dns.name.Name object """ return Name([x.lower() for x in self.labels])
[ "def", "canonicalize", "(", "self", ")", ":", "return", "Name", "(", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "self", ".", "labels", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/name.py#L261-L267
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/shapedbutton.py
python
__SToggleMixin.OnLeftUp
(self, event)
Handles the ``wx.EVT_LEFT_UP`` event for the button. :param `event`: a :class:`MouseEvent` event to be processed.
Handles the ``wx.EVT_LEFT_UP`` event for the button.
[ "Handles", "the", "wx", ".", "EVT_LEFT_UP", "event", "for", "the", "button", "." ]
def OnLeftUp(self, event): """ Handles the ``wx.EVT_LEFT_UP`` event for the button. :param `event`: a :class:`MouseEvent` event to be processed. """ if not self.IsEnabled() or not self.HasCapture(): return if self.HasCapture(): if self._isup != self._saveup: self.Notify() self.ReleaseMouse() self.Refresh()
[ "def", "OnLeftUp", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "IsEnabled", "(", ")", "or", "not", "self", ".", "HasCapture", "(", ")", ":", "return", "if", "self", ".", "HasCapture", "(", ")", ":", "if", "self", ".", "_isup", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shapedbutton.py#L1310-L1326
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/mxnet/executor.py
python
Executor.backward
(self, out_grads=None)
Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray, optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs that are not a loss function.
Do backward pass to get the gradient of arguments.
[ "Do", "backward", "pass", "to", "get", "the", "gradient", "of", "arguments", "." ]
def backward(self, out_grads=None): """Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray, optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs that are not a loss function. """ if out_grads is None: out_grads = [] elif isinstance(out_grads, NDArray): out_grads = [out_grads] for obj in out_grads: if not isinstance(obj, NDArray): raise TypeError("inputs must be NDArray") ndarray = c_array(NDArrayHandle, [item.handle for item in out_grads]) check_call(_LIB.MXExecutorBackward( self.handle, mx_uint(len(out_grads)), ndarray))
[ "def", "backward", "(", "self", ",", "out_grads", "=", "None", ")", ":", "if", "out_grads", "is", "None", ":", "out_grads", "=", "[", "]", "elif", "isinstance", "(", "out_grads", ",", "NDArray", ")", ":", "out_grads", "=", "[", "out_grads", "]", "for",...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/executor.py#L115-L137
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
commonTools/release/updateTrilinosDB.py
python
write_to_csv
(filepath, package_db)
Use the csv module to write the contents of the package database to a comma-separated value file.
Use the csv module to write the contents of the package database to a comma-separated value file.
[ "Use", "the", "csv", "module", "to", "write", "the", "contents", "of", "the", "package", "database", "to", "a", "comma", "-", "separated", "value", "file", "." ]
def write_to_csv(filepath, package_db): """ Use the csv module to write the contents of the package database to a comma-separated value file. """ # Setup trilinosID = get_trilinos_id(package_db) trilinos_dict = package_db[trilinosID] fieldnames = ["package_id", "name", "version", "parent", "maturity", "sub_packages", "required_dep", "optional_dep" ] # Write the file with open(filepath, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for packageID, package in package_db.items(): row = stringify_package_dict(package) row["package_id"] = packageID writer.writerow(row)
[ "def", "write_to_csv", "(", "filepath", ",", "package_db", ")", ":", "# Setup", "trilinosID", "=", "get_trilinos_id", "(", "package_db", ")", "trilinos_dict", "=", "package_db", "[", "trilinosID", "]", "fieldnames", "=", "[", "\"package_id\"", ",", "\"name\"", "...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/commonTools/release/updateTrilinosDB.py#L356-L381
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
MULAN_universal_lesion_analysis/maskrcnn/utils/model_zoo.py
python
cache_url
(url, model_dir=None, progress=True)
return cached_file
r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more digits of the SHA256 hash of the contents of the file. The hash is used to ensure unique names and to verify the contents of the file. The default value of `model_dir` is ``$TORCH_HOME/models`` where ``$TORCH_HOME`` defaults to ``~/.torch``. The default directory can be overridden with the ``$TORCH_MODEL_ZOO`` environment variable. Args: url (string): URL of the object to download model_dir (string, optional): directory in which to save the object progress (bool, optional): whether or not to display a progress bar to stderr Example: >>> cached_file = maskrcnn.utils.model_zoo.cache_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth')
r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more digits of the SHA256 hash of the contents of the file. The hash is used to ensure unique names and to verify the contents of the file. The default value of `model_dir` is ``$TORCH_HOME/models`` where ``$TORCH_HOME`` defaults to ``~/.torch``. The default directory can be overridden with the ``$TORCH_MODEL_ZOO`` environment variable. Args: url (string): URL of the object to download model_dir (string, optional): directory in which to save the object progress (bool, optional): whether or not to display a progress bar to stderr Example: >>> cached_file = maskrcnn.utils.model_zoo.cache_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth')
[ "r", "Loads", "the", "Torch", "serialized", "object", "at", "the", "given", "URL", ".", "If", "the", "object", "is", "already", "present", "in", "model_dir", "it", "s", "deserialized", "and", "returned", ".", "The", "filename", "part", "of", "the", "URL", ...
def cache_url(url, model_dir=None, progress=True): r"""Loads the Torch serialized object at the given URL. If the object is already present in `model_dir`, it's deserialized and returned. The filename part of the URL should follow the naming convention ``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more digits of the SHA256 hash of the contents of the file. The hash is used to ensure unique names and to verify the contents of the file. The default value of `model_dir` is ``$TORCH_HOME/models`` where ``$TORCH_HOME`` defaults to ``~/.torch``. The default directory can be overridden with the ``$TORCH_MODEL_ZOO`` environment variable. Args: url (string): URL of the object to download model_dir (string, optional): directory in which to save the object progress (bool, optional): whether or not to display a progress bar to stderr Example: >>> cached_file = maskrcnn.utils.model_zoo.cache_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth') """ if model_dir is None: torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch')) model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models')) if not os.path.exists(model_dir): os.makedirs(model_dir) parts = urlparse(url) filename = os.path.basename(parts.path) if filename == "model_final.pkl": # workaround as pre-trained Caffe2 models from Detectron have all the same filename # so make the full path the filename by replacing / with _ filename = parts.path.replace("/", "_") cached_file = os.path.join(model_dir, filename) if not os.path.exists(cached_file) and is_main_process(): sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file)) hash_prefix = HASH_REGEX.search(filename) if hash_prefix is not None: hash_prefix = hash_prefix.group(1) # workaround: Caffe2 models don't have a hash, but follow the R-50 convention, # which matches the hash PyTorch uses. So we skip the hash matching # if the hash_prefix is less than 6 characters if len(hash_prefix) < 6: hash_prefix = None _download_url_to_file(url, cached_file, hash_prefix, progress=progress) synchronize() return cached_file
[ "def", "cache_url", "(", "url", ",", "model_dir", "=", "None", ",", "progress", "=", "True", ")", ":", "if", "model_dir", "is", "None", ":", "torch_home", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "getenv", "(", "'TORCH_HOME'", ",", ...
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/MULAN_universal_lesion_analysis/maskrcnn/utils/model_zoo.py#L15-L56
Sigil-Ebook/Sigil
0d145d3a4874b4a26f7aabd68dbd9d18a2402e52
src/Resource_Files/plugin_launchers/python/sigil_bs4/element.py
python
Tag.__nonzero__
(self)
return True
A tag is non-None even if it has no contents.
A tag is non-None even if it has no contents.
[ "A", "tag", "is", "non", "-", "None", "even", "if", "it", "has", "no", "contents", "." ]
def __nonzero__(self): "A tag is non-None even if it has no contents." return True
[ "def", "__nonzero__", "(", "self", ")", ":", "return", "True" ]
https://github.com/Sigil-Ebook/Sigil/blob/0d145d3a4874b4a26f7aabd68dbd9d18a2402e52/src/Resource_Files/plugin_launchers/python/sigil_bs4/element.py#L1010-L1012
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/flatnotebook.py
python
FlatNotebook.GetPageShapeAngle
(self, page_index)
return result, True
Returns the angle associated to a tab.
Returns the angle associated to a tab.
[ "Returns", "the", "angle", "associated", "to", "a", "tab", "." ]
def GetPageShapeAngle(self, page_index): """ Returns the angle associated to a tab. """ if page_index < 0 or page_index >= len(self._pages._pagesInfoVec): return None, False result = self._pages._pagesInfoVec[page_index].GetTabAngle() return result, True
[ "def", "GetPageShapeAngle", "(", "self", ",", "page_index", ")", ":", "if", "page_index", "<", "0", "or", "page_index", ">=", "len", "(", "self", ".", "_pages", ".", "_pagesInfoVec", ")", ":", "return", "None", ",", "False", "result", "=", "self", ".", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L3485-L3492
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/preprocessing/image.py
python
apply_transform
(x, transform_matrix, channel_axis=0, fill_mode='nearest', cval=0.)
return x
Apply the image transformation specified by a matrix. Arguments: x: 2D numpy array, single image. transform_matrix: Numpy array specifying the geometric transformation. channel_axis: Index of axis for channels in the input tensor. fill_mode: Points outside the boundaries of the input are filled according to the given mode (one of `{'constant', 'nearest', 'reflect', 'wrap'}`). cval: Value used for points outside the boundaries of the input if `mode='constant'`. Returns: The transformed version of the input.
Apply the image transformation specified by a matrix.
[ "Apply", "the", "image", "transformation", "specified", "by", "a", "matrix", "." ]
def apply_transform(x, transform_matrix, channel_axis=0, fill_mode='nearest', cval=0.): """Apply the image transformation specified by a matrix. Arguments: x: 2D numpy array, single image. transform_matrix: Numpy array specifying the geometric transformation. channel_axis: Index of axis for channels in the input tensor. fill_mode: Points outside the boundaries of the input are filled according to the given mode (one of `{'constant', 'nearest', 'reflect', 'wrap'}`). cval: Value used for points outside the boundaries of the input if `mode='constant'`. Returns: The transformed version of the input. """ x = np.rollaxis(x, channel_axis, 0) final_affine_matrix = transform_matrix[:2, :2] final_offset = transform_matrix[:2, 2] channel_images = [ ndi.interpolation.affine_transform( x_channel, final_affine_matrix, final_offset, order=0, mode=fill_mode, cval=cval) for x_channel in x ] x = np.stack(channel_images, axis=0) x = np.rollaxis(x, 0, channel_axis + 1) return x
[ "def", "apply_transform", "(", "x", ",", "transform_matrix", ",", "channel_axis", "=", "0", ",", "fill_mode", "=", "'nearest'", ",", "cval", "=", "0.", ")", ":", "x", "=", "np", ".", "rollaxis", "(", "x", ",", "channel_axis", ",", "0", ")", "final_affi...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/preprocessing/image.py#L219-L253
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/six.py
python
with_metaclass
(meta, *bases)
return type.__new__(metaclass, 'temporary_class', (), {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "meta", ")...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/six.py#L800-L809
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.AddOrGetProjectReference
(self, other_pbxproject)
return [product_group, project_ref]
Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary.
Add a reference to another project file (via PBXProject object) to this one.
[ "Add", "a", "reference", "to", "another", "project", "file", "(", "via", "PBXProject", "object", ")", "to", "this", "one", "." ]
def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary. """ if not 'projectReferences' in self._properties: self._properties['projectReferences'] = [] product_group = None project_ref = None if not other_pbxproject in self._other_pbxprojects: # This project file isn't yet linked to the other one. Establish the # link. product_group = PBXGroup({'name': 'Products'}) # ProductGroup is strong. product_group.parent = self # There's nothing unique about this PBXGroup, and if left alone, it will # wind up with the same set of hashables as all other PBXGroup objects # owned by the projectReferences list. Add the hashables of the # remote PBXProject that it's related to. product_group._hashables.extend(other_pbxproject.Hashables()) # The other project reports its path as relative to the same directory # that this project's path is relative to. The other project's path # is not necessarily already relative to this project. Figure out the # pathname that this project needs to use to refer to the other one. this_path = posixpath.dirname(self.Path()) projectDirPath = self.GetProperty('projectDirPath') if projectDirPath: if posixpath.isabs(projectDirPath[0]): this_path = projectDirPath else: this_path = posixpath.join(this_path, projectDirPath) other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) # ProjectRef is weak (it's owned by the mainGroup hierarchy). project_ref = PBXFileReference({ 'lastKnownFileType': 'wrapper.pb-project', 'path': other_path, 'sourceTree': 'SOURCE_ROOT', }) self.ProjectsGroup().AppendChild(project_ref) ref_dict = {'ProductGroup': product_group, 'ProjectRef': project_ref} self._other_pbxprojects[other_pbxproject] = ref_dict self.AppendProperty('projectReferences', ref_dict) # Xcode seems to sort this list case-insensitively self._properties['projectReferences'] = \ sorted(self._properties['projectReferences'], cmp=lambda x,y: cmp(x['ProjectRef'].Name().lower(), y['ProjectRef'].Name().lower())) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict['ProductGroup'] project_ref = project_ref_dict['ProjectRef'] self._SetUpProductReferences(other_pbxproject, product_group, project_ref) return [product_group, project_ref]
[ "def", "AddOrGetProjectReference", "(", "self", ",", "other_pbxproject", ")", ":", "if", "not", "'projectReferences'", "in", "self", ".", "_properties", ":", "self", ".", "_properties", "[", "'projectReferences'", "]", "=", "[", "]", "product_group", "=", "None"...
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/xcodeproj_file.py#L2664-L2736
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py
python
ValidateMSBuildSettings
(settings, stderr=sys.stderr)
Validates that the names of the settings are valid for MSBuild. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages.
Validates that the names of the settings are valid for MSBuild.
[ "Validates", "that", "the", "names", "of", "the", "settings", "are", "valid", "for", "MSBuild", "." ]
def ValidateMSBuildSettings(settings, stderr=sys.stderr): """Validates that the names of the settings are valid for MSBuild. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ _ValidateSettings(_msbuild_validators, settings, stderr)
[ "def", "ValidateMSBuildSettings", "(", "settings", ",", "stderr", "=", "sys", ".", "stderr", ")", ":", "_ValidateSettings", "(", "_msbuild_validators", ",", "settings", ",", "stderr", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L504-L512
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/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/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L2169-L2188
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/framework/tensor_util.py
python
with_shape
(expected_shape, tensor)
return tensor
Asserts tensor has expected shape. If tensor shape and expected_shape, are fully defined, assert they match. Otherwise, add assert op that will validate the shape when tensor is evaluated, and set shape on tensor. Args: expected_shape: Expected shape to assert, as a 1D array of ints, or tensor of same. tensor: Tensor whose shape we're validating. Returns: tensor, perhaps with a dependent assert operation. Raises: ValueError: if tensor has an invalid shape.
Asserts tensor has expected shape.
[ "Asserts", "tensor", "has", "expected", "shape", "." ]
def with_shape(expected_shape, tensor): """Asserts tensor has expected shape. If tensor shape and expected_shape, are fully defined, assert they match. Otherwise, add assert op that will validate the shape when tensor is evaluated, and set shape on tensor. Args: expected_shape: Expected shape to assert, as a 1D array of ints, or tensor of same. tensor: Tensor whose shape we're validating. Returns: tensor, perhaps with a dependent assert operation. Raises: ValueError: if tensor has an invalid shape. """ if isinstance(tensor, sparse_tensor.SparseTensor): raise ValueError('SparseTensor not supported.') # Shape type must be 1D int32. if tensor_util.is_tensor(expected_shape): if expected_shape.dtype.base_dtype != dtypes.int32: raise ValueError( 'Invalid dtype %s for shape %s expected of tensor %s.' % ( expected_shape.dtype, expected_shape, tensor.name)) if isinstance(expected_shape, (list, tuple)): if not expected_shape: expected_shape = np.asarray([], dtype=np.int32) else: np_expected_shape = np.asarray(expected_shape) expected_shape = ( np.asarray(expected_shape, dtype=np.int32) if np_expected_shape.dtype == np.int64 else np_expected_shape) if isinstance(expected_shape, np.ndarray): if expected_shape.ndim > 1: raise ValueError( 'Invalid rank %s for shape %s expected of tensor %s.' % ( expected_shape.ndim, expected_shape, tensor.name)) if expected_shape.dtype != np.int32: raise ValueError( 'Invalid dtype %s for shape %s expected of tensor %s.' % ( expected_shape.dtype, expected_shape, tensor.name)) actual_shape = tensor.get_shape() if (not actual_shape.is_fully_defined() or tensor_util.is_tensor(expected_shape)): with ops.name_scope('%s/' % tensor.op.name, values=[tensor]): if (not tensor_util.is_tensor(expected_shape) and (len(expected_shape) < 1)): # TODO(irving): Remove scalar special case return array_ops.reshape(tensor, []) with ops.control_dependencies([_assert_shape_op(expected_shape, tensor)]): result = array_ops.identity(tensor) if not tensor_util.is_tensor(expected_shape): result.set_shape(expected_shape) return result if (not tensor_util.is_tensor(expected_shape) and not actual_shape.is_compatible_with(expected_shape)): if (len(expected_shape) < 1) and actual_shape.is_compatible_with([1]): # TODO(irving): Remove scalar special case. with ops.name_scope('%s/' % tensor.op.name, values=[tensor]): return array_ops.reshape(tensor, []) raise ValueError('Invalid shape for tensor %s, expected %s, got %s.' % ( tensor.name, expected_shape, actual_shape)) return tensor
[ "def", "with_shape", "(", "expected_shape", ",", "tensor", ")", ":", "if", "isinstance", "(", "tensor", ",", "sparse_tensor", ".", "SparseTensor", ")", ":", "raise", "ValueError", "(", "'SparseTensor not supported.'", ")", "# Shape type must be 1D int32.", "if", "te...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/framework/tensor_util.py#L232-L299
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
DC.GetPen
(*args, **kwargs)
return _gdi_.DC_GetPen(*args, **kwargs)
GetPen(self) -> Pen Gets the current pen
GetPen(self) -> Pen
[ "GetPen", "(", "self", ")", "-", ">", "Pen" ]
def GetPen(*args, **kwargs): """ GetPen(self) -> Pen Gets the current pen """ return _gdi_.DC_GetPen(*args, **kwargs)
[ "def", "GetPen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_GetPen", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L4353-L4359
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/ctrlbox.py
python
ControlBar.GetControlSizer
(self)
return self._sizer
Get the sizer that is used to layout the contols (horizontal sizer) @return: wx.BoxSizer
Get the sizer that is used to layout the contols (horizontal sizer) @return: wx.BoxSizer
[ "Get", "the", "sizer", "that", "is", "used", "to", "layout", "the", "contols", "(", "horizontal", "sizer", ")", "@return", ":", "wx", ".", "BoxSizer" ]
def GetControlSizer(self): """Get the sizer that is used to layout the contols (horizontal sizer) @return: wx.BoxSizer """ return self._sizer
[ "def", "GetControlSizer", "(", "self", ")", ":", "return", "self", ".", "_sizer" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/ctrlbox.py#L486-L491
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/dummy_thread.py
python
interrupt_main
()
Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.
Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.
[ "Set", "_interrupt", "flag", "to", "True", "to", "have", "start_new_thread", "raise", "KeyboardInterrupt", "upon", "exiting", "." ]
def interrupt_main(): """Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
[ "def", "interrupt_main", "(", ")", ":", "if", "_main", ":", "raise", "KeyboardInterrupt", "else", ":", "global", "_interrupt", "_interrupt", "=", "True" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/dummy_thread.py#L138-L145
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor.py
python
Descriptor.EnumValueName
(self, enum, value)
return self.enum_types_by_name[enum].values_by_number[value].name
Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the value is not a valid value for the enum.
Returns the string name of an enum value.
[ "Returns", "the", "string", "name", "of", "an", "enum", "value", "." ]
def EnumValueName(self, enum, value): """Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the value is not a valid value for the enum. """ return self.enum_types_by_name[enum].values_by_number[value].name
[ "def", "EnumValueName", "(", "self", ",", "enum", ",", "value", ")", ":", "return", "self", ".", "enum_types_by_name", "[", "enum", "]", ".", "values_by_number", "[", "value", "]", ".", "name" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor.py#L272-L288
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/idtracking.py
python
FrameSymbolVisitor.visit_OverlayScope
(self, node, **kwargs)
Do not visit into overlay scopes.
Do not visit into overlay scopes.
[ "Do", "not", "visit", "into", "overlay", "scopes", "." ]
def visit_OverlayScope(self, node, **kwargs): """Do not visit into overlay scopes."""
[ "def", "visit_OverlayScope", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/idtracking.py#L285-L286
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.VCHome
(*args, **kwargs)
return _stc.StyledTextCtrl_VCHome(*args, **kwargs)
VCHome(self) Move caret to before first visible character on line. If already there move to first character on line.
VCHome(self)
[ "VCHome", "(", "self", ")" ]
def VCHome(*args, **kwargs): """ VCHome(self) Move caret to before first visible character on line. If already there move to first character on line. """ return _stc.StyledTextCtrl_VCHome(*args, **kwargs)
[ "def", "VCHome", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_VCHome", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L4579-L4586
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/fields.py
python
RequestField._render_part
(self, name, value)
return self.header_formatter(name, value)
Overridable helper function to format a single header parameter. By default, this calls ``self.header_formatter``. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string.
Overridable helper function to format a single header parameter. By default, this calls ``self.header_formatter``.
[ "Overridable", "helper", "function", "to", "format", "a", "single", "header", "parameter", ".", "By", "default", "this", "calls", "self", ".", "header_formatter", "." ]
def _render_part(self, name, value): """ Overridable helper function to format a single header parameter. By default, this calls ``self.header_formatter``. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ return self.header_formatter(name, value)
[ "def", "_render_part", "(", "self", ",", "name", ",", "value", ")", ":", "return", "self", ".", "header_formatter", "(", "name", ",", "value", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/fields.py#L194-L205
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/utils/tensorboard/_caffe2_graph.py
python
protos_to_graph_def
(net_defs, shapes=None, **kwargs)
return _operators_to_graph_def(shapes, ops, **kwargs)
Convert a set of Caffe2 net definitions to a Tensorflow graph. Args: net_defs: List of caffe2_pb2.NetDef protobufs representing computation graphs. shapes: Dictionary mapping blob names to their shapes/dimensions. Returns: Call to _operators_to_graph_def() with the extracted operators from the NetDefs and **kwargs. See _operators_to_graph_def for detailed **kwargs.
Convert a set of Caffe2 net definitions to a Tensorflow graph.
[ "Convert", "a", "set", "of", "Caffe2", "net", "definitions", "to", "a", "Tensorflow", "graph", "." ]
def protos_to_graph_def(net_defs, shapes=None, **kwargs): ''' Convert a set of Caffe2 net definitions to a Tensorflow graph. Args: net_defs: List of caffe2_pb2.NetDef protobufs representing computation graphs. shapes: Dictionary mapping blob names to their shapes/dimensions. Returns: Call to _operators_to_graph_def() with the extracted operators from the NetDefs and **kwargs. See _operators_to_graph_def for detailed **kwargs. ''' for net in net_defs: _propagate_device_option(net) shapes = copy.deepcopy(shapes or {}) ops = [op for net_def in net_defs for op in net_def.op] return _operators_to_graph_def(shapes, ops, **kwargs)
[ "def", "protos_to_graph_def", "(", "net_defs", ",", "shapes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "for", "net", "in", "net_defs", ":", "_propagate_device_option", "(", "net", ")", "shapes", "=", "copy", ".", "deepcopy", "(", "shapes", "or", "...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/tensorboard/_caffe2_graph.py#L797-L815
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/polynomial/legendre.py
python
legder
(c, m=1, scl=1, axis=0)
return c
Differentiate a Legendre series. Returns the Legendre series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Legendre series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Legendre series of the derivative. See Also -------- legint Notes ----- In general, the result of differentiating a Legendre series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c = (1,2,3,4) >>> L.legder(c) array([ 6., 9., 20.]) >>> L.legder(c, 3) array([ 60.]) >>> L.legder(c, scl=-1) array([ -6., -9., -20.]) >>> L.legder(c, 2,-1) array([ 9., 60.])
Differentiate a Legendre series.
[ "Differentiate", "a", "Legendre", "series", "." ]
def legder(c, m=1, scl=1, axis=0): """ Differentiate a Legendre series. Returns the Legendre series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Legendre series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Legendre series of the derivative. See Also -------- legint Notes ----- In general, the result of differentiating a Legendre series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c = (1,2,3,4) >>> L.legder(c) array([ 6., 9., 20.]) >>> L.legder(c, 3) array([ 60.]) >>> L.legder(c, scl=-1) array([ -6., -9., -20.]) >>> L.legder(c, 2,-1) array([ 9., 60.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: c = c[:1]*0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 2, -1): der[j - 1] = (2*j - 1)*c[j] c[j - 2] += c[j] if n > 1: der[1] = 3*c[2] der[0] = c[1] c = der c = np.moveaxis(c, 0, iaxis) return c
[ "def", "legder", "(", "c", ",", "m", "=", "1", ",", "scl", "=", "1", ",", "axis", "=", "0", ")", ":", "c", "=", "np", ".", "array", "(", "c", ",", "ndmin", "=", "1", ",", "copy", "=", "1", ")", "if", "c", ".", "dtype", ".", "char", "in"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/legendre.py#L679-L772
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pubsub/core/topicobj.py
python
Topic.validate
(self, listener)
return self.__validator.validate(listener)
Checks whether listener could be subscribed to this topic: if yes, just returns; if not, raises ListenerMismatchError. Note that method raises TopicDefnError if self not hasMDS().
Checks whether listener could be subscribed to this topic: if yes, just returns; if not, raises ListenerMismatchError. Note that method raises TopicDefnError if self not hasMDS().
[ "Checks", "whether", "listener", "could", "be", "subscribed", "to", "this", "topic", ":", "if", "yes", "just", "returns", ";", "if", "not", "raises", "ListenerMismatchError", ".", "Note", "that", "method", "raises", "TopicDefnError", "if", "self", "not", "hasM...
def validate(self, listener): """Checks whether listener could be subscribed to this topic: if yes, just returns; if not, raises ListenerMismatchError. Note that method raises TopicDefnError if self not hasMDS().""" if not self.hasMDS(): raise TopicDefnError(self.__tupleName) return self.__validator.validate(listener)
[ "def", "validate", "(", "self", ",", "listener", ")", ":", "if", "not", "self", ".", "hasMDS", "(", ")", ":", "raise", "TopicDefnError", "(", "self", ".", "__tupleName", ")", "return", "self", ".", "__validator", ".", "validate", "(", "listener", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/topicobj.py#L272-L279
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/searchengine.py
python
SearchEngine.search_text
(self, text, prog=None, ok=0)
return res
Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameter is a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True.
Return (lineno, matchobj) or None for forward/backward search.
[ "Return", "(", "lineno", "matchobj", ")", "or", "None", "for", "forward", "/", "backward", "search", "." ]
def search_text(self, text, prog=None, ok=0): '''Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameter is a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. ''' if not prog: prog = self.getprog() if not prog: return None # Compilation failed -- stop wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res
[ "def", "search_text", "(", "self", ",", "text", ",", "prog", "=", "None", ",", "ok", "=", "0", ")", ":", "if", "not", "prog", ":", "prog", "=", "self", ".", "getprog", "(", ")", "if", "not", "prog", ":", "return", "None", "# Compilation failed -- sto...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/searchengine.py#L105-L143
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/prepare_bindings.py
python
prepare_all_bindings
(options)
Prepares bindings for each of the languages supported. @param options the parsed arguments from the command line @return the exit value for the program. 0 is success, all othes indicate some kind of failure.
Prepares bindings for each of the languages supported.
[ "Prepares", "bindings", "for", "each", "of", "the", "languages", "supported", "." ]
def prepare_all_bindings(options): """Prepares bindings for each of the languages supported. @param options the parsed arguments from the command line @return the exit value for the program. 0 is success, all othes indicate some kind of failure. """ # Check for the existence of the SWIG scripts folder scripts_dir = os.path.join(options.src_root, "scripts") if not os.path.exists(scripts_dir): logging.error("failed to find scripts dir: '%s'", scripts_dir) sys.exit(-8) child_dirs = ["Python"] # Iterate script directory find any script language directories for script_lang in child_dirs: logging.info("executing language script for: '%s'", script_lang) prepare_binding_for_language(scripts_dir, script_lang, options)
[ "def", "prepare_all_bindings", "(", "options", ")", ":", "# Check for the existence of the SWIG scripts folder", "scripts_dir", "=", "os", ".", "path", ".", "join", "(", "options", ".", "src_root", ",", "\"scripts\"", ")", "if", "not", "os", ".", "path", ".", "e...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/prepare_bindings.py#L60-L79
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/framework/ops.py
python
Operation._get_control_flow_context
(self)
return self._control_flow_context
Returns the control flow context of this op. Returns: A context object.
Returns the control flow context of this op.
[ "Returns", "the", "control", "flow", "context", "of", "this", "op", "." ]
def _get_control_flow_context(self): """Returns the control flow context of this op. Returns: A context object. """ return self._control_flow_context
[ "def", "_get_control_flow_context", "(", "self", ")", ":", "return", "self", ".", "_control_flow_context" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L1630-L1636
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Parser/asdl.py
python
ASDLParser.p_definition_1
(self, (definitions, definition))
return definitions + definition
definitions ::= definition definitions
definitions ::= definition definitions
[ "definitions", "::", "=", "definition", "definitions" ]
def p_definition_1(self, (definitions, definition)): " definitions ::= definition definitions " return definitions + definition
[ "def", "p_definition_1", "(", "self", ",", "(", "definitions", ",", "definition", ")", ")", ":", "return", "definitions", "+", "definition" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Parser/asdl.py#L136-L138
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/text/transforms.py
python
JiebaTokenizer.__add_dict_py_file
(self, file_path)
Add user defined word by file
Add user defined word by file
[ "Add", "user", "defined", "word", "by", "file" ]
def __add_dict_py_file(self, file_path): """Add user defined word by file""" words_list = self.__parser_file(file_path) for data in words_list: if data[1] is None: freq = 0 else: freq = int(data[1]) self.add_word(data[0], freq)
[ "def", "__add_dict_py_file", "(", "self", ",", "file_path", ")", ":", "words_list", "=", "self", ".", "__parser_file", "(", "file_path", ")", "for", "data", "in", "words_list", ":", "if", "data", "[", "1", "]", "is", "None", ":", "freq", "=", "0", "els...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/text/transforms.py#L210-L218
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py
python
expandtabs
(s, tabsize=8)
return res + line
expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8).
expandtabs(s [,tabsize]) -> string
[ "expandtabs", "(", "s", "[", "tabsize", "]", ")", "-", ">", "string" ]
def expandtabs(s, tabsize=8): """expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8). """ res = line = '' for c in s: if c == '\t': c = ' '*(tabsize - len(line) % tabsize) line = line + c if c == '\n': res = res + line line = '' return res + line
[ "def", "expandtabs", "(", "s", ",", "tabsize", "=", "8", ")", ":", "res", "=", "line", "=", "''", "for", "c", "in", "s", ":", "if", "c", "==", "'\\t'", ":", "c", "=", "' '", "*", "(", "tabsize", "-", "len", "(", "line", ")", "%", "tabsize", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py#L328-L344
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py
python
convert_contrib_roialign
(node, **kwargs)
return nodes
Map MXNet's _contrib_ROIAlign
Map MXNet's _contrib_ROIAlign
[ "Map", "MXNet", "s", "_contrib_ROIAlign" ]
def convert_contrib_roialign(node, **kwargs): """Map MXNet's _contrib_ROIAlign """ from onnx.helper import make_node from onnx import TensorProto name, input_nodes, attrs = get_inputs(node, kwargs) pooled_size = convert_string_to_list(str(attrs.get('pooled_size'))) spatial_scale = float(attrs.get('spatial_scale')) sample_ratio = int(attrs.get('sample_ratio', '0')) position_sensitive = attrs.get('position_sensitive', 'False') aligned = attrs.get('aligned', 'False') if position_sensitive != 'False': raise NotImplementedError('_contrib_ROIAlign does not currently support \ position_sensitive!=False') if aligned != 'False': raise NotImplementedError('_contrib_ROIAlign does not currently support \ aligned!=False') create_tensor([0], name+'_0', kwargs['initializer']) create_tensor([0], name+'_0_s', kwargs['initializer'], dtype='float32') create_tensor([1], name+'_1', kwargs['initializer']) create_tensor([5], name+'_5', kwargs['initializer']) create_tensor([2, 3], name+'_2_3', kwargs['initializer']) nodes = [ make_node('Slice', [input_nodes[1], name+'_1', name+'_5', name+'_1'], [name+'_rois']), make_node('Slice', [input_nodes[1], name+'_0', name+'_1', name+'_1'], [name+'_inds___']), make_node('Squeeze', [name+'_inds___', name+'_1'], [name+'_inds__']), make_node('Relu', [name+'_inds__'], [name+'_inds_']), make_node('Cast', [name+'_inds_'], [name+'_inds'], to=int(TensorProto.INT64)), make_node('RoiAlign', [input_nodes[0], name+'_rois', name+'_inds'], [name+'_roi'], mode='avg', output_height=pooled_size[0], output_width=pooled_size[1], sampling_ratio=sample_ratio, spatial_scale=spatial_scale), make_node('Unsqueeze', [name+'_inds___', name+'_2_3'], [name+'_unsq']), make_node('Less', [name+'_unsq', name+'_0_s'], [name+'_less']), make_node('Where', [name+'_less', name+'_0_s', name+'_roi'], [name]) ] return nodes
[ "def", "convert_contrib_roialign", "(", "node", ",", "*", "*", "kwargs", ")", ":", "from", "onnx", ".", "helper", "import", "make_node", "from", "onnx", "import", "TensorProto", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", ...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py#L909-L949
google/mozc
7329757e1ad30e327c1ae823a8302c79482d6b9c
src/build_tools/versioning_files.py
python
VersioningFiles
(version_string, is_debug, file_paths)
Creates versioned files and information files of the files.
Creates versioned files and information files of the files.
[ "Creates", "versioned", "files", "and", "information", "files", "of", "the", "files", "." ]
def VersioningFiles(version_string, is_debug, file_paths): """Creates versioned files and information files of the files.""" for file_path in file_paths: _VersioningFile(version_string, is_debug, file_path)
[ "def", "VersioningFiles", "(", "version_string", ",", "is_debug", ",", "file_paths", ")", ":", "for", "file_path", "in", "file_paths", ":", "_VersioningFile", "(", "version_string", ",", "is_debug", ",", "file_path", ")" ]
https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/build_tools/versioning_files.py#L108-L111
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetMachOType
(self)
return { 'executable': 'mh_execute', 'static_library': 'staticlib', 'shared_library': 'mh_dylib', 'loadable_module': 'mh_bundle', }[self.spec['type']]
Returns the MACH_O_TYPE of this target.
Returns the MACH_O_TYPE of this target.
[ "Returns", "the", "MACH_O_TYPE", "of", "this", "target", "." ]
def GetMachOType(self): """Returns the MACH_O_TYPE of this target.""" # Weird, but matches Xcode. if not self._IsBundle() and self.spec['type'] == 'executable': return '' return { 'executable': 'mh_execute', 'static_library': 'staticlib', 'shared_library': 'mh_dylib', 'loadable_module': 'mh_bundle', }[self.spec['type']]
[ "def", "GetMachOType", "(", "self", ")", ":", "# Weird, but matches Xcode.", "if", "not", "self", ".", "_IsBundle", "(", ")", "and", "self", ".", "spec", "[", "'type'", "]", "==", "'executable'", ":", "return", "''", "return", "{", "'executable'", ":", "'m...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py#L144-L154
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/webapp/forms.py
python
FormsHandler.new_factory
(cls, registry_path=DEFAULT_REGISTRY_PATH)
return forms_factory
Construct a factory for use with WSGIApplication. This method is called automatically with the correct registry path when services are configured via service_handlers.service_mapping. Args: registry_path: Absolute path on server where the ProtoRPC RegsitryService is located. Returns: Factory function that creates a properly configured FormsHandler instance.
Construct a factory for use with WSGIApplication.
[ "Construct", "a", "factory", "for", "use", "with", "WSGIApplication", "." ]
def new_factory(cls, registry_path=DEFAULT_REGISTRY_PATH): """Construct a factory for use with WSGIApplication. This method is called automatically with the correct registry path when services are configured via service_handlers.service_mapping. Args: registry_path: Absolute path on server where the ProtoRPC RegsitryService is located. Returns: Factory function that creates a properly configured FormsHandler instance. """ def forms_factory(): return cls(registry_path) return forms_factory
[ "def", "new_factory", "(", "cls", ",", "registry_path", "=", "DEFAULT_REGISTRY_PATH", ")", ":", "def", "forms_factory", "(", ")", ":", "return", "cls", "(", "registry_path", ")", "return", "forms_factory" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/webapp/forms.py#L148-L163
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteList
(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary)
Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style.
Write a variable definition that is a list of values.
[ "Write", "a", "variable", "definition", "that", "is", "a", "list", "of", "values", "." ]
def WriteList(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values))
[ "def", "WriteList", "(", "self", ",", "value_list", ",", "variable", "=", "None", ",", "prefix", "=", "''", ",", "quoter", "=", "QuoteIfNecessary", ")", ":", "values", "=", "''", "if", "value_list", ":", "value_list", "=", "[", "quoter", "(", "prefix", ...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/make.py#L1719-L1731
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/closest-binary-search-tree-value-ii.py
python
Solution2.closestKValues
(self, root, target, k)
return result
:type root: TreeNode :type target: float :type k: int :rtype: List[int]
:type root: TreeNode :type target: float :type k: int :rtype: List[int]
[ ":", "type", "root", ":", "TreeNode", ":", "type", "target", ":", "float", ":", "type", "k", ":", "int", ":", "rtype", ":", "List", "[", "int", "]" ]
def closestKValues(self, root, target, k): """ :type root: TreeNode :type target: float :type k: int :rtype: List[int] """ # Helper class to make a stack to the next node. class BSTIterator: # @param root, a binary search tree's root node def __init__(self, stack, child1, child2): self.stack = list(stack) self.cur = self.stack.pop() self.child1 = child1 self.child2 = child2 # @return an integer, the next node def next(self): node = None if self.cur and self.child1(self.cur): self.stack.append(self.cur) node = self.child1(self.cur) while self.child2(node): self.stack.append(node) node = self.child2(node) elif self.stack: prev = self.cur node = self.stack.pop() while node: if self.child2(node) is prev: break else: prev = node node = self.stack.pop() if self.stack else None self.cur = node return node # Build the stack to the closet node. stack = [] while root: stack.append(root) root = root.left if target < root.val else root.right dist = lambda node: abs(node.val - target) if node else float("inf") stack = stack[:stack.index(min(stack, key=dist))+1] # The forward or backward iterator. backward = lambda node: node.left forward = lambda node: node.right smaller_it, larger_it = BSTIterator(stack, backward, forward), BSTIterator(stack, forward, backward) smaller_node, larger_node = smaller_it.next(), larger_it.next() # Get the closest k values by advancing the iterators of the stacks. result = [stack[-1].val] for _ in xrange(k - 1): if dist(smaller_node) < dist(larger_node): result.append(smaller_node.val) smaller_node = smaller_it.next() else: result.append(larger_node.val) larger_node = larger_it.next() return result
[ "def", "closestKValues", "(", "self", ",", "root", ",", "target", ",", "k", ")", ":", "# Helper class to make a stack to the next node.", "class", "BSTIterator", ":", "# @param root, a binary search tree's root node", "def", "__init__", "(", "self", ",", "stack", ",", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/closest-binary-search-tree-value-ii.py#L55-L115
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/numpy/_symbol.py
python
greater
(x1, x2, out=None)
return _ufunc_helper(x1, x2, _npi.greater, _np.greater, _npi.greater_scalar, _npi.less_scalar, out)
Return the truth value of (x1 > x2) element-wise. Parameters ---------- x1, x2 : _Symbol or scalars Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes the shape of the output). out : Dummy parameter, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or `None`, a freshly-allocated array is returned. Returns ------- out : _Symbol or scalar Output array of type bool, element-wise comparison of `x1` and `x2`. This is a scalar if both `x1` and `x2` are scalars. See Also -------- equal, greater, greater_equal, less, less_equal Examples -------- >>> np.greater(np.ones(2, 1)), np.zeros(1, 3)) array([[ True, True, True], [ True, True, True]]) >>> np.greater(1, np.ones(1)) array([False])
Return the truth value of (x1 > x2) element-wise. Parameters ---------- x1, x2 : _Symbol or scalars Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes the shape of the output). out : Dummy parameter, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or `None`, a freshly-allocated array is returned. Returns ------- out : _Symbol or scalar Output array of type bool, element-wise comparison of `x1` and `x2`. This is a scalar if both `x1` and `x2` are scalars. See Also -------- equal, greater, greater_equal, less, less_equal Examples -------- >>> np.greater(np.ones(2, 1)), np.zeros(1, 3)) array([[ True, True, True], [ True, True, True]]) >>> np.greater(1, np.ones(1)) array([False])
[ "Return", "the", "truth", "value", "of", "(", "x1", ">", "x2", ")", "element", "-", "wise", ".", "Parameters", "----------", "x1", "x2", ":", "_Symbol", "or", "scalars", "Input", "arrays", ".", "If", "x1", ".", "shape", "!", "=", "x2", ".", "shape", ...
def greater(x1, x2, out=None): """ Return the truth value of (x1 > x2) element-wise. Parameters ---------- x1, x2 : _Symbol or scalars Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes the shape of the output). out : Dummy parameter, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or `None`, a freshly-allocated array is returned. Returns ------- out : _Symbol or scalar Output array of type bool, element-wise comparison of `x1` and `x2`. This is a scalar if both `x1` and `x2` are scalars. See Also -------- equal, greater, greater_equal, less, less_equal Examples -------- >>> np.greater(np.ones(2, 1)), np.zeros(1, 3)) array([[ True, True, True], [ True, True, True]]) >>> np.greater(1, np.ones(1)) array([False]) """ return _ufunc_helper(x1, x2, _npi.greater, _np.greater, _npi.greater_scalar, _npi.less_scalar, out)
[ "def", "greater", "(", "x1", ",", "x2", ",", "out", "=", "None", ")", ":", "return", "_ufunc_helper", "(", "x1", ",", "x2", ",", "_npi", ".", "greater", ",", "_np", ".", "greater", ",", "_npi", ".", "greater_scalar", ",", "_npi", ".", "less_scalar", ...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L6405-L6434
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/descriptor.py
python
Descriptor.fields_by_camelcase_name
(self)
return self._fields_by_camelcase_name
Same FieldDescriptor objects as in :attr:`fields`, but indexed by :attr:`FieldDescriptor.camelcase_name`.
Same FieldDescriptor objects as in :attr:`fields`, but indexed by :attr:`FieldDescriptor.camelcase_name`.
[ "Same", "FieldDescriptor", "objects", "as", "in", ":", "attr", ":", "fields", "but", "indexed", "by", ":", "attr", ":", "FieldDescriptor", ".", "camelcase_name", "." ]
def fields_by_camelcase_name(self): """Same FieldDescriptor objects as in :attr:`fields`, but indexed by :attr:`FieldDescriptor.camelcase_name`. """ if self._fields_by_camelcase_name is None: self._fields_by_camelcase_name = dict( (f.camelcase_name, f) for f in self.fields) return self._fields_by_camelcase_name
[ "def", "fields_by_camelcase_name", "(", "self", ")", ":", "if", "self", ".", "_fields_by_camelcase_name", "is", "None", ":", "self", ".", "_fields_by_camelcase_name", "=", "dict", "(", "(", "f", ".", "camelcase_name", ",", "f", ")", "for", "f", "in", "self",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/descriptor.py#L373-L380
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py
python
ParserElement.setDebugActions
( self, startAction, successAction, exceptionAction )
return self
Enable display of debugging messages while doing pattern matching.
Enable display of debugging messages while doing pattern matching.
[ "Enable", "display", "of", "debugging", "messages", "while", "doing", "pattern", "matching", "." ]
def setDebugActions( self, startAction, successAction, exceptionAction ): """ Enable display of debugging messages while doing pattern matching. """ self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self
[ "def", "setDebugActions", "(", "self", ",", "startAction", ",", "successAction", ",", "exceptionAction", ")", ":", "self", ".", "debugActions", "=", "(", "startAction", "or", "_defaultStartDebugAction", ",", "successAction", "or", "_defaultSuccessDebugAction", ",", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py#L2102-L2110
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/training/saver.py
python
Saver.set_last_checkpoints_with_time
(self, last_checkpoints_with_time)
Sets the list of old checkpoint filenames and timestamps. Args: last_checkpoints_with_time: A list of tuples of checkpoint filenames and timestamps. Raises: AssertionError: If last_checkpoints_with_time is not a list.
Sets the list of old checkpoint filenames and timestamps.
[ "Sets", "the", "list", "of", "old", "checkpoint", "filenames", "and", "timestamps", "." ]
def set_last_checkpoints_with_time(self, last_checkpoints_with_time): """Sets the list of old checkpoint filenames and timestamps. Args: last_checkpoints_with_time: A list of tuples of checkpoint filenames and timestamps. Raises: AssertionError: If last_checkpoints_with_time is not a list. """ assert isinstance(last_checkpoints_with_time, list) self._last_checkpoints = last_checkpoints_with_time
[ "def", "set_last_checkpoints_with_time", "(", "self", ",", "last_checkpoints_with_time", ")", ":", "assert", "isinstance", "(", "last_checkpoints_with_time", ",", "list", ")", "self", ".", "_last_checkpoints", "=", "last_checkpoints_with_time" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/saver.py#L1360-L1371
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py
python
CompositeDataSet.GetCellData
(self)
return self._CellData()
Returns the cell data as a DataSetAttributes instance.
Returns the cell data as a DataSetAttributes instance.
[ "Returns", "the", "cell", "data", "as", "a", "DataSetAttributes", "instance", "." ]
def GetCellData(self): "Returns the cell data as a DataSetAttributes instance." if self._CellData is None or self._CellData() is None: cdata = self.GetAttributes(ArrayAssociation.CELL) self._CellData = weakref.ref(cdata) return self._CellData()
[ "def", "GetCellData", "(", "self", ")", ":", "if", "self", ".", "_CellData", "is", "None", "or", "self", ".", "_CellData", "(", ")", "is", "None", ":", "cdata", "=", "self", ".", "GetAttributes", "(", "ArrayAssociation", ".", "CELL", ")", "self", ".", ...
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py#L975-L980
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/jpsro.py
python
_min_epsilon_mgce
(meta_game, per_player_repeats, ignore_repeats=False)
return dist, dict()
Min Epsilon Maximum Gini CE.
Min Epsilon Maximum Gini CE.
[ "Min", "Epsilon", "Maximum", "Gini", "CE", "." ]
def _min_epsilon_mgce(meta_game, per_player_repeats, ignore_repeats=False): """Min Epsilon Maximum Gini CE.""" a_mat, e_vec, meta = _ace_constraints( meta_game, [0.0] * len(per_player_repeats), remove_null=True, zero_tolerance=1e-8) a_mats = _partition_by_player( a_mat, meta["p_vec"], len(per_player_repeats)) e_vecs = _partition_by_player( e_vec, meta["p_vec"], len(per_player_repeats)) dist, _ = _try_two_solvers( _qp_ce, meta_game, a_mats, e_vecs, action_repeats=(None if ignore_repeats else per_player_repeats), min_epsilon=True) return dist, dict()
[ "def", "_min_epsilon_mgce", "(", "meta_game", ",", "per_player_repeats", ",", "ignore_repeats", "=", "False", ")", ":", "a_mat", ",", "e_vec", ",", "meta", "=", "_ace_constraints", "(", "meta_game", ",", "[", "0.0", "]", "*", "len", "(", "per_player_repeats", ...
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/jpsro.py#L820-L834
vmtk/vmtk
927331ad752265199390eabbbf2e07cdc2b4bcc6
PypeS/pype.py
python
Pype.PrintLog
(self,logMessage,indent=0)
Prints log messages from pypescript members to the console. All vmtkscripts subclassing from pypes.Pype use the PrintLog method in order to write their output to the console. Args: logMessage (str): the message to be logged indent (int): number of spaces to intent the message. Defaults to 0.
Prints log messages from pypescript members to the console.
[ "Prints", "log", "messages", "from", "pypescript", "members", "to", "the", "console", "." ]
def PrintLog(self,logMessage,indent=0): '''Prints log messages from pypescript members to the console. All vmtkscripts subclassing from pypes.Pype use the PrintLog method in order to write their output to the console. Args: logMessage (str): the message to be logged indent (int): number of spaces to intent the message. Defaults to 0. ''' if not self.LogOn: return indentUnit = ' ' indentation = '' for i in range(indent): indentation = indentation + indentUnit self.OutputStream.write(indentation + logMessage + '\n')
[ "def", "PrintLog", "(", "self", ",", "logMessage", ",", "indent", "=", "0", ")", ":", "if", "not", "self", ".", "LogOn", ":", "return", "indentUnit", "=", "' '", "indentation", "=", "''", "for", "i", "in", "range", "(", "indent", ")", ":", "indent...
https://github.com/vmtk/vmtk/blob/927331ad752265199390eabbbf2e07cdc2b4bcc6/PypeS/pype.py#L77-L93
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/urllib/request.py
python
build_opener
(*handlers)
return opener
Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable HTTPS. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used.
Create an opener object from a list of handlers.
[ "Create", "an", "opener", "object", "from", "a", "list", "of", "handlers", "." ]
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable HTTPS. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor, DataHandler] if hasattr(http.client, "HTTPSConnection"): default_classes.append(HTTPSHandler) skip = set() for klass in default_classes: for check in handlers: if isinstance(check, type): if issubclass(check, klass): skip.add(klass) elif isinstance(check, klass): skip.add(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if isinstance(h, type): h = h() opener.add_handler(h) return opener
[ "def", "build_opener", "(", "*", "handlers", ")", ":", "opener", "=", "OpenerDirector", "(", ")", "default_classes", "=", "[", "ProxyHandler", ",", "UnknownHandler", ",", "HTTPHandler", ",", "HTTPDefaultErrorHandler", ",", "HTTPRedirectHandler", ",", "FTPHandler", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/urllib/request.py#L575-L609
manutdzou/KITTI_SSD
5b620c2f291d36a0fe14489214f22a992f173f44
scripts/cpp_lint.py
python
CheckForNonStandardConstructs
(filename, clean_lines, linenum, nesting_state, error)
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
[ "r", "Logs", "an", "error", "if", "we", "see", "certain", "non", "-", "ANSI", "constructs", "ignored", "by", "gcc", "-", "2", "." ]
def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' % re.escape(base_classname), line) if (args and args.group(1) != 'void' and not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), args.group(1).strip())): error(filename, linenum, 'runtime/explicit', 5, 'Single-argument constructors should be marked explicit.')
[ "def", "CheckForNonStandardConstructs", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Remove comments from the line, but leave in strings for now.", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "i...
https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/scripts/cpp_lint.py#L2198-L2302
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/generator/make.py
python
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
[ "Calculate", "the", "generator", "specific", "info", "that", "gets", "fed", "to", "input", "(", "called", "by", "gyp", ")", "." ]
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) android_ndk_version = generator_flags.get('android_ndk_version', None) # Android NDK requires a strict link order. if android_ndk_version: global generator_wants_sorted_dependencies generator_wants_sorted_dependencies = True output_dir = params['options'].generator_output or \ params['options'].toplevel_dir builddir_name = generator_flags.get('output_dir', 'out') qualified_out_dir = os.path.normpath(os.path.join( output_dir, builddir_name, 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': params['options'].toplevel_dir, 'qualified_out_dir': qualified_out_dir, }
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "android_ndk_version", "=", "generator_flags", ".", "get", "(", "'android_ndk_version'", ",", "None", ")", ...
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/make.py#L98-L118
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Options.py
python
OptionsContext.parse_args
(self, _args=None)
Parses arguments from a list which is not necessarily the command-line. Initializes the module variables options, commands and envvars If help is requested, prints it and exit the application :param _args: arguments :type _args: list of strings
Parses arguments from a list which is not necessarily the command-line. Initializes the module variables options, commands and envvars If help is requested, prints it and exit the application
[ "Parses", "arguments", "from", "a", "list", "which", "is", "not", "necessarily", "the", "command", "-", "line", ".", "Initializes", "the", "module", "variables", "options", "commands", "and", "envvars", "If", "help", "is", "requested", "prints", "it", "and", ...
def parse_args(self, _args=None): """ Parses arguments from a list which is not necessarily the command-line. Initializes the module variables options, commands and envvars If help is requested, prints it and exit the application :param _args: arguments :type _args: list of strings """ options, commands, envvars = self.parse_cmd_args() self.init_logs(options, commands, envvars) self.init_module_vars(options, commands, envvars)
[ "def", "parse_args", "(", "self", ",", "_args", "=", "None", ")", ":", "options", ",", "commands", ",", "envvars", "=", "self", ".", "parse_cmd_args", "(", ")", "self", ".", "init_logs", "(", "options", ",", "commands", ",", "envvars", ")", "self", "."...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Options.py#L339-L350
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatnotebook.py
python
FNBRendererRibbonTabs.DrawTab
(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus)
Draws a tab using the `Ribbon Tabs` style. :param `pageContainer`: an instance of :class:`FlatNotebook`; :param `dc`: an instance of :class:`DC`; :param `posx`: the x position of the tab; :param `tabIdx`: the index of the tab; :param `tabWidth`: the tab's width; :param `tabHeight`: the tab's height; :param `btnStatus`: the status of the 'X' button inside this tab.
Draws a tab using the `Ribbon Tabs` style.
[ "Draws", "a", "tab", "using", "the", "Ribbon", "Tabs", "style", "." ]
def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): """ Draws a tab using the `Ribbon Tabs` style. :param `pageContainer`: an instance of :class:`FlatNotebook`; :param `dc`: an instance of :class:`DC`; :param `posx`: the x position of the tab; :param `tabIdx`: the index of the tab; :param `tabWidth`: the tab's width; :param `tabHeight`: the tab's height; :param `btnStatus`: the status of the 'X' button inside this tab. """ pc = pageContainer gc = wx.GraphicsContext.Create(dc) gc.SetPen(dc.GetPen()) gc.SetBrush(dc.GetBrush()) spacer = math.ceil(float(FNB_HEIGHT_SPACER)/2/2) gc.DrawRoundedRectangle(posx+1,spacer,tabWidth-1,tabHeight-spacer*2,5) if tabIdx == pc.GetSelection(): pass else: if tabIdx != pc.GetSelection() - 1: pass # ----------------------------------- # Text and image drawing # ----------------------------------- # Text drawing offset from the left border of the # rectangle # The width of the images are 16 pixels padding = pc.GetParent().GetPadding() hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 imageYCoord = FNB_HEIGHT_SPACER/2 if hasImage: textOffset = 2*pc._pParent._nPadding + 16 else: textOffset = pc._pParent._nPadding textOffset += 2 if tabIdx != pc.GetSelection(): # Set the text background to be like the vertical lines dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour()) if hasImage: imageXOffset = textOffset - 16 - padding pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, posx + imageXOffset, imageYCoord, wx.IMAGELIST_DRAW_TRANSPARENT, True) pageTextColour = pc._pParent.GetPageTextColour(tabIdx) if pageTextColour is not None: dc.SetTextForeground(pageTextColour) dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) # draw 'x' on tab (if enabled) if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) tabCloseButtonXCoord = posx + textOffset + textWidth + 1 # take a bitmap from the position of the 'x' button (the x on tab button) # this bitmap will be used later to delete old buttons tabCloseButtonYCoord = imageYCoord x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) # Draw the tab self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)
[ "def", "DrawTab", "(", "self", ",", "pageContainer", ",", "dc", ",", "posx", ",", "tabIdx", ",", "tabWidth", ",", "tabHeight", ",", "btnStatus", ")", ":", "pc", "=", "pageContainer", "gc", "=", "wx", ".", "GraphicsContext", ".", "Create", "(", "dc", ")...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L3674-L3751
FEniCS/dolfinx
3dfdf038cccdb70962865b58a63bf29c2e55ec6e
python/dolfinx/fem/function.py
python
FunctionSpace.dofmap
(self)
return dofmap.DofMap(self._cpp_object.dofmap)
Degree-of-freedom map associated with the function space.
Degree-of-freedom map associated with the function space.
[ "Degree", "-", "of", "-", "freedom", "map", "associated", "with", "the", "function", "space", "." ]
def dofmap(self) -> dofmap.DofMap: """Degree-of-freedom map associated with the function space.""" return dofmap.DofMap(self._cpp_object.dofmap)
[ "def", "dofmap", "(", "self", ")", "->", "dofmap", ".", "DofMap", ":", "return", "dofmap", ".", "DofMap", "(", "self", ".", "_cpp_object", ".", "dofmap", ")" ]
https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/function.py#L548-L550
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetLdflags
(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir)
return ldflags, intermediate_manifest, manifest_files
Returns the flags that need to be added to link commands, and the manifest files.
Returns the flags that need to be added to link commands, and the manifest files.
[ "Returns", "the", "flags", "that", "need", "to", "be", "added", "to", "link", "commands", "and", "the", "manifest", "files", "." ]
def GetLdflags(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir): """Returns the flags that need to be added to link commands, and the manifest files.""" config = self._TargetConfig(config) ldflags = [] ld = self._GetWrapper(self, self.msvs_settings[config], 'VCLinkerTool', append=ldflags) self._GetDefFileAsLdflags(ldflags, gyp_to_build_path) ld('GenerateDebugInformation', map={'true': '/DEBUG'}) ld('TargetMachine', map={'1': 'X86', '17': 'X64', '3': 'ARM'}, prefix='/MACHINE:') ldflags.extend(self._GetAdditionalLibraryDirectories( 'VCLinkerTool', config, gyp_to_build_path)) ld('DelayLoadDLLs', prefix='/DELAYLOAD:') ld('TreatLinkerWarningAsErrors', prefix='/WX', map={'true': '', 'false': ':NO'}) out = self.GetOutputName(config, expand_special) if out: ldflags.append('/OUT:' + out) pdb = self.GetPDBName(config, expand_special, output_name + '.pdb') if pdb: ldflags.append('/PDB:' + pdb) pgd = self.GetPGDName(config, expand_special) if pgd: ldflags.append('/PGD:' + pgd) map_file = self.GetMapFileName(config, expand_special) ld('GenerateMapFile', map={'true': '/MAP:' + map_file if map_file else '/MAP'}) ld('MapExports', map={'true': '/MAPINFO:EXPORTS'}) ld('AdditionalOptions', prefix='') minimum_required_version = self._Setting( ('VCLinkerTool', 'MinimumRequiredVersion'), config, default='') if minimum_required_version: minimum_required_version = ',' + minimum_required_version ld('SubSystem', map={'1': 'CONSOLE%s' % minimum_required_version, '2': 'WINDOWS%s' % minimum_required_version}, prefix='/SUBSYSTEM:') stack_reserve_size = self._Setting( ('VCLinkerTool', 'StackReserveSize'), config, default='') if stack_reserve_size: stack_commit_size = self._Setting( ('VCLinkerTool', 'StackCommitSize'), config, default='') if stack_commit_size: stack_commit_size = ',' + stack_commit_size ldflags.append('/STACK:%s%s' % (stack_reserve_size, stack_commit_size)) ld('TerminalServerAware', map={'1': ':NO', '2': ''}, prefix='/TSAWARE') ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL') ld('BaseAddress', prefix='/BASE:') ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED') ld('RandomizedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE') ld('DataExecutionPrevention', map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT') ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:') ld('ForceSymbolReferences', prefix='/INCLUDE:') ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:') ld('LinkTimeCodeGeneration', map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE', '4': ':PGUPDATE'}, prefix='/LTCG') ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:') ld('ResourceOnlyDLL', map={'true': '/NOENTRY'}) ld('EntryPointSymbol', prefix='/ENTRY:') ld('Profile', map={'true': '/PROFILE'}) ld('LargeAddressAware', map={'1': ':NO', '2': ''}, prefix='/LARGEADDRESSAWARE') # TODO(scottmg): This should sort of be somewhere else (not really a flag). ld('AdditionalDependencies', prefix='') if self.GetArch(config) == 'x86': safeseh_default = 'true' else: safeseh_default = None ld('ImageHasSafeExceptionHandlers', map={'false': ':NO', 'true': ''}, prefix='/SAFESEH', default=safeseh_default) # If the base address is not specifically controlled, DYNAMICBASE should # be on by default. base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED', ldflags) if not base_flags: ldflags.append('/DYNAMICBASE') # If the NXCOMPAT flag has not been specified, default to on. Despite the # documentation that says this only defaults to on when the subsystem is # Vista or greater (which applies to the linker), the IDE defaults it on # unless it's explicitly off. if not filter(lambda x: 'NXCOMPAT' in x, ldflags): ldflags.append('/NXCOMPAT') have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags) manifest_flags, intermediate_manifest, manifest_files = \ self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path, is_executable and not have_def_file, build_dir) ldflags.extend(manifest_flags) return ldflags, intermediate_manifest, manifest_files
[ "def", "GetLdflags", "(", "self", ",", "config", ",", "gyp_to_build_path", ",", "expand_special", ",", "manifest_base_name", ",", "output_name", ",", "is_executable", ",", "build_dir", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", ...
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L556-L657
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
python
_padding
(sequences, num_unroll)
return length, padded_sequences
For a dictionary of sequences, pads tensors to a multiple of `num_unroll`. Args: sequences: dictionary with `Tensor` values. num_unroll: int specifying to what multiple to pad sequences to. Returns: length: Scalar `Tensor` of dimension 0 of all the values in sequences. padded_sequence: Dictionary of sequences that are padded to a multiple of `num_unroll`. Raises: ValueError: If `num_unroll` not an int or sequences not a dictionary from string to `Tensor`.
For a dictionary of sequences, pads tensors to a multiple of `num_unroll`.
[ "For", "a", "dictionary", "of", "sequences", "pads", "tensors", "to", "a", "multiple", "of", "num_unroll", "." ]
def _padding(sequences, num_unroll): """For a dictionary of sequences, pads tensors to a multiple of `num_unroll`. Args: sequences: dictionary with `Tensor` values. num_unroll: int specifying to what multiple to pad sequences to. Returns: length: Scalar `Tensor` of dimension 0 of all the values in sequences. padded_sequence: Dictionary of sequences that are padded to a multiple of `num_unroll`. Raises: ValueError: If `num_unroll` not an int or sequences not a dictionary from string to `Tensor`. """ if not isinstance(num_unroll, numbers.Integral): raise ValueError("Unsupported num_unroll expected int, got: %s" % str(num_unroll)) if not isinstance(sequences, dict): raise TypeError("Unsupported sequences expected dict, got: %s" % str(sequences)) for key, value in sequences.items(): if not isinstance(key, six.string_types): raise TypeError("Unsupported sequences key expected string, got: %s" % str(key)) if not sequences: return 0, {} sequences_dict = {} for key, value in sequences.items(): if not (isinstance(value, sparse_tensor.SparseTensor) or isinstance(value, sparse_tensor.SparseTensorValue)): sequences_dict[key] = ops.convert_to_tensor(value) else: sequences_dict[key] = value lengths = [array_ops.shape(value)[0] for value in sequences_dict.values() if isinstance(value, ops.Tensor)] if lengths: length = lengths[0] all_lengths_equal = [ control_flow_ops.Assert( math_ops.equal(l, length), [string_ops.string_join( ["All sequence lengths must match, but received lengths: ", string_ops.as_string(lengths)])]) for l in lengths] length = control_flow_ops.with_dependencies(all_lengths_equal, length) else: # Only have SparseTensors sparse_lengths = [value.dense_shape[0] for value in sequences_dict.values() if isinstance(value, sparse_tensor.SparseTensor)] length = math_ops.maximum(sparse_lengths) unroll = array_ops.constant(num_unroll) padded_length = length + ((unroll - (length % unroll)) % unroll) padded_sequences = {} for key, value in sequences_dict.items(): if isinstance(value, ops.Tensor): # 1. create shape of paddings # first dimension of value will be increased by num_paddings to # padded_length num_paddings = [padded_length - array_ops.shape(value)[0]] # the shape of the paddings that we concat with the original value will be # [num_paddings, tf.shape(value)[1], tf.shape(value)[2], ..., # tf.shape(value)[tf.rank(value) - 1])] padding_shape = array_ops.concat( (num_paddings, array_ops.shape(value)[1:]), 0) # 2. fill padding shape with dummies dummy = array_ops.constant( "" if value.dtype == dtypes.string else 0, dtype=value.dtype) paddings = array_ops.fill(dims=padding_shape, value=dummy) # 3. concat values with paddings padded_sequences[key] = array_ops.concat([value, paddings], 0) else: padded_shape = array_ops.concat([[math_ops.to_int64(padded_length)], value.dense_shape[1:]], 0) padded_sequences[key] = sparse_tensor.SparseTensor( indices=value.indices, values=value.values, dense_shape=padded_shape) return length, padded_sequences
[ "def", "_padding", "(", "sequences", ",", "num_unroll", ")", ":", "if", "not", "isinstance", "(", "num_unroll", ",", "numbers", ".", "Integral", ")", ":", "raise", "ValueError", "(", "\"Unsupported num_unroll expected int, got: %s\"", "%", "str", "(", "num_unroll"...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L1550-L1628
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/byteflow.py
python
TraceRunner.op_DELETE_SLICE_1
(self, state, inst)
del TOS1[TOS:]
del TOS1[TOS:]
[ "del", "TOS1", "[", "TOS", ":", "]" ]
def op_DELETE_SLICE_1(self, state, inst): """ del TOS1[TOS:] """ tos = state.pop() tos1 = state.pop() slicevar = state.make_temp() indexvar = state.make_temp() nonevar = state.make_temp() state.append( inst, base=tos1, start=tos, slicevar=slicevar, indexvar=indexvar, nonevar=nonevar, )
[ "def", "op_DELETE_SLICE_1", "(", "self", ",", "state", ",", "inst", ")", ":", "tos", "=", "state", ".", "pop", "(", ")", "tos1", "=", "state", ".", "pop", "(", ")", "slicevar", "=", "state", ".", "make_temp", "(", ")", "indexvar", "=", "state", "."...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/byteflow.py#L478-L494
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenu.CloseSubMenu
(self, itemIdx, alwaysClose=False)
Closes a child sub-menu. :param integer `itemIdx`: the index of the item for which we want to close the submenu; :param bool `alwaysClose`: if ``True``, always close the submenu irrespectively of other conditions.
Closes a child sub-menu.
[ "Closes", "a", "child", "sub", "-", "menu", "." ]
def CloseSubMenu(self, itemIdx, alwaysClose=False): """ Closes a child sub-menu. :param integer `itemIdx`: the index of the item for which we want to close the submenu; :param bool `alwaysClose`: if ``True``, always close the submenu irrespectively of other conditions. """ item = None subMenu = None if itemIdx >= 0 and itemIdx < len(self._itemsArr): item = self._itemsArr[itemIdx] # Close sub-menu first if item: subMenu = item.GetSubMenu() if self._openedSubMenu: if self._openedSubMenu != subMenu or alwaysClose: # We have another sub-menu open, close it self._openedSubMenu.Dismiss(False, True) self._openedSubMenu = None
[ "def", "CloseSubMenu", "(", "self", ",", "itemIdx", ",", "alwaysClose", "=", "False", ")", ":", "item", "=", "None", "subMenu", "=", "None", "if", "itemIdx", ">=", "0", "and", "itemIdx", "<", "len", "(", "self", ".", "_itemsArr", ")", ":", "item", "=...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L6490-L6513
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
CreateHandler.WriteGLES2Implementation
(self, func, file)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteGLES2Implementation(self, func, file): """Overrriden from TypeHandler.""" file.Write("%s GLES2Implementation::%s(%s) {\n" % (func.return_type, func.original_name, func.MakeTypedOriginalArgString(""))) file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n") func.WriteDestinationInitalizationValidation(file) self.WriteClientGLCallLog(func, file) for arg in func.GetOriginalArgs(): arg.WriteClientSideValidationCode(file, func) file.Write(" GLuint client_id;\n") file.Write( " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n") file.Write(" MakeIds(this, 0, 1, &client_id);\n") file.Write(" helper_->%s(%s);\n" % (func.name, func.MakeCmdArgString(""))) file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n') file.Write(" CheckGLError();\n") file.Write(" return client_id;\n") file.Write("}\n") file.Write("\n")
[ "def", "WriteGLES2Implementation", "(", "self", ",", "func", ",", "file", ")", ":", "file", ".", "Write", "(", "\"%s GLES2Implementation::%s(%s) {\\n\"", "%", "(", "func", ".", "return_type", ",", "func", ".", "original_name", ",", "func", ".", "MakeTypedOrigina...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L4198-L4218
cmu-db/bustub
fe1b9e984bd2967997b52df872c873d80f71cf7d
build_support/cpplint.py
python
CheckComment
(line, filename, linenum, next_line_start, error)
Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found.
Checks for common mistakes in comments.
[ "Checks", "for", "common", "mistakes", "in", "comments", "." ]
def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found. """ commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0: # Allow one space for new scopes, two spaces otherwise: if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # Checks for common mistakes in TODO comments. comment = line[commentpos:] match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') # If the comment contains an alphanumeric character, there # should be a space somewhere between it and the // unless # it's a /// or //! Doxygen comment. if (Match(r'//[^ ]*\w', comment) and not Match(r'(///|//\!)(\s+|$)', comment)): error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment')
[ "def", "CheckComment", "(", "line", ",", "filename", ",", "linenum", ",", "next_line_start", ",", "error", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", ":", "# Check if the // may be in quotes. If so,...
https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L3353-L3404
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_util.py
python
IsCondSwitch
(op)
return is_cond_switch
Return true if `op` is the Switch for a conditional.
Return true if `op` is the Switch for a conditional.
[ "Return", "true", "if", "op", "is", "the", "Switch", "for", "a", "conditional", "." ]
def IsCondSwitch(op): """Return true if `op` is the Switch for a conditional.""" if not IsSwitch(op): return False if not op.outputs: return False # Switch nodes are not part of the cond control flow context that they # represent, so consider the consumers of its outputs to determine if it is # cond switch or not. A switch is a cond switch iff all its consumers are in # cond contexts. is_cond_switch = True for o in op.outputs: for c in o.consumers(): ctxt = c._get_control_flow_context() # pylint: disable=protected-access if IsLoopEnter(c): ctxt = ctxt.outer_context is_cond_switch = is_cond_switch and (ctxt is not None and ctxt.IsCondContext()) return is_cond_switch
[ "def", "IsCondSwitch", "(", "op", ")", ":", "if", "not", "IsSwitch", "(", "op", ")", ":", "return", "False", "if", "not", "op", ".", "outputs", ":", "return", "False", "# Switch nodes are not part of the cond control flow context that they", "# represent, so consider ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_util.py#L112-L130
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ebmlib/clipboard.py
python
Clipboard.Switch
(cls, reg)
Switch to register @param reg: char
Switch to register @param reg: char
[ "Switch", "to", "register", "@param", "reg", ":", "char" ]
def Switch(cls, reg): """Switch to register @param reg: char """ if reg in cls.NAMES or reg == u'"': cls.current = reg else: raise ClipboardException(u"Switched to invalid register name")
[ "def", "Switch", "(", "cls", ",", "reg", ")", ":", "if", "reg", "in", "cls", ".", "NAMES", "or", "reg", "==", "u'\"'", ":", "cls", ".", "current", "=", "reg", "else", ":", "raise", "ClipboardException", "(", "u\"Switched to invalid register name\"", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/clipboard.py#L59-L67
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/MSVSUtil.py
python
_SuffixName
(name, suffix)
return '#'.join(parts)
Add a suffix to the end of a target. Arguments: name: name of the target (foo#target) suffix: the suffix to be added Returns: Target name with suffix added (foo_suffix#target)
Add a suffix to the end of a target.
[ "Add", "a", "suffix", "to", "the", "end", "of", "a", "target", "." ]
def _SuffixName(name, suffix): """Add a suffix to the end of a target. Arguments: name: name of the target (foo#target) suffix: the suffix to be added Returns: Target name with suffix added (foo_suffix#target) """ parts = name.rsplit('#', 1) parts[0] = '%s_%s' % (parts[0], suffix) return '#'.join(parts)
[ "def", "_SuffixName", "(", "name", ",", "suffix", ")", ":", "parts", "=", "name", ".", "rsplit", "(", "'#'", ",", "1", ")", "parts", "[", "0", "]", "=", "'%s_%s'", "%", "(", "parts", "[", "0", "]", ",", "suffix", ")", "return", "'#'", ".", "joi...
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/MSVSUtil.py#L47-L58
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/generic.py
python
NDFrame.add_prefix
(self, prefix)
return self.rename(**mapper)
Prefix labels with string `prefix`. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. Parameters ---------- prefix : str The string to add before each label. Returns ------- Series or DataFrame New Series or DataFrame with updated labels. See Also -------- Series.add_suffix: Suffix row labels with string `suffix`. DataFrame.add_suffix: Suffix column labels with string `suffix`. Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_prefix('item_') item_0 1 item_1 2 item_2 3 item_3 4 dtype: int64 >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) >>> df A B 0 1 3 1 2 4 2 3 5 3 4 6 >>> df.add_prefix('col_') col_A col_B 0 1 3 1 2 4 2 3 5 3 4 6
Prefix labels with string `prefix`.
[ "Prefix", "labels", "with", "string", "prefix", "." ]
def add_prefix(self, prefix): """ Prefix labels with string `prefix`. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. Parameters ---------- prefix : str The string to add before each label. Returns ------- Series or DataFrame New Series or DataFrame with updated labels. See Also -------- Series.add_suffix: Suffix row labels with string `suffix`. DataFrame.add_suffix: Suffix column labels with string `suffix`. Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.add_prefix('item_') item_0 1 item_1 2 item_2 3 item_3 4 dtype: int64 >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]}) >>> df A B 0 1 3 1 2 4 2 3 5 3 4 6 >>> df.add_prefix('col_') col_A col_B 0 1 3 1 2 4 2 3 5 3 4 6 """ f = functools.partial('{prefix}{}'.format, prefix=prefix) mapper = {self._info_axis_name: f} return self.rename(**mapper)
[ "def", "add_prefix", "(", "self", ",", "prefix", ")", ":", "f", "=", "functools", ".", "partial", "(", "'{prefix}{}'", ".", "format", ",", "prefix", "=", "prefix", ")", "mapper", "=", "{", "self", ".", "_info_axis_name", ":", "f", "}", "return", "self"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L3858-L3915
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/pipeline.py
python
make_pipeline
(*steps, **kwargs)
return Pipeline(_name_estimators(steps), memory=memory, verbose=verbose)
Construct a Pipeline from the given estimators. This is a shorthand for the Pipeline constructor; it does not require, and does not permit, naming the estimators. Instead, their names will be set to the lowercase of their types automatically. Parameters ---------- *steps : list of estimators. memory : None, str or object with the joblib.Memory interface, optional Used to cache the fitted transformers of the pipeline. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute ``named_steps`` or ``steps`` to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming. verbose : boolean, default=False If True, the time elapsed while fitting each step will be printed as it is completed. See Also -------- sklearn.pipeline.Pipeline : Class for creating a pipeline of transforms with a final estimator. Examples -------- >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.preprocessing import StandardScaler >>> make_pipeline(StandardScaler(), GaussianNB(priors=None)) Pipeline(steps=[('standardscaler', StandardScaler()), ('gaussiannb', GaussianNB())]) Returns ------- p : Pipeline
Construct a Pipeline from the given estimators.
[ "Construct", "a", "Pipeline", "from", "the", "given", "estimators", "." ]
def make_pipeline(*steps, **kwargs): """Construct a Pipeline from the given estimators. This is a shorthand for the Pipeline constructor; it does not require, and does not permit, naming the estimators. Instead, their names will be set to the lowercase of their types automatically. Parameters ---------- *steps : list of estimators. memory : None, str or object with the joblib.Memory interface, optional Used to cache the fitted transformers of the pipeline. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute ``named_steps`` or ``steps`` to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming. verbose : boolean, default=False If True, the time elapsed while fitting each step will be printed as it is completed. See Also -------- sklearn.pipeline.Pipeline : Class for creating a pipeline of transforms with a final estimator. Examples -------- >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.preprocessing import StandardScaler >>> make_pipeline(StandardScaler(), GaussianNB(priors=None)) Pipeline(steps=[('standardscaler', StandardScaler()), ('gaussiannb', GaussianNB())]) Returns ------- p : Pipeline """ memory = kwargs.pop('memory', None) verbose = kwargs.pop('verbose', False) if kwargs: raise TypeError('Unknown keyword arguments: "{}"' .format(list(kwargs.keys())[0])) return Pipeline(_name_estimators(steps), memory=memory, verbose=verbose)
[ "def", "make_pipeline", "(", "*", "steps", ",", "*", "*", "kwargs", ")", ":", "memory", "=", "kwargs", ".", "pop", "(", "'memory'", ",", "None", ")", "verbose", "=", "kwargs", ".", "pop", "(", "'verbose'", ",", "False", ")", "if", "kwargs", ":", "r...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/pipeline.py#L656-L703
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/graph_editor/transform.py
python
Transformer._connect_ops
(self, info)
Connect the previously copied ops.
Connect the previously copied ops.
[ "Connect", "the", "previously", "copied", "ops", "." ]
def _connect_ops(self, info): """Connect the previously copied ops.""" for op in info.sgv.ops: logging.debug("Finalizing op: %s", op.name) op_ = info.transformed_ops[op] # pylint: disable=protected-access if op_.inputs: raise ValueError("The newly transformed op should not have " "any inputs yet: {}".format(op_.name)) inputs_ = [self._transformed_t(info, t) for t in op.inputs] for t in inputs_: op_._add_input(t) # Finalize original op. if op._original_op: original_op = info.transform_original_op_handler(info, op._original_op) if original_op is None: logging.debug("Could not find original op for: %s", op_.name) else: op_._original_op = original_op # Finalize control inputs: control_inputs_ = [self.transform_control_input_handler(info, ci) for ci in op.control_inputs] control_inputs_ = [ci for ci in control_inputs_ if ci is not None] reroute.add_control_inputs(op_, control_inputs_)
[ "def", "_connect_ops", "(", "self", ",", "info", ")", ":", "for", "op", "in", "info", ".", "sgv", ".", "ops", ":", "logging", ".", "debug", "(", "\"Finalizing op: %s\"", ",", "op", ".", "name", ")", "op_", "=", "info", ".", "transformed_ops", "[", "o...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/graph_editor/transform.py#L459-L485
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
TimeSpan.Hours
(*args, **kwargs)
return _misc_.TimeSpan_Hours(*args, **kwargs)
Hours(long hours) -> TimeSpan
Hours(long hours) -> TimeSpan
[ "Hours", "(", "long", "hours", ")", "-", ">", "TimeSpan" ]
def Hours(*args, **kwargs): """Hours(long hours) -> TimeSpan""" return _misc_.TimeSpan_Hours(*args, **kwargs)
[ "def", "Hours", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "TimeSpan_Hours", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4379-L4381
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/implementations/webhdfs.py
python
WebHDFS._open
( self, path, mode="rb", block_size=None, autocommit=True, replication=None, permissions=None, **kwargs )
return WebHDFile( self, path, mode=mode, block_size=block_size, tempdir=self.tempdir, autocommit=autocommit, replication=replication, permissions=permissions, )
Parameters ---------- path: str File location mode: str 'rb', 'wb', etc. block_size: int Client buffer size for read-ahead or write buffer autocommit: bool If False, writes to temporary file that only gets put in final location upon commit replication: int Number of copies of file on the cluster, write mode only permissions: str or int posix permissions, write mode only kwargs Returns ------- WebHDFile instance
[]
def _open( self, path, mode="rb", block_size=None, autocommit=True, replication=None, permissions=None, **kwargs ): """ Parameters ---------- path: str File location mode: str 'rb', 'wb', etc. block_size: int Client buffer size for read-ahead or write buffer autocommit: bool If False, writes to temporary file that only gets put in final location upon commit replication: int Number of copies of file on the cluster, write mode only permissions: str or int posix permissions, write mode only kwargs Returns ------- WebHDFile instance """ block_size = block_size or self.blocksize return WebHDFile( self, path, mode=mode, block_size=block_size, tempdir=self.tempdir, autocommit=autocommit, replication=replication, permissions=permissions, )
[ "def", "_open", "(", "self", ",", "path", ",", "mode", "=", "\"rb\"", ",", "block_size", "=", "None", ",", "autocommit", "=", "True", ",", "replication", "=", "None", ",", "permissions", "=", "None", ",", "*", "*", "kwargs", ")", ":", "block_size", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/implementations/webhdfs.py#L140-L183
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
DC.DrawIcon
(*args, **kwargs)
return _gdi_.DC_DrawIcon(*args, **kwargs)
DrawIcon(self, Icon icon, int x, int y) Draw an icon on the display (does nothing if the device context is PostScript). This can be the simplest way of drawing bitmaps on a window.
DrawIcon(self, Icon icon, int x, int y)
[ "DrawIcon", "(", "self", "Icon", "icon", "int", "x", "int", "y", ")" ]
def DrawIcon(*args, **kwargs): """ DrawIcon(self, Icon icon, int x, int y) Draw an icon on the display (does nothing if the device context is PostScript). This can be the simplest way of drawing bitmaps on a window. """ return _gdi_.DC_DrawIcon(*args, **kwargs)
[ "def", "DrawIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_DrawIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L3677-L3685