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
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/module/base_module.py
python
BaseModule.output_names
(self)
A list of names for the outputs of this module.
A list of names for the outputs of this module.
[ "A", "list", "of", "names", "for", "the", "outputs", "of", "this", "module", "." ]
def output_names(self): """A list of names for the outputs of this module.""" raise NotImplementedError()
[ "def", "output_names", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/module/base_module.py#L545-L547
kevinlin311tw/Caffe-DeepBinaryCode
9eaa7662be47d49f475ecbeea2bd51be105270d2
python/caffe/net_spec.py
python
to_proto
(*tops)
return net
Generate a NetParameter that contains all layers needed to compute all arguments.
Generate a NetParameter that contains all layers needed to compute all arguments.
[ "Generate", "a", "NetParameter", "that", "contains", "all", "layers", "needed", "to", "compute", "all", "arguments", "." ]
def to_proto(*tops): """Generate a NetParameter that contains all layers needed to compute all arguments.""" layers = OrderedDict() autonames = Counter() for top in tops: top.fn._to_proto(layers, {}, autonames) net = caffe_pb2.NetParameter() net.layer.extend(layers.values()) return net
[ "def", "to_proto", "(", "*", "tops", ")", ":", "layers", "=", "OrderedDict", "(", ")", "autonames", "=", "Counter", "(", ")", "for", "top", "in", "tops", ":", "top", ".", "fn", ".", "_to_proto", "(", "layers", ",", "{", "}", ",", "autonames", ")", "net", "=", "caffe_pb2", ".", "NetParameter", "(", ")", "net", ".", "layer", ".", "extend", "(", "layers", ".", "values", "(", ")", ")", "return", "net" ]
https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/python/caffe/net_spec.py#L43-L53
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PyIntProperty.__init__
(self, *args)
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), long value=0) -> PyIntProperty __init__(self, String label, String name, wxLongLong value) -> PyIntProperty
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), long value=0) -> PyIntProperty __init__(self, String label, String name, wxLongLong value) -> PyIntProperty
[ "__init__", "(", "self", "String", "label", "=", "(", "*", "wxPGProperty", "::", "sm_wxPG_LABEL", ")", "String", "name", "=", "(", "*", "wxPGProperty", "::", "sm_wxPG_LABEL", ")", "long", "value", "=", "0", ")", "-", ">", "PyIntProperty", "__init__", "(", "self", "String", "label", "String", "name", "wxLongLong", "value", ")", "-", ">", "PyIntProperty" ]
def __init__(self, *args): """ __init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), long value=0) -> PyIntProperty __init__(self, String label, String name, wxLongLong value) -> PyIntProperty """ _propgrid.PyIntProperty_swiginit(self,_propgrid.new_PyIntProperty(*args)) self._SetSelf(self); self._RegisterMethods()
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "_propgrid", ".", "PyIntProperty_swiginit", "(", "self", ",", "_propgrid", ".", "new_PyIntProperty", "(", "*", "args", ")", ")", "self", ".", "_SetSelf", "(", "self", ")", "self", ".", "_RegisterMethods", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L4370-L4377
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
osxbuild/build-app.py
python
getTarUnpackPath
(tarName, inDir=None)
return theDir
NOTE: THIS FUNCTION IS NOT RELIABLE. It only works if the tar file would extract a single directory with all contents in that dir. If it unpacks more than one file or directory, the output will be incomplete.
NOTE: THIS FUNCTION IS NOT RELIABLE. It only works if the tar file would extract a single directory with all contents in that dir. If it unpacks more than one file or directory, the output will be incomplete.
[ "NOTE", ":", "THIS", "FUNCTION", "IS", "NOT", "RELIABLE", ".", "It", "only", "works", "if", "the", "tar", "file", "would", "extract", "a", "single", "directory", "with", "all", "contents", "in", "that", "dir", ".", "If", "it", "unpacks", "more", "than", "one", "file", "or", "directory", "the", "output", "will", "be", "incomplete", "." ]
def getTarUnpackPath(tarName, inDir=None): """ NOTE: THIS FUNCTION IS NOT RELIABLE. It only works if the tar file would extract a single directory with all contents in that dir. If it unpacks more than one file or directory, the output will be incomplete. """ tarPath = tarName if inDir is not None: tarPath = path.join(inDir, tarName) # HACK: XZ support was added to tarfile.open() in Python 3.3. Can't use for # now, so we'll have to apply a hack to get around this. In addition, the # builder must have the xz binary on their build machine, otherwise the # following error will appear: "tar: Error opening archive: Child process # exited with status 254Child process exited with status 254" if tarName == "Python-%s.tar.xz" % pythonVer: theDir = "Python-%s" % pythonVer else: tar = tarfile.open(tarPath,'r') theDir = tar.next().name.split('/')[0] tar.close() return theDir
[ "def", "getTarUnpackPath", "(", "tarName", ",", "inDir", "=", "None", ")", ":", "tarPath", "=", "tarName", "if", "inDir", "is", "not", "None", ":", "tarPath", "=", "path", ".", "join", "(", "inDir", ",", "tarName", ")", "# HACK: XZ support was added to tarfile.open() in Python 3.3. Can't use for", "# now, so we'll have to apply a hack to get around this. In addition, the", "# builder must have the xz binary on their build machine, otherwise the", "# following error will appear: \"tar: Error opening archive: Child process", "# exited with status 254Child process exited with status 254\"", "if", "tarName", "==", "\"Python-%s.tar.xz\"", "%", "pythonVer", ":", "theDir", "=", "\"Python-%s\"", "%", "pythonVer", "else", ":", "tar", "=", "tarfile", ".", "open", "(", "tarPath", ",", "'r'", ")", "theDir", "=", "tar", ".", "next", "(", ")", ".", "name", ".", "split", "(", "'/'", ")", "[", "0", "]", "tar", ".", "close", "(", ")", "return", "theDir" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/osxbuild/build-app.py#L201-L222
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
_not
(x)
return Not()(x)[0]
Return `np.logical_not(x)`, where x is Tensor.
Return `np.logical_not(x)`, where x is Tensor.
[ "Return", "np", ".", "logical_not", "(", "x", ")", "where", "x", "is", "Tensor", "." ]
def _not(x): """ Return `np.logical_not(x)`, where x is Tensor. """ return Not()(x)[0]
[ "def", "_not", "(", "x", ")", ":", "return", "Not", "(", ")", "(", "x", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L3575-L3579
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/tensor_forest/python/tensor_forest.py
python
RandomTreeGraphs.training_graph
(self, input_data, input_labels, random_seed, data_spec, epoch=None)
return control_flow_ops.group(*updates)
Constructs a TF graph for training a random tree. Args: input_data: A tensor or SparseTensor or placeholder for input data. input_labels: A tensor or placeholder for labels associated with input_data. random_seed: The random number generator seed to use for this tree. 0 means use the current time as the seed. data_spec: A list of tf.dtype values specifying the original types of each column. epoch: A tensor or placeholder for the epoch the training data comes from. Returns: The last op in the random tree training graph.
Constructs a TF graph for training a random tree.
[ "Constructs", "a", "TF", "graph", "for", "training", "a", "random", "tree", "." ]
def training_graph(self, input_data, input_labels, random_seed, data_spec, epoch=None): """Constructs a TF graph for training a random tree. Args: input_data: A tensor or SparseTensor or placeholder for input data. input_labels: A tensor or placeholder for labels associated with input_data. random_seed: The random number generator seed to use for this tree. 0 means use the current time as the seed. data_spec: A list of tf.dtype values specifying the original types of each column. epoch: A tensor or placeholder for the epoch the training data comes from. Returns: The last op in the random tree training graph. """ epoch = [0] if epoch is None else epoch sparse_indices = [] sparse_values = [] sparse_shape = [] if isinstance(input_data, ops.SparseTensor): sparse_indices = input_data.indices sparse_values = input_data.values sparse_shape = input_data.shape input_data = [] # Count extremely random stats. (node_sums, node_squares, splits_indices, splits_sums, splits_squares, totals_indices, totals_sums, totals_squares, input_leaves) = ( self.training_ops.count_extremely_random_stats( input_data, sparse_indices, sparse_values, sparse_shape, data_spec, input_labels, self.variables.tree, self.variables.tree_thresholds, self.variables.node_to_accumulator_map, self.variables.candidate_split_features, self.variables.candidate_split_thresholds, self.variables.start_epoch, epoch, num_classes=self.params.num_output_columns, regression=self.params.regression)) node_update_ops = [] node_update_ops.append( state_ops.assign_add(self.variables.node_sums, node_sums)) splits_update_ops = [] splits_update_ops.append(self.training_ops.scatter_add_ndim( self.variables.candidate_split_sums, splits_indices, splits_sums)) splits_update_ops.append(self.training_ops.scatter_add_ndim( self.variables.accumulator_sums, totals_indices, totals_sums)) if self.params.regression: node_update_ops.append(state_ops.assign_add(self.variables.node_squares, node_squares)) splits_update_ops.append(self.training_ops.scatter_add_ndim( self.variables.candidate_split_squares, splits_indices, splits_squares)) splits_update_ops.append(self.training_ops.scatter_add_ndim( self.variables.accumulator_squares, totals_indices, totals_squares)) # Sample inputs. update_indices, feature_updates, threshold_updates = ( self.training_ops.sample_inputs( input_data, sparse_indices, sparse_values, sparse_shape, self.variables.node_to_accumulator_map, input_leaves, self.variables.candidate_split_features, self.variables.candidate_split_thresholds, split_initializations_per_input=( self.params.split_initializations_per_input), split_sampling_random_seed=random_seed)) update_features_op = state_ops.scatter_update( self.variables.candidate_split_features, update_indices, feature_updates) update_thresholds_op = state_ops.scatter_update( self.variables.candidate_split_thresholds, update_indices, threshold_updates) # Calculate finished nodes. with ops.control_dependencies(splits_update_ops): children = array_ops.squeeze(array_ops.slice( self.variables.tree, [0, 0], [-1, 1]), squeeze_dims=[1]) is_leaf = math_ops.equal(constants.LEAF_NODE, children) leaves = math_ops.to_int32(array_ops.squeeze(array_ops.where(is_leaf), squeeze_dims=[1])) finished, stale = self.training_ops.finished_nodes( leaves, self.variables.node_to_accumulator_map, self.variables.candidate_split_sums, self.variables.candidate_split_squares, self.variables.accumulator_sums, self.variables.accumulator_squares, self.variables.start_epoch, epoch, num_split_after_samples=self.params.split_after_samples, min_split_samples=self.params.min_split_samples) # Update leaf scores. non_fertile_leaves = array_ops.boolean_mask( leaves, math_ops.less(array_ops.gather( self.variables.node_to_accumulator_map, leaves), 0)) # TODO(gilberth): It should be possible to limit the number of non # fertile leaves we calculate scores for, especially since we can only take # at most array_ops.shape(finished)[0] of them. with ops.control_dependencies(node_update_ops): sums = array_ops.gather(self.variables.node_sums, non_fertile_leaves) if self.params.regression: squares = array_ops.gather(self.variables.node_squares, non_fertile_leaves) non_fertile_leaf_scores = self._variance(sums, squares) else: non_fertile_leaf_scores = self._weighted_gini(sums) # Calculate best splits. with ops.control_dependencies(splits_update_ops): split_indices = self.training_ops.best_splits( finished, self.variables.node_to_accumulator_map, self.variables.candidate_split_sums, self.variables.candidate_split_squares, self.variables.accumulator_sums, self.variables.accumulator_squares, regression=self.params.regression) # Grow tree. with ops.control_dependencies([update_features_op, update_thresholds_op]): (tree_update_indices, tree_children_updates, tree_threshold_updates, new_eot) = (self.training_ops.grow_tree( self.variables.end_of_tree, self.variables.node_to_accumulator_map, finished, split_indices, self.variables.candidate_split_features, self.variables.candidate_split_thresholds)) tree_update_op = state_ops.scatter_update( self.variables.tree, tree_update_indices, tree_children_updates) thresholds_update_op = state_ops.scatter_update( self.variables.tree_thresholds, tree_update_indices, tree_threshold_updates) # TODO(thomaswc): Only update the epoch on the new leaves. new_epoch_updates = epoch * array_ops.ones_like(tree_threshold_updates, dtype=dtypes.int32) epoch_update_op = state_ops.scatter_update( self.variables.start_epoch, tree_update_indices, new_epoch_updates) # Update fertile slots. with ops.control_dependencies([tree_update_op]): (node_map_updates, accumulators_cleared, accumulators_allocated) = ( self.training_ops.update_fertile_slots( finished, non_fertile_leaves, non_fertile_leaf_scores, self.variables.end_of_tree, self.variables.accumulator_sums, self.variables.node_to_accumulator_map, stale, regression=self.params.regression)) # Ensure end_of_tree doesn't get updated until UpdateFertileSlots has # used it to calculate new leaves. gated_new_eot, = control_flow_ops.tuple([new_eot], control_inputs=[node_map_updates]) eot_update_op = state_ops.assign(self.variables.end_of_tree, gated_new_eot) updates = [] updates.append(eot_update_op) updates.append(tree_update_op) updates.append(thresholds_update_op) updates.append(epoch_update_op) updates.append(state_ops.scatter_update( self.variables.node_to_accumulator_map, array_ops.squeeze(array_ops.slice(node_map_updates, [0, 0], [1, -1]), squeeze_dims=[0]), array_ops.squeeze(array_ops.slice(node_map_updates, [1, 0], [1, -1]), squeeze_dims=[0]))) cleared_and_allocated_accumulators = array_ops.concat( 0, [accumulators_cleared, accumulators_allocated]) # Calculate values to put into scatter update for candidate counts. # Candidate split counts are always reset back to 0 for both cleared # and allocated accumulators. This means some accumulators might be doubly # reset to 0 if the were released and not allocated, then later allocated. split_values = array_ops.tile( array_ops.expand_dims(array_ops.expand_dims( array_ops.zeros_like(cleared_and_allocated_accumulators, dtype=dtypes.float32), 1), 2), [1, self.params.num_splits_to_consider, self.params.num_output_columns]) updates.append(state_ops.scatter_update( self.variables.candidate_split_sums, cleared_and_allocated_accumulators, split_values)) if self.params.regression: updates.append(state_ops.scatter_update( self.variables.candidate_split_squares, cleared_and_allocated_accumulators, split_values)) # Calculate values to put into scatter update for total counts. total_cleared = array_ops.tile( array_ops.expand_dims( math_ops.neg(array_ops.ones_like(accumulators_cleared, dtype=dtypes.float32)), 1), [1, self.params.num_output_columns]) total_reset = array_ops.tile( array_ops.expand_dims( array_ops.zeros_like(accumulators_allocated, dtype=dtypes.float32), 1), [1, self.params.num_output_columns]) accumulator_updates = array_ops.concat(0, [total_cleared, total_reset]) updates.append(state_ops.scatter_update( self.variables.accumulator_sums, cleared_and_allocated_accumulators, accumulator_updates)) if self.params.regression: updates.append(state_ops.scatter_update( self.variables.accumulator_squares, cleared_and_allocated_accumulators, accumulator_updates)) # Calculate values to put into scatter update for candidate splits. split_features_updates = array_ops.tile( array_ops.expand_dims( math_ops.neg(array_ops.ones_like( cleared_and_allocated_accumulators)), 1), [1, self.params.num_splits_to_consider]) updates.append(state_ops.scatter_update( self.variables.candidate_split_features, cleared_and_allocated_accumulators, split_features_updates)) updates += self.finish_iteration() return control_flow_ops.group(*updates)
[ "def", "training_graph", "(", "self", ",", "input_data", ",", "input_labels", ",", "random_seed", ",", "data_spec", ",", "epoch", "=", "None", ")", ":", "epoch", "=", "[", "0", "]", "if", "epoch", "is", "None", "else", "epoch", "sparse_indices", "=", "[", "]", "sparse_values", "=", "[", "]", "sparse_shape", "=", "[", "]", "if", "isinstance", "(", "input_data", ",", "ops", ".", "SparseTensor", ")", ":", "sparse_indices", "=", "input_data", ".", "indices", "sparse_values", "=", "input_data", ".", "values", "sparse_shape", "=", "input_data", ".", "shape", "input_data", "=", "[", "]", "# Count extremely random stats.", "(", "node_sums", ",", "node_squares", ",", "splits_indices", ",", "splits_sums", ",", "splits_squares", ",", "totals_indices", ",", "totals_sums", ",", "totals_squares", ",", "input_leaves", ")", "=", "(", "self", ".", "training_ops", ".", "count_extremely_random_stats", "(", "input_data", ",", "sparse_indices", ",", "sparse_values", ",", "sparse_shape", ",", "data_spec", ",", "input_labels", ",", "self", ".", "variables", ".", "tree", ",", "self", ".", "variables", ".", "tree_thresholds", ",", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "self", ".", "variables", ".", "candidate_split_features", ",", "self", ".", "variables", ".", "candidate_split_thresholds", ",", "self", ".", "variables", ".", "start_epoch", ",", "epoch", ",", "num_classes", "=", "self", ".", "params", ".", "num_output_columns", ",", "regression", "=", "self", ".", "params", ".", "regression", ")", ")", "node_update_ops", "=", "[", "]", "node_update_ops", ".", "append", "(", "state_ops", ".", "assign_add", "(", "self", ".", "variables", ".", "node_sums", ",", "node_sums", ")", ")", "splits_update_ops", "=", "[", "]", "splits_update_ops", ".", "append", "(", "self", ".", "training_ops", ".", "scatter_add_ndim", "(", "self", ".", "variables", ".", "candidate_split_sums", ",", "splits_indices", ",", "splits_sums", ")", ")", "splits_update_ops", ".", "append", "(", "self", ".", "training_ops", ".", "scatter_add_ndim", "(", "self", ".", "variables", ".", "accumulator_sums", ",", "totals_indices", ",", "totals_sums", ")", ")", "if", "self", ".", "params", ".", "regression", ":", "node_update_ops", ".", "append", "(", "state_ops", ".", "assign_add", "(", "self", ".", "variables", ".", "node_squares", ",", "node_squares", ")", ")", "splits_update_ops", ".", "append", "(", "self", ".", "training_ops", ".", "scatter_add_ndim", "(", "self", ".", "variables", ".", "candidate_split_squares", ",", "splits_indices", ",", "splits_squares", ")", ")", "splits_update_ops", ".", "append", "(", "self", ".", "training_ops", ".", "scatter_add_ndim", "(", "self", ".", "variables", ".", "accumulator_squares", ",", "totals_indices", ",", "totals_squares", ")", ")", "# Sample inputs.", "update_indices", ",", "feature_updates", ",", "threshold_updates", "=", "(", "self", ".", "training_ops", ".", "sample_inputs", "(", "input_data", ",", "sparse_indices", ",", "sparse_values", ",", "sparse_shape", ",", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "input_leaves", ",", "self", ".", "variables", ".", "candidate_split_features", ",", "self", ".", "variables", ".", "candidate_split_thresholds", ",", "split_initializations_per_input", "=", "(", "self", ".", "params", ".", "split_initializations_per_input", ")", ",", "split_sampling_random_seed", "=", "random_seed", ")", ")", "update_features_op", "=", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "candidate_split_features", ",", "update_indices", ",", "feature_updates", ")", "update_thresholds_op", "=", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "candidate_split_thresholds", ",", "update_indices", ",", "threshold_updates", ")", "# Calculate finished nodes.", "with", "ops", ".", "control_dependencies", "(", "splits_update_ops", ")", ":", "children", "=", "array_ops", ".", "squeeze", "(", "array_ops", ".", "slice", "(", "self", ".", "variables", ".", "tree", ",", "[", "0", ",", "0", "]", ",", "[", "-", "1", ",", "1", "]", ")", ",", "squeeze_dims", "=", "[", "1", "]", ")", "is_leaf", "=", "math_ops", ".", "equal", "(", "constants", ".", "LEAF_NODE", ",", "children", ")", "leaves", "=", "math_ops", ".", "to_int32", "(", "array_ops", ".", "squeeze", "(", "array_ops", ".", "where", "(", "is_leaf", ")", ",", "squeeze_dims", "=", "[", "1", "]", ")", ")", "finished", ",", "stale", "=", "self", ".", "training_ops", ".", "finished_nodes", "(", "leaves", ",", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "self", ".", "variables", ".", "candidate_split_sums", ",", "self", ".", "variables", ".", "candidate_split_squares", ",", "self", ".", "variables", ".", "accumulator_sums", ",", "self", ".", "variables", ".", "accumulator_squares", ",", "self", ".", "variables", ".", "start_epoch", ",", "epoch", ",", "num_split_after_samples", "=", "self", ".", "params", ".", "split_after_samples", ",", "min_split_samples", "=", "self", ".", "params", ".", "min_split_samples", ")", "# Update leaf scores.", "non_fertile_leaves", "=", "array_ops", ".", "boolean_mask", "(", "leaves", ",", "math_ops", ".", "less", "(", "array_ops", ".", "gather", "(", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "leaves", ")", ",", "0", ")", ")", "# TODO(gilberth): It should be possible to limit the number of non", "# fertile leaves we calculate scores for, especially since we can only take", "# at most array_ops.shape(finished)[0] of them.", "with", "ops", ".", "control_dependencies", "(", "node_update_ops", ")", ":", "sums", "=", "array_ops", ".", "gather", "(", "self", ".", "variables", ".", "node_sums", ",", "non_fertile_leaves", ")", "if", "self", ".", "params", ".", "regression", ":", "squares", "=", "array_ops", ".", "gather", "(", "self", ".", "variables", ".", "node_squares", ",", "non_fertile_leaves", ")", "non_fertile_leaf_scores", "=", "self", ".", "_variance", "(", "sums", ",", "squares", ")", "else", ":", "non_fertile_leaf_scores", "=", "self", ".", "_weighted_gini", "(", "sums", ")", "# Calculate best splits.", "with", "ops", ".", "control_dependencies", "(", "splits_update_ops", ")", ":", "split_indices", "=", "self", ".", "training_ops", ".", "best_splits", "(", "finished", ",", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "self", ".", "variables", ".", "candidate_split_sums", ",", "self", ".", "variables", ".", "candidate_split_squares", ",", "self", ".", "variables", ".", "accumulator_sums", ",", "self", ".", "variables", ".", "accumulator_squares", ",", "regression", "=", "self", ".", "params", ".", "regression", ")", "# Grow tree.", "with", "ops", ".", "control_dependencies", "(", "[", "update_features_op", ",", "update_thresholds_op", "]", ")", ":", "(", "tree_update_indices", ",", "tree_children_updates", ",", "tree_threshold_updates", ",", "new_eot", ")", "=", "(", "self", ".", "training_ops", ".", "grow_tree", "(", "self", ".", "variables", ".", "end_of_tree", ",", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "finished", ",", "split_indices", ",", "self", ".", "variables", ".", "candidate_split_features", ",", "self", ".", "variables", ".", "candidate_split_thresholds", ")", ")", "tree_update_op", "=", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "tree", ",", "tree_update_indices", ",", "tree_children_updates", ")", "thresholds_update_op", "=", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "tree_thresholds", ",", "tree_update_indices", ",", "tree_threshold_updates", ")", "# TODO(thomaswc): Only update the epoch on the new leaves.", "new_epoch_updates", "=", "epoch", "*", "array_ops", ".", "ones_like", "(", "tree_threshold_updates", ",", "dtype", "=", "dtypes", ".", "int32", ")", "epoch_update_op", "=", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "start_epoch", ",", "tree_update_indices", ",", "new_epoch_updates", ")", "# Update fertile slots.", "with", "ops", ".", "control_dependencies", "(", "[", "tree_update_op", "]", ")", ":", "(", "node_map_updates", ",", "accumulators_cleared", ",", "accumulators_allocated", ")", "=", "(", "self", ".", "training_ops", ".", "update_fertile_slots", "(", "finished", ",", "non_fertile_leaves", ",", "non_fertile_leaf_scores", ",", "self", ".", "variables", ".", "end_of_tree", ",", "self", ".", "variables", ".", "accumulator_sums", ",", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "stale", ",", "regression", "=", "self", ".", "params", ".", "regression", ")", ")", "# Ensure end_of_tree doesn't get updated until UpdateFertileSlots has", "# used it to calculate new leaves.", "gated_new_eot", ",", "=", "control_flow_ops", ".", "tuple", "(", "[", "new_eot", "]", ",", "control_inputs", "=", "[", "node_map_updates", "]", ")", "eot_update_op", "=", "state_ops", ".", "assign", "(", "self", ".", "variables", ".", "end_of_tree", ",", "gated_new_eot", ")", "updates", "=", "[", "]", "updates", ".", "append", "(", "eot_update_op", ")", "updates", ".", "append", "(", "tree_update_op", ")", "updates", ".", "append", "(", "thresholds_update_op", ")", "updates", ".", "append", "(", "epoch_update_op", ")", "updates", ".", "append", "(", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "node_to_accumulator_map", ",", "array_ops", ".", "squeeze", "(", "array_ops", ".", "slice", "(", "node_map_updates", ",", "[", "0", ",", "0", "]", ",", "[", "1", ",", "-", "1", "]", ")", ",", "squeeze_dims", "=", "[", "0", "]", ")", ",", "array_ops", ".", "squeeze", "(", "array_ops", ".", "slice", "(", "node_map_updates", ",", "[", "1", ",", "0", "]", ",", "[", "1", ",", "-", "1", "]", ")", ",", "squeeze_dims", "=", "[", "0", "]", ")", ")", ")", "cleared_and_allocated_accumulators", "=", "array_ops", ".", "concat", "(", "0", ",", "[", "accumulators_cleared", ",", "accumulators_allocated", "]", ")", "# Calculate values to put into scatter update for candidate counts.", "# Candidate split counts are always reset back to 0 for both cleared", "# and allocated accumulators. This means some accumulators might be doubly", "# reset to 0 if the were released and not allocated, then later allocated.", "split_values", "=", "array_ops", ".", "tile", "(", "array_ops", ".", "expand_dims", "(", "array_ops", ".", "expand_dims", "(", "array_ops", ".", "zeros_like", "(", "cleared_and_allocated_accumulators", ",", "dtype", "=", "dtypes", ".", "float32", ")", ",", "1", ")", ",", "2", ")", ",", "[", "1", ",", "self", ".", "params", ".", "num_splits_to_consider", ",", "self", ".", "params", ".", "num_output_columns", "]", ")", "updates", ".", "append", "(", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "candidate_split_sums", ",", "cleared_and_allocated_accumulators", ",", "split_values", ")", ")", "if", "self", ".", "params", ".", "regression", ":", "updates", ".", "append", "(", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "candidate_split_squares", ",", "cleared_and_allocated_accumulators", ",", "split_values", ")", ")", "# Calculate values to put into scatter update for total counts.", "total_cleared", "=", "array_ops", ".", "tile", "(", "array_ops", ".", "expand_dims", "(", "math_ops", ".", "neg", "(", "array_ops", ".", "ones_like", "(", "accumulators_cleared", ",", "dtype", "=", "dtypes", ".", "float32", ")", ")", ",", "1", ")", ",", "[", "1", ",", "self", ".", "params", ".", "num_output_columns", "]", ")", "total_reset", "=", "array_ops", ".", "tile", "(", "array_ops", ".", "expand_dims", "(", "array_ops", ".", "zeros_like", "(", "accumulators_allocated", ",", "dtype", "=", "dtypes", ".", "float32", ")", ",", "1", ")", ",", "[", "1", ",", "self", ".", "params", ".", "num_output_columns", "]", ")", "accumulator_updates", "=", "array_ops", ".", "concat", "(", "0", ",", "[", "total_cleared", ",", "total_reset", "]", ")", "updates", ".", "append", "(", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "accumulator_sums", ",", "cleared_and_allocated_accumulators", ",", "accumulator_updates", ")", ")", "if", "self", ".", "params", ".", "regression", ":", "updates", ".", "append", "(", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "accumulator_squares", ",", "cleared_and_allocated_accumulators", ",", "accumulator_updates", ")", ")", "# Calculate values to put into scatter update for candidate splits.", "split_features_updates", "=", "array_ops", ".", "tile", "(", "array_ops", ".", "expand_dims", "(", "math_ops", ".", "neg", "(", "array_ops", ".", "ones_like", "(", "cleared_and_allocated_accumulators", ")", ")", ",", "1", ")", ",", "[", "1", ",", "self", ".", "params", ".", "num_splits_to_consider", "]", ")", "updates", ".", "append", "(", "state_ops", ".", "scatter_update", "(", "self", ".", "variables", ".", "candidate_split_features", ",", "cleared_and_allocated_accumulators", ",", "split_features_updates", ")", ")", "updates", "+=", "self", ".", "finish_iteration", "(", ")", "return", "control_flow_ops", ".", "group", "(", "*", "updates", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/tensor_forest/python/tensor_forest.py#L528-L756
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pdfviewer/viewer.py
python
pypdfProcessor.ConvertCMYK
(self, operand)
return (r, g, b)
Convert CMYK values (0 to 1.0) in operand to nearest RGB
Convert CMYK values (0 to 1.0) in operand to nearest RGB
[ "Convert", "CMYK", "values", "(", "0", "to", "1", ".", "0", ")", "in", "operand", "to", "nearest", "RGB" ]
def ConvertCMYK(self, operand): "Convert CMYK values (0 to 1.0) in operand to nearest RGB" c, m, y, k = operand r = round((1-c)*(1-k)*255) b = round((1-y)*(1-k)*255) g = round((1-m)*(1-k)*255) return (r, g, b)
[ "def", "ConvertCMYK", "(", "self", ",", "operand", ")", ":", "c", ",", "m", ",", "y", ",", "k", "=", "operand", "r", "=", "round", "(", "(", "1", "-", "c", ")", "*", "(", "1", "-", "k", ")", "*", "255", ")", "b", "=", "round", "(", "(", "1", "-", "y", ")", "*", "(", "1", "-", "k", ")", "*", "255", ")", "g", "=", "round", "(", "(", "1", "-", "m", ")", "*", "(", "1", "-", "k", ")", "*", "255", ")", "return", "(", "r", ",", "g", ",", "b", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pdfviewer/viewer.py#L920-L926
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py
python
get_cookie_header
(jar, request)
return r.get_new_headers().get('Cookie')
Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str
Produce an appropriate Cookie header string to be sent with `request`, or None.
[ "Produce", "an", "appropriate", "Cookie", "header", "string", "to", "be", "sent", "with", "request", "or", "None", "." ]
def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie')
[ "def", "get_cookie_header", "(", "jar", ",", "request", ")", ":", "r", "=", "MockRequest", "(", "request", ")", "jar", ".", "add_cookie_header", "(", "r", ")", "return", "r", ".", "get_new_headers", "(", ")", ".", "get", "(", "'Cookie'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py#L135-L143
NVIDIA/MDL-SDK
aa9642b2546ad7b6236b5627385d882c2ed83c5d
src/mdl/jit/llvm/dist/utils/gdb-scripts/prettyprinters.py
python
TwinePrinter.string_from_pretty_printer_lookup
(self, val)
return s
Lookup the default pretty-printer for val and use it. If no pretty-printer is defined for the type of val, print an error and return a placeholder string.
Lookup the default pretty-printer for val and use it.
[ "Lookup", "the", "default", "pretty", "-", "printer", "for", "val", "and", "use", "it", "." ]
def string_from_pretty_printer_lookup(self, val): '''Lookup the default pretty-printer for val and use it. If no pretty-printer is defined for the type of val, print an error and return a placeholder string.''' pp = gdb.default_visualizer(val) if pp: s = pp.to_string() # The pretty-printer may return a LazyString instead of an actual Python # string. Convert it to a Python string. However, GDB doesn't seem to # register the LazyString type, so we can't check # "type(s) == gdb.LazyString". if 'LazyString' in type(s).__name__: s = s.value().address.string() else: print(('No pretty printer for {} found. The resulting Twine ' + 'representation will be incomplete.').format(val.type.name)) s = '(missing {})'.format(val.type.name) return s
[ "def", "string_from_pretty_printer_lookup", "(", "self", ",", "val", ")", ":", "pp", "=", "gdb", ".", "default_visualizer", "(", "val", ")", "if", "pp", ":", "s", "=", "pp", ".", "to_string", "(", ")", "# The pretty-printer may return a LazyString instead of an actual Python", "# string. Convert it to a Python string. However, GDB doesn't seem to", "# register the LazyString type, so we can't check", "# \"type(s) == gdb.LazyString\".", "if", "'LazyString'", "in", "type", "(", "s", ")", ".", "__name__", ":", "s", "=", "s", ".", "value", "(", ")", ".", "address", ".", "string", "(", ")", "else", ":", "print", "(", "(", "'No pretty printer for {} found. The resulting Twine '", "+", "'representation will be incomplete.'", ")", ".", "format", "(", "val", ".", "type", ".", "name", ")", ")", "s", "=", "'(missing {})'", ".", "format", "(", "val", ".", "type", ".", "name", ")", "return", "s" ]
https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/utils/gdb-scripts/prettyprinters.py#L209-L231
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pubsub/core/topicobj.py
python
Topic.isValid
(self, listener)
return self.__validator.isValid(listener)
Return True only if listener could be subscribed to this topic, otherwise returns False. Note that method raises TopicDefnError if self not hasMDS().
Return True only if listener could be subscribed to this topic, otherwise returns False. Note that method raises TopicDefnError if self not hasMDS().
[ "Return", "True", "only", "if", "listener", "could", "be", "subscribed", "to", "this", "topic", "otherwise", "returns", "False", ".", "Note", "that", "method", "raises", "TopicDefnError", "if", "self", "not", "hasMDS", "()", "." ]
def isValid(self, listener): """Return True only if listener could be subscribed to this topic, otherwise returns False. Note that method raises TopicDefnError if self not hasMDS().""" if not self.hasMDS(): raise TopicDefnError(self.__tupleName) return self.__validator.isValid(listener)
[ "def", "isValid", "(", "self", ",", "listener", ")", ":", "if", "not", "self", ".", "hasMDS", "(", ")", ":", "raise", "TopicDefnError", "(", "self", ".", "__tupleName", ")", "return", "self", ".", "__validator", ".", "isValid", "(", "listener", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/topicobj.py#L281-L287
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
bindings/python/llvm/object.py
python
Section.address
(self)
return lib.LLVMGetSectionAddress(self)
The address of this section, in long bytes.
The address of this section, in long bytes.
[ "The", "address", "of", "this", "section", "in", "long", "bytes", "." ]
def address(self): """The address of this section, in long bytes.""" if self.expired: raise Exception('Section instance has expired.') return lib.LLVMGetSectionAddress(self)
[ "def", "address", "(", "self", ")", ":", "if", "self", ".", "expired", ":", "raise", "Exception", "(", "'Section instance has expired.'", ")", "return", "lib", ".", "LLVMGetSectionAddress", "(", "self", ")" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/bindings/python/llvm/object.py#L225-L230
mysql/mysql-router
cc0179f982bb9739a834eb6fd205a56224616133
ext/gmock/scripts/generator/cpp/ast.py
python
AstBuilder.GetName
(self, seq=None)
return tokens, next_token
Returns ([tokens], next_token_info).
Returns ([tokens], next_token_info).
[ "Returns", "(", "[", "tokens", "]", "next_token_info", ")", "." ]
def GetName(self, seq=None): """Returns ([tokens], next_token_info).""" GetNextToken = self._GetNextToken if seq is not None: it = iter(seq) GetNextToken = lambda: next(it) next_token = GetNextToken() tokens = [] last_token_was_name = False while (next_token.token_type == tokenize.NAME or (next_token.token_type == tokenize.SYNTAX and next_token.name in ('::', '<'))): # Two NAMEs in a row means the identifier should terminate. # It's probably some sort of variable declaration. if last_token_was_name and next_token.token_type == tokenize.NAME: break last_token_was_name = next_token.token_type == tokenize.NAME tokens.append(next_token) # Handle templated names. if next_token.name == '<': tokens.extend(self._GetMatchingChar('<', '>', GetNextToken)) last_token_was_name = True next_token = GetNextToken() return tokens, next_token
[ "def", "GetName", "(", "self", ",", "seq", "=", "None", ")", ":", "GetNextToken", "=", "self", ".", "_GetNextToken", "if", "seq", "is", "not", "None", ":", "it", "=", "iter", "(", "seq", ")", "GetNextToken", "=", "lambda", ":", "next", "(", "it", ")", "next_token", "=", "GetNextToken", "(", ")", "tokens", "=", "[", "]", "last_token_was_name", "=", "False", "while", "(", "next_token", ".", "token_type", "==", "tokenize", ".", "NAME", "or", "(", "next_token", ".", "token_type", "==", "tokenize", ".", "SYNTAX", "and", "next_token", ".", "name", "in", "(", "'::'", ",", "'<'", ")", ")", ")", ":", "# Two NAMEs in a row means the identifier should terminate.", "# It's probably some sort of variable declaration.", "if", "last_token_was_name", "and", "next_token", ".", "token_type", "==", "tokenize", ".", "NAME", ":", "break", "last_token_was_name", "=", "next_token", ".", "token_type", "==", "tokenize", ".", "NAME", "tokens", ".", "append", "(", "next_token", ")", "# Handle templated names.", "if", "next_token", ".", "name", "==", "'<'", ":", "tokens", ".", "extend", "(", "self", ".", "_GetMatchingChar", "(", "'<'", ",", "'>'", ",", "GetNextToken", ")", ")", "last_token_was_name", "=", "True", "next_token", "=", "GetNextToken", "(", ")", "return", "tokens", ",", "next_token" ]
https://github.com/mysql/mysql-router/blob/cc0179f982bb9739a834eb6fd205a56224616133/ext/gmock/scripts/generator/cpp/ast.py#L927-L950
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/autodiff/grad_manager.py
python
GradManager.attached_tensors
(self)
return [spec.tensor() for spec in self._attach_specs.values()]
r"""Return attached tensor list from :meth:`attach`.
r"""Return attached tensor list from :meth:`attach`.
[ "r", "Return", "attached", "tensor", "list", "from", ":", "meth", ":", "attach", "." ]
def attached_tensors(self): r"""Return attached tensor list from :meth:`attach`.""" return [spec.tensor() for spec in self._attach_specs.values()]
[ "def", "attached_tensors", "(", "self", ")", ":", "return", "[", "spec", ".", "tensor", "(", ")", "for", "spec", "in", "self", ".", "_attach_specs", ".", "values", "(", ")", "]" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/autodiff/grad_manager.py#L128-L130
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/rds2/layer1.py
python
RDSConnection.revoke_db_security_group_ingress
(self, db_security_group_name, cidrip=None, ec2_security_group_name=None, ec2_security_group_id=None, ec2_security_group_owner_id=None)
return self._make_request( action='RevokeDBSecurityGroupIngress', verb='POST', path='/', params=params)
Revokes ingress from a DBSecurityGroup for previously authorized IP ranges or EC2 or VPC Security Groups. Required parameters for this API are one of CIDRIP, EC2SecurityGroupId for VPC, or (EC2SecurityGroupOwnerId and either EC2SecurityGroupName or EC2SecurityGroupId). :type db_security_group_name: string :param db_security_group_name: The name of the DB security group to revoke ingress from. :type cidrip: string :param cidrip: The IP range to revoke access from. Must be a valid CIDR range. If `CIDRIP` is specified, `EC2SecurityGroupName`, `EC2SecurityGroupId` and `EC2SecurityGroupOwnerId` cannot be provided. :type ec2_security_group_name: string :param ec2_security_group_name: The name of the EC2 security group to revoke access from. For VPC DB security groups, `EC2SecurityGroupId` must be provided. Otherwise, EC2SecurityGroupOwnerId and either `EC2SecurityGroupName` or `EC2SecurityGroupId` must be provided. :type ec2_security_group_id: string :param ec2_security_group_id: The id of the EC2 security group to revoke access from. For VPC DB security groups, `EC2SecurityGroupId` must be provided. Otherwise, EC2SecurityGroupOwnerId and either `EC2SecurityGroupName` or `EC2SecurityGroupId` must be provided. :type ec2_security_group_owner_id: string :param ec2_security_group_owner_id: The AWS Account Number of the owner of the EC2 security group specified in the `EC2SecurityGroupName` parameter. The AWS Access Key ID is not an acceptable value. For VPC DB security groups, `EC2SecurityGroupId` must be provided. Otherwise, EC2SecurityGroupOwnerId and either `EC2SecurityGroupName` or `EC2SecurityGroupId` must be provided.
Revokes ingress from a DBSecurityGroup for previously authorized IP ranges or EC2 or VPC Security Groups. Required parameters for this API are one of CIDRIP, EC2SecurityGroupId for VPC, or (EC2SecurityGroupOwnerId and either EC2SecurityGroupName or EC2SecurityGroupId).
[ "Revokes", "ingress", "from", "a", "DBSecurityGroup", "for", "previously", "authorized", "IP", "ranges", "or", "EC2", "or", "VPC", "Security", "Groups", ".", "Required", "parameters", "for", "this", "API", "are", "one", "of", "CIDRIP", "EC2SecurityGroupId", "for", "VPC", "or", "(", "EC2SecurityGroupOwnerId", "and", "either", "EC2SecurityGroupName", "or", "EC2SecurityGroupId", ")", "." ]
def revoke_db_security_group_ingress(self, db_security_group_name, cidrip=None, ec2_security_group_name=None, ec2_security_group_id=None, ec2_security_group_owner_id=None): """ Revokes ingress from a DBSecurityGroup for previously authorized IP ranges or EC2 or VPC Security Groups. Required parameters for this API are one of CIDRIP, EC2SecurityGroupId for VPC, or (EC2SecurityGroupOwnerId and either EC2SecurityGroupName or EC2SecurityGroupId). :type db_security_group_name: string :param db_security_group_name: The name of the DB security group to revoke ingress from. :type cidrip: string :param cidrip: The IP range to revoke access from. Must be a valid CIDR range. If `CIDRIP` is specified, `EC2SecurityGroupName`, `EC2SecurityGroupId` and `EC2SecurityGroupOwnerId` cannot be provided. :type ec2_security_group_name: string :param ec2_security_group_name: The name of the EC2 security group to revoke access from. For VPC DB security groups, `EC2SecurityGroupId` must be provided. Otherwise, EC2SecurityGroupOwnerId and either `EC2SecurityGroupName` or `EC2SecurityGroupId` must be provided. :type ec2_security_group_id: string :param ec2_security_group_id: The id of the EC2 security group to revoke access from. For VPC DB security groups, `EC2SecurityGroupId` must be provided. Otherwise, EC2SecurityGroupOwnerId and either `EC2SecurityGroupName` or `EC2SecurityGroupId` must be provided. :type ec2_security_group_owner_id: string :param ec2_security_group_owner_id: The AWS Account Number of the owner of the EC2 security group specified in the `EC2SecurityGroupName` parameter. The AWS Access Key ID is not an acceptable value. For VPC DB security groups, `EC2SecurityGroupId` must be provided. Otherwise, EC2SecurityGroupOwnerId and either `EC2SecurityGroupName` or `EC2SecurityGroupId` must be provided. """ params = {'DBSecurityGroupName': db_security_group_name, } if cidrip is not None: params['CIDRIP'] = cidrip if ec2_security_group_name is not None: params['EC2SecurityGroupName'] = ec2_security_group_name if ec2_security_group_id is not None: params['EC2SecurityGroupId'] = ec2_security_group_id if ec2_security_group_owner_id is not None: params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id return self._make_request( action='RevokeDBSecurityGroupIngress', verb='POST', path='/', params=params)
[ "def", "revoke_db_security_group_ingress", "(", "self", ",", "db_security_group_name", ",", "cidrip", "=", "None", ",", "ec2_security_group_name", "=", "None", ",", "ec2_security_group_id", "=", "None", ",", "ec2_security_group_owner_id", "=", "None", ")", ":", "params", "=", "{", "'DBSecurityGroupName'", ":", "db_security_group_name", ",", "}", "if", "cidrip", "is", "not", "None", ":", "params", "[", "'CIDRIP'", "]", "=", "cidrip", "if", "ec2_security_group_name", "is", "not", "None", ":", "params", "[", "'EC2SecurityGroupName'", "]", "=", "ec2_security_group_name", "if", "ec2_security_group_id", "is", "not", "None", ":", "params", "[", "'EC2SecurityGroupId'", "]", "=", "ec2_security_group_id", "if", "ec2_security_group_owner_id", "is", "not", "None", ":", "params", "[", "'EC2SecurityGroupOwnerId'", "]", "=", "ec2_security_group_owner_id", "return", "self", ".", "_make_request", "(", "action", "=", "'RevokeDBSecurityGroupIngress'", ",", "verb", "=", "'POST'", ",", "path", "=", "'/'", ",", "params", "=", "params", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/rds2/layer1.py#L3698-L3755
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/itanium_mangler.py
python
mangle_args_c
(argtys)
return ''.join([mangle_type_c(t) for t in argtys])
Mangle sequence of C type names
Mangle sequence of C type names
[ "Mangle", "sequence", "of", "C", "type", "names" ]
def mangle_args_c(argtys): """ Mangle sequence of C type names """ return ''.join([mangle_type_c(t) for t in argtys])
[ "def", "mangle_args_c", "(", "argtys", ")", ":", "return", "''", ".", "join", "(", "[", "mangle_type_c", "(", "t", ")", "for", "t", "in", "argtys", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/itanium_mangler.py#L192-L196
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/nn_ops.py
python
conv1d
(value, filters, stride, padding, use_cudnn_on_gpu=None, data_format=None, name=None)
Computes a 1-D convolution given 3-D input and filter tensors. Given an input tensor of shape [batch, in_width, in_channels] and a filter / kernel tensor of shape [filter_width, in_channels, out_channels], this op reshapes the arguments to pass them to conv2d to perform the equivalent convolution operation. Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`. A tensor of shape [batch, in_width, in_channels] is reshaped to [batch, 1, in_width, in_channels], and the filter is reshaped to [1, filter_width, in_channels, out_channels]. The result is then reshaped back to [batch, out_width, out_channels] (where out_width is a function of the stride and padding as in conv2d) and returned to the caller. Args: value: A 3D `Tensor`. Must be of type `float32` or `float64`. filters: A 3D `Tensor`. Must have the same type as `input`. stride: An `integer`. The number of entries by which the filter is moved right at each step. padding: 'SAME' or 'VALID' use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. data_format: An optional `string` from `"NHWC", "NCHW"`. Defaults to `"NHWC"`, the data is stored in the order of [batch, in_width, in_channels]. The `"NCHW"` format stores data as [batch, in_channels, in_width]. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as input.
Computes a 1-D convolution given 3-D input and filter tensors.
[ "Computes", "a", "1", "-", "D", "convolution", "given", "3", "-", "D", "input", "and", "filter", "tensors", "." ]
def conv1d(value, filters, stride, padding, use_cudnn_on_gpu=None, data_format=None, name=None): """Computes a 1-D convolution given 3-D input and filter tensors. Given an input tensor of shape [batch, in_width, in_channels] and a filter / kernel tensor of shape [filter_width, in_channels, out_channels], this op reshapes the arguments to pass them to conv2d to perform the equivalent convolution operation. Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`. A tensor of shape [batch, in_width, in_channels] is reshaped to [batch, 1, in_width, in_channels], and the filter is reshaped to [1, filter_width, in_channels, out_channels]. The result is then reshaped back to [batch, out_width, out_channels] (where out_width is a function of the stride and padding as in conv2d) and returned to the caller. Args: value: A 3D `Tensor`. Must be of type `float32` or `float64`. filters: A 3D `Tensor`. Must have the same type as `input`. stride: An `integer`. The number of entries by which the filter is moved right at each step. padding: 'SAME' or 'VALID' use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. data_format: An optional `string` from `"NHWC", "NCHW"`. Defaults to `"NHWC"`, the data is stored in the order of [batch, in_width, in_channels]. The `"NCHW"` format stores data as [batch, in_channels, in_width]. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as input. """ with ops.name_scope(name, "conv1d", [value, filters]) as name: # Reshape the input tensor to [batch, 1, in_width, in_channels] value = array_ops.expand_dims(value, 1) # And reshape the filter to [1, filter_width, in_channels, out_channels] filters = array_ops.expand_dims(filters, 0) result = gen_nn_ops.conv2d(value, filters, [1, 1, stride, 1], padding, use_cudnn_on_gpu=use_cudnn_on_gpu, data_format=data_format) return array_ops.squeeze(result, [1])
[ "def", "conv1d", "(", "value", ",", "filters", ",", "stride", ",", "padding", ",", "use_cudnn_on_gpu", "=", "None", ",", "data_format", "=", "None", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"conv1d\"", ",", "[", "value", ",", "filters", "]", ")", "as", "name", ":", "# Reshape the input tensor to [batch, 1, in_width, in_channels]", "value", "=", "array_ops", ".", "expand_dims", "(", "value", ",", "1", ")", "# And reshape the filter to [1, filter_width, in_channels, out_channels]", "filters", "=", "array_ops", ".", "expand_dims", "(", "filters", ",", "0", ")", "result", "=", "gen_nn_ops", ".", "conv2d", "(", "value", ",", "filters", ",", "[", "1", ",", "1", ",", "stride", ",", "1", "]", ",", "padding", ",", "use_cudnn_on_gpu", "=", "use_cudnn_on_gpu", ",", "data_format", "=", "data_format", ")", "return", "array_ops", ".", "squeeze", "(", "result", ",", "[", "1", "]", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/nn_ops.py#L1792-L1835
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.push_parameter_definitions
(self, frame)
Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters.
Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters.
[ "Pushes", "all", "parameter", "targets", "from", "the", "given", "frame", "into", "a", "local", "stack", "that", "permits", "tracking", "of", "yet", "to", "be", "assigned", "parameters", ".", "In", "particular", "this", "enables", "the", "optimization", "from", "visit_Name", "to", "skip", "undefined", "expressions", "for", "parameters", "in", "macros", "as", "macros", "can", "reference", "otherwise", "unbound", "parameters", "." ]
def push_parameter_definitions(self, frame): """Pushes all parameter targets from the given frame into a local stack that permits tracking of yet to be assigned parameters. In particular this enables the optimization from `visit_Name` to skip undefined expressions for parameters in macros as macros can reference otherwise unbound parameters. """ self._param_def_block.append(frame.symbols.dump_param_targets())
[ "def", "push_parameter_definitions", "(", "self", ",", "frame", ")", ":", "self", ".", "_param_def_block", ".", "append", "(", "frame", ".", "symbols", ".", "dump_param_targets", "(", ")", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/compiler.py#L614-L621
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py
python
ParseBaseException.__getattr__
( self, aname )
supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text
supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text
[ "supported", "attributes", "by", "name", "are", ":", "-", "lineno", "-", "returns", "the", "line", "number", "of", "the", "exception", "text", "-", "col", "-", "returns", "the", "column", "number", "of", "the", "exception", "text", "-", "line", "-", "returns", "the", "line", "containing", "the", "exception", "text" ]
def __getattr__( self, aname ): """supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text """ if( aname == "lineno" ): return lineno( self.loc, self.pstr ) elif( aname in ("col", "column") ): return col( self.loc, self.pstr ) elif( aname == "line" ): return line( self.loc, self.pstr ) else: raise AttributeError(aname)
[ "def", "__getattr__", "(", "self", ",", "aname", ")", ":", "if", "(", "aname", "==", "\"lineno\"", ")", ":", "return", "lineno", "(", "self", ".", "loc", ",", "self", ".", "pstr", ")", "elif", "(", "aname", "in", "(", "\"col\"", ",", "\"column\"", ")", ")", ":", "return", "col", "(", "self", ".", "loc", ",", "self", ".", "pstr", ")", "elif", "(", "aname", "==", "\"line\"", ")", ":", "return", "line", "(", "self", ".", "loc", ",", "self", ".", "pstr", ")", "else", ":", "raise", "AttributeError", "(", "aname", ")" ]
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/pyparsing.py#L259-L272
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/default_settings.py
python
_validate_incredibuild_registry_settings
(ctx)
Helper function to verify the correct incredibuild settings
Helper function to verify the correct incredibuild settings
[ "Helper", "function", "to", "verify", "the", "correct", "incredibuild", "settings" ]
def _validate_incredibuild_registry_settings(ctx): """ Helper function to verify the correct incredibuild settings """ if Utils.unversioned_sys_platform() != 'win32': return # Check windows registry only if not ctx.is_option_true('use_incredibuild'): return # No need to check IB settings if there is no IB allowUserInput = True if not ctx.is_option_true('ask_for_user_input'): allowUserInput = False if Options.options.execsolution: allowUserInput = False if ctx.is_option_true('internal_dont_check_recursive_execution'): allowUserInput = False try: import _winreg IB_settings_read_only = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder", 0, _winreg.KEY_READ) except: Logs.warn('[WARNING] Cannot open registry entry "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder" for reading, please check your incredibuild installation') return def _check_ib_setting(setting_name, required_value, desc): """ Helper function to read (and potentially modify a registry setting for IB """ (data, type) = (None, _winreg.REG_SZ) try: (data,type) = _winreg.QueryValueEx(IB_settings_read_only, setting_name) except: import traceback traceback.print_exc(file=sys.stdout) Logs.warn('[WARNING] Cannot find a registry entry for "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder\\%s"' % setting_name ) # Do we have the right value? if str(data) != required_value: if not allowUserInput: # Dont try anything if no input is allowed Logs.warn('[WARNING] "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder\\%s" set to "%s" but should be "%s"; run WAF outside of Visual Studio to fix automatically' % (setting_name, data, required_value) ) return try: # Try to open the registry for writing IB_settings_writing = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder", 0, _winreg.KEY_SET_VALUE | _winreg.KEY_READ) except: Logs.warn('[WARNING] Cannot access a registry entry "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder\\%s" for writing.' % setting_name) Logs.warn('[WARNING] Please run cry_waf.exe as an administrator or change the value to "%s" in the registry to ensure a correct operation of WAF' % required_value) return if data is None: info_str = [('Should WAF create "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder\\%s" with value "%s"?' % (setting_name, required_value) )] else: info_str = [('Should WAF change "HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Xoreax\\Incredibuild\\Builder\\%s" from "%s" to "%s"?' % (setting_name, data, required_value) )] info_str.append(desc) # Get user choice if not ctx.is_option_true('console_mode'): # gui retVal = 'True' if ctx.gui_get_choice('\n'.join(info_str)) else 'False' else: # console Logs.info('\n'.join(info_str)) retVal = _get_boolean_value(ctx, 'Input', 'Yes') if retVal == 'True' or retVal == 'Yes': _winreg.SetValueEx(IB_settings_writing, setting_name,0, type, str(required_value)) else: Logs.warn('[WARNING] WAF is running with "unsupported" IncrediBuild settings. Expect to encounter IncrediBuild errors during compilation.') _check_ib_setting('MaxConcurrentPDBs', '0', '"MaxConcurrentPDBs" controls how many files can be processed in parallel (an optimization also useful for MSBuild)') _check_ib_setting('AllowDoubleTargets', '0', '"AllowDoubleTargets" controls if remote processes can be restarted on local machine when possible\nThis option is mandatory since it causes compiler crashed with WAF')
[ "def", "_validate_incredibuild_registry_settings", "(", "ctx", ")", ":", "if", "Utils", ".", "unversioned_sys_platform", "(", ")", "!=", "'win32'", ":", "return", "# Check windows registry only", "if", "not", "ctx", ".", "is_option_true", "(", "'use_incredibuild'", ")", ":", "return", "# No need to check IB settings if there is no IB", "allowUserInput", "=", "True", "if", "not", "ctx", ".", "is_option_true", "(", "'ask_for_user_input'", ")", ":", "allowUserInput", "=", "False", "if", "Options", ".", "options", ".", "execsolution", ":", "allowUserInput", "=", "False", "if", "ctx", ".", "is_option_true", "(", "'internal_dont_check_recursive_execution'", ")", ":", "allowUserInput", "=", "False", "try", ":", "import", "_winreg", "IB_settings_read_only", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_LOCAL_MACHINE", ",", "\"Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\"", ",", "0", ",", "_winreg", ".", "KEY_READ", ")", "except", ":", "Logs", ".", "warn", "(", "'[WARNING] Cannot open registry entry \"HKEY_LOCAL_MACHINE\\\\Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\" for reading, please check your incredibuild installation'", ")", "return", "def", "_check_ib_setting", "(", "setting_name", ",", "required_value", ",", "desc", ")", ":", "\"\"\" Helper function to read (and potentially modify a registry setting for IB \"\"\"", "(", "data", ",", "type", ")", "=", "(", "None", ",", "_winreg", ".", "REG_SZ", ")", "try", ":", "(", "data", ",", "type", ")", "=", "_winreg", ".", "QueryValueEx", "(", "IB_settings_read_only", ",", "setting_name", ")", "except", ":", "import", "traceback", "traceback", ".", "print_exc", "(", "file", "=", "sys", ".", "stdout", ")", "Logs", ".", "warn", "(", "'[WARNING] Cannot find a registry entry for \"HKEY_LOCAL_MACHINE\\\\Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\\\\%s\"'", "%", "setting_name", ")", "# Do we have the right value?", "if", "str", "(", "data", ")", "!=", "required_value", ":", "if", "not", "allowUserInput", ":", "# Dont try anything if no input is allowed", "Logs", ".", "warn", "(", "'[WARNING] \"HKEY_LOCAL_MACHINE\\\\Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\\\\%s\" set to \"%s\" but should be \"%s\"; run WAF outside of Visual Studio to fix automatically'", "%", "(", "setting_name", ",", "data", ",", "required_value", ")", ")", "return", "try", ":", "# Try to open the registry for writing", "IB_settings_writing", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_LOCAL_MACHINE", ",", "\"Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\"", ",", "0", ",", "_winreg", ".", "KEY_SET_VALUE", "|", "_winreg", ".", "KEY_READ", ")", "except", ":", "Logs", ".", "warn", "(", "'[WARNING] Cannot access a registry entry \"HKEY_LOCAL_MACHINE\\\\Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\\\\%s\" for writing.'", "%", "setting_name", ")", "Logs", ".", "warn", "(", "'[WARNING] Please run cry_waf.exe as an administrator or change the value to \"%s\" in the registry to ensure a correct operation of WAF'", "%", "required_value", ")", "return", "if", "data", "is", "None", ":", "info_str", "=", "[", "(", "'Should WAF create \"HKEY_LOCAL_MACHINE\\\\Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\\\\%s\" with value \"%s\"?'", "%", "(", "setting_name", ",", "required_value", ")", ")", "]", "else", ":", "info_str", "=", "[", "(", "'Should WAF change \"HKEY_LOCAL_MACHINE\\\\Software\\\\Wow6432Node\\\\Xoreax\\\\Incredibuild\\\\Builder\\\\%s\" from \"%s\" to \"%s\"?'", "%", "(", "setting_name", ",", "data", ",", "required_value", ")", ")", "]", "info_str", ".", "append", "(", "desc", ")", "# Get user choice", "if", "not", "ctx", ".", "is_option_true", "(", "'console_mode'", ")", ":", "# gui", "retVal", "=", "'True'", "if", "ctx", ".", "gui_get_choice", "(", "'\\n'", ".", "join", "(", "info_str", ")", ")", "else", "'False'", "else", ":", "# console", "Logs", ".", "info", "(", "'\\n'", ".", "join", "(", "info_str", ")", ")", "retVal", "=", "_get_boolean_value", "(", "ctx", ",", "'Input'", ",", "'Yes'", ")", "if", "retVal", "==", "'True'", "or", "retVal", "==", "'Yes'", ":", "_winreg", ".", "SetValueEx", "(", "IB_settings_writing", ",", "setting_name", ",", "0", ",", "type", ",", "str", "(", "required_value", ")", ")", "else", ":", "Logs", ".", "warn", "(", "'[WARNING] WAF is running with \"unsupported\" IncrediBuild settings. Expect to encounter IncrediBuild errors during compilation.'", ")", "_check_ib_setting", "(", "'MaxConcurrentPDBs'", ",", "'0'", ",", "'\"MaxConcurrentPDBs\" controls how many files can be processed in parallel (an optimization also useful for MSBuild)'", ")", "_check_ib_setting", "(", "'AllowDoubleTargets'", ",", "'0'", ",", "'\"AllowDoubleTargets\" controls if remote processes can be restarted on local machine when possible\\nThis option is mandatory since it causes compiler crashed with WAF'", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/default_settings.py#L130-L198
wenwei202/caffe
f54a74abaf6951d8485cbdcfa1d74a4c37839466
scripts/cpp_lint.py
python
_CppLintState.PrintErrorCounts
(self)
Print a summary of errors by category, and the total.
Print a summary of errors by category, and the total.
[ "Print", "a", "summary", "of", "errors", "by", "category", "and", "the", "total", "." ]
def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count)
[ "def", "PrintErrorCounts", "(", "self", ")", ":", "for", "category", ",", "count", "in", "self", ".", "errors_by_category", ".", "iteritems", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Category \\'%s\\' errors found: %d\\n'", "%", "(", "category", ",", "count", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'Total errors found: %d\\n'", "%", "self", ".", "error_count", ")" ]
https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/scripts/cpp_lint.py#L757-L762
junhyukoh/caffe-lstm
598d45456fa2a1b127a644f4aa38daa8fb9fc722
scripts/cpp_lint.py
python
CheckCStyleCast
(filename, linenum, line, raw_line, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ match = Search(pattern, line) if not match: return False # Exclude lines with sizeof, since sizeof looks like a cast. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) if sizeof_match: return False # operator++(int) and operator--(int) if (line[0:match.start(1) - 1].endswith(' operator++') or line[0:match.start(1) - 1].endswith(' operator--')): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "linenum", ",", "line", ",", "raw_line", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "# Exclude lines with sizeof, since sizeof looks like a cast.", "sizeof_match", "=", "Match", "(", "r'.*sizeof\\s*$'", ",", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ")", "if", "sizeof_match", ":", "return", "False", "# operator++(int) and operator--(int)", "if", "(", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ".", "endswith", "(", "' operator++'", ")", "or", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", ".", "endswith", "(", "' operator--'", ")", ")", ":", "return", "False", "# A single unnamed argument for a function tends to look like old", "# style cast. If we see those, don't issue warnings for deprecated", "# casts, instead issue warnings for unnamed arguments where", "# appropriate.", "#", "# These are things that we want warnings for, since the style guide", "# explicitly require all parameters to be named:", "# Function(int);", "# Function(int) {", "# ConstMember(int) const;", "# ConstMember(int) const {", "# ExceptionMember(int) throw (...);", "# ExceptionMember(int) throw (...) {", "# PureVirtual(int) = 0;", "#", "# These are functions of some sort, where the compiler would be fine", "# if they had named parameters, but people often omit those", "# identifiers to reduce clutter:", "# (FunctionPointer)(int);", "# (FunctionPointer)(int) = value;", "# Function((function_pointer_arg)(int))", "# <TemplateArgument(int)>;", "# <(FunctionPointerTemplateArgument)(int)>;", "remainder", "=", "line", "[", "match", ".", "end", "(", "0", ")", ":", "]", "if", "Match", "(", "r'^\\s*(?:;|const\\b|throw\\b|=|>|\\{|\\))'", ",", "remainder", ")", ":", "# Looks like an unnamed parameter.", "# Don't warn on any kind of template arguments.", "if", "Match", "(", "r'^\\s*>'", ",", "remainder", ")", ":", "return", "False", "# Don't warn on assignments to function pointers, but keep warnings for", "# unnamed parameters to pure virtual functions. Note that this pattern", "# will also pass on assignments of \"0\" to function pointers, but the", "# preferred values for those would be \"nullptr\" or \"NULL\".", "matched_zero", "=", "Match", "(", "r'^\\s=\\s*(\\S+)\\s*;'", ",", "remainder", ")", "if", "matched_zero", "and", "matched_zero", ".", "group", "(", "1", ")", "!=", "'0'", ":", "return", "False", "# Don't warn on function pointer declarations. For this we need", "# to check what came before the \"(type)\" string.", "if", "Match", "(", "r'.*\\)\\s*$'", ",", "line", "[", "0", ":", "match", ".", "start", "(", "0", ")", "]", ")", ":", "return", "False", "# Don't warn if the parameter is named with block comments, e.g.:", "# Function(int /*unused_param*/);", "if", "'/*'", "in", "raw_line", ":", "return", "False", "# Passed all filters, issue warning here.", "error", "(", "filename", ",", "linenum", ",", "'readability/function'", ",", "3", ",", "'All parameters should be named in a function'", ")", "return", "True", "# At this point, all that should be left is actual casts.", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using C-style cast. Use %s<%s>(...) instead'", "%", "(", "cast_type", ",", "match", ".", "group", "(", "1", ")", ")", ")", "return", "True" ]
https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L4247-L4338
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
build/automationutils.py
python
dumpScreen
(utilityPath)
dumps a screenshot of the entire screen to a directory specified by the MOZ_UPLOAD_DIR environment variable
dumps a screenshot of the entire screen to a directory specified by the MOZ_UPLOAD_DIR environment variable
[ "dumps", "a", "screenshot", "of", "the", "entire", "screen", "to", "a", "directory", "specified", "by", "the", "MOZ_UPLOAD_DIR", "environment", "variable" ]
def dumpScreen(utilityPath): """dumps a screenshot of the entire screen to a directory specified by the MOZ_UPLOAD_DIR environment variable""" # Need to figure out which OS-dependent tool to use if mozinfo.isUnix: utility = [os.path.join(utilityPath, "screentopng")] utilityname = "screentopng" elif mozinfo.isMac: utility = ['/usr/sbin/screencapture', '-C', '-x', '-t', 'png'] utilityname = "screencapture" elif mozinfo.isWin: utility = [os.path.join(utilityPath, "screenshot.exe")] utilityname = "screenshot" # Get dir where to write the screenshot file parent_dir = os.environ.get('MOZ_UPLOAD_DIR', None) if not parent_dir: log.info('Failed to retrieve MOZ_UPLOAD_DIR env var') return # Run the capture try: tmpfd, imgfilename = tempfile.mkstemp(prefix='mozilla-test-fail-screenshot_', suffix='.png', dir=parent_dir) os.close(tmpfd) returncode = subprocess.call(utility + [imgfilename]) printstatus(returncode, utilityname) except OSError, err: log.info("Failed to start %s for screenshot: %s" % utility[0], err.strerror) return
[ "def", "dumpScreen", "(", "utilityPath", ")", ":", "# Need to figure out which OS-dependent tool to use", "if", "mozinfo", ".", "isUnix", ":", "utility", "=", "[", "os", ".", "path", ".", "join", "(", "utilityPath", ",", "\"screentopng\"", ")", "]", "utilityname", "=", "\"screentopng\"", "elif", "mozinfo", ".", "isMac", ":", "utility", "=", "[", "'/usr/sbin/screencapture'", ",", "'-C'", ",", "'-x'", ",", "'-t'", ",", "'png'", "]", "utilityname", "=", "\"screencapture\"", "elif", "mozinfo", ".", "isWin", ":", "utility", "=", "[", "os", ".", "path", ".", "join", "(", "utilityPath", ",", "\"screenshot.exe\"", ")", "]", "utilityname", "=", "\"screenshot\"", "# Get dir where to write the screenshot file", "parent_dir", "=", "os", ".", "environ", ".", "get", "(", "'MOZ_UPLOAD_DIR'", ",", "None", ")", "if", "not", "parent_dir", ":", "log", ".", "info", "(", "'Failed to retrieve MOZ_UPLOAD_DIR env var'", ")", "return", "# Run the capture", "try", ":", "tmpfd", ",", "imgfilename", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "'mozilla-test-fail-screenshot_'", ",", "suffix", "=", "'.png'", ",", "dir", "=", "parent_dir", ")", "os", ".", "close", "(", "tmpfd", ")", "returncode", "=", "subprocess", ".", "call", "(", "utility", "+", "[", "imgfilename", "]", ")", "printstatus", "(", "returncode", ",", "utilityname", ")", "except", "OSError", ",", "err", ":", "log", ".", "info", "(", "\"Failed to start %s for screenshot: %s\"", "%", "utility", "[", "0", "]", ",", "err", ".", "strerror", ")", "return" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/build/automationutils.py#L459-L489
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/plan/motionplanning.py
python
CSpaceInterface.setFeasibility
(self, pyFeas)
return _motionplanning.CSpaceInterface_setFeasibility(self, pyFeas)
Args: pyFeas (:obj:`object`)
Args: pyFeas (:obj:`object`)
[ "Args", ":", "pyFeas", "(", ":", "obj", ":", "object", ")" ]
def setFeasibility(self, pyFeas): """ Args: pyFeas (:obj:`object`) """ return _motionplanning.CSpaceInterface_setFeasibility(self, pyFeas)
[ "def", "setFeasibility", "(", "self", ",", "pyFeas", ")", ":", "return", "_motionplanning", ".", "CSpaceInterface_setFeasibility", "(", "self", ",", "pyFeas", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/motionplanning.py#L325-L330
AngoraFuzzer/Angora
80e81c8590077bc0ac069dbd367da8ce405ff618
llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py
python
CleansedLines.NumLines
(self)
return self.num_lines
Returns the number of lines represented.
Returns the number of lines represented.
[ "Returns", "the", "number", "of", "lines", "represented", "." ]
def NumLines(self): """Returns the number of lines represented.""" return self.num_lines
[ "def", "NumLines", "(", "self", ")", ":", "return", "self", ".", "num_lines" ]
https://github.com/AngoraFuzzer/Angora/blob/80e81c8590077bc0ac069dbd367da8ce405ff618/llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py#L1005-L1007
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
Sound.IsOk
(*args, **kwargs)
return _misc_.Sound_IsOk(*args, **kwargs)
IsOk(self) -> bool
IsOk(self) -> bool
[ "IsOk", "(", "self", ")", "-", ">", "bool" ]
def IsOk(*args, **kwargs): """IsOk(self) -> bool""" return _misc_.Sound_IsOk(*args, **kwargs)
[ "def", "IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Sound_IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2453-L2455
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextCtrl.GetScaleX
(*args, **kwargs)
return _richtext.RichTextCtrl_GetScaleX(*args, **kwargs)
GetScaleX(self) -> double
GetScaleX(self) -> double
[ "GetScaleX", "(", "self", ")", "-", ">", "double" ]
def GetScaleX(*args, **kwargs): """GetScaleX(self) -> double""" return _richtext.RichTextCtrl_GetScaleX(*args, **kwargs)
[ "def", "GetScaleX", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_GetScaleX", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L4168-L4170
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py
python
Standard_Suite_Events.exists
(self, _object, _attributes={}, **_arguments)
exists: Verify if an object exists. Required argument: the object for the command Keyword argument _attributes: AppleEvent attribute dictionary Returns: the reply for the command
exists: Verify if an object exists. Required argument: the object for the command Keyword argument _attributes: AppleEvent attribute dictionary Returns: the reply for the command
[ "exists", ":", "Verify", "if", "an", "object", "exists", ".", "Required", "argument", ":", "the", "object", "for", "the", "command", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "the", "reply", "for", "the", "command" ]
def exists(self, _object, _attributes={}, **_arguments): """exists: Verify if an object exists. Required argument: the object for the command Keyword argument _attributes: AppleEvent attribute dictionary Returns: the reply for the command """ _code = 'core' _subcode = 'doex' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "exists", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'doex'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py#L116-L135
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/twitter.py
python
DirectMessage.SetRecipientId
(self, recipient_id)
Set the unique recipient id of this direct message. Args: recipient id: The unique recipient id of this direct message
Set the unique recipient id of this direct message.
[ "Set", "the", "unique", "recipient", "id", "of", "this", "direct", "message", "." ]
def SetRecipientId(self, recipient_id): '''Set the unique recipient id of this direct message. Args: recipient id: The unique recipient id of this direct message ''' self._recipient_id = recipient_id
[ "def", "SetRecipientId", "(", "self", ",", "recipient_id", ")", ":", "self", ".", "_recipient_id", "=", "recipient_id" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/twitter.py#L699-L705
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/configobj/validate.py
python
_is_num_param
(names, values, to_float=False)
return out_params
Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. >>> _is_num_param(('', ''), (0, 1.0)) [0, 1] >>> _is_num_param(('', ''), (0, 1.0), to_float=True) [0.0, 1.0] >>> _is_num_param(('a'), ('a')) Traceback (most recent call last): VdtParamError: passed an incorrect value "a" for parameter "a".
Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. >>> _is_num_param(('', ''), (0, 1.0)) [0, 1] >>> _is_num_param(('', ''), (0, 1.0), to_float=True) [0.0, 1.0] >>> _is_num_param(('a'), ('a')) Traceback (most recent call last): VdtParamError: passed an incorrect value "a" for parameter "a".
[ "Return", "numbers", "from", "inputs", "or", "raise", "VdtParamError", ".", "Lets", "None", "pass", "through", ".", "Pass", "in", "keyword", "argument", "to_float", "=", "True", "to", "use", "float", "for", "the", "conversion", "rather", "than", "int", ".", ">>>", "_is_num_param", "((", ")", "(", "0", "1", ".", "0", "))", "[", "0", "1", "]", ">>>", "_is_num_param", "((", ")", "(", "0", "1", ".", "0", ")", "to_float", "=", "True", ")", "[", "0", ".", "0", "1", ".", "0", "]", ">>>", "_is_num_param", "((", "a", ")", "(", "a", "))", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "VdtParamError", ":", "passed", "an", "incorrect", "value", "a", "for", "parameter", "a", "." ]
def _is_num_param(names, values, to_float=False): """ Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. >>> _is_num_param(('', ''), (0, 1.0)) [0, 1] >>> _is_num_param(('', ''), (0, 1.0), to_float=True) [0.0, 1.0] >>> _is_num_param(('a'), ('a')) Traceback (most recent call last): VdtParamError: passed an incorrect value "a" for parameter "a". """ fun = to_float and float or int out_params = [] for (name, val) in zip(names, values): if val is None: out_params.append(val) elif isinstance(val, (int, long, float, basestring)): try: out_params.append(fun(val)) except ValueError, e: raise VdtParamError(name, val) else: raise VdtParamError(name, val) return out_params
[ "def", "_is_num_param", "(", "names", ",", "values", ",", "to_float", "=", "False", ")", ":", "fun", "=", "to_float", "and", "float", "or", "int", "out_params", "=", "[", "]", "for", "(", "name", ",", "val", ")", "in", "zip", "(", "names", ",", "values", ")", ":", "if", "val", "is", "None", ":", "out_params", ".", "append", "(", "val", ")", "elif", "isinstance", "(", "val", ",", "(", "int", ",", "long", ",", "float", ",", "basestring", ")", ")", ":", "try", ":", "out_params", ".", "append", "(", "fun", "(", "val", ")", ")", "except", "ValueError", ",", "e", ":", "raise", "VdtParamError", "(", "name", ",", "val", ")", "else", ":", "raise", "VdtParamError", "(", "name", ",", "val", ")", "return", "out_params" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/configobj/validate.py#L718-L746
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/calendar.py
python
CalendarEvent.__init__
(self, *args, **kwargs)
__init__(self, Window win, DateTime dt, EventType type) -> CalendarEvent
__init__(self, Window win, DateTime dt, EventType type) -> CalendarEvent
[ "__init__", "(", "self", "Window", "win", "DateTime", "dt", "EventType", "type", ")", "-", ">", "CalendarEvent" ]
def __init__(self, *args, **kwargs): """__init__(self, Window win, DateTime dt, EventType type) -> CalendarEvent""" _calendar.CalendarEvent_swiginit(self,_calendar.new_CalendarEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_calendar", ".", "CalendarEvent_swiginit", "(", "self", ",", "_calendar", ".", "new_CalendarEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/calendar.py#L195-L197
mickem/nscp
79f89fdbb6da63f91bc9dedb7aea202fe938f237
scripts/python/lib/google/protobuf/internal/python_message.py
python
_AddEnumValues
(descriptor, cls)
Sets class-level attributes for all enum fields defined in this message. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type.
Sets class-level attributes for all enum fields defined in this message.
[ "Sets", "class", "-", "level", "attributes", "for", "all", "enum", "fields", "defined", "in", "this", "message", "." ]
def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. """ for enum_type in descriptor.enum_types: for enum_value in enum_type.values: setattr(cls, enum_value.name, enum_value.number)
[ "def", "_AddEnumValues", "(", "descriptor", ",", "cls", ")", ":", "for", "enum_type", "in", "descriptor", ".", "enum_types", ":", "for", "enum_value", "in", "enum_type", ".", "values", ":", "setattr", "(", "cls", ",", "enum_value", ".", "name", ",", "enum_value", ".", "number", ")" ]
https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/python_message.py#L224-L233
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
libraries/AP_HAL_ChibiOS/hwdef/scripts/dma_resolver.py
python
sharing_allowed
(p1, p2)
return True
return true if sharing is allowed between p1 and p2
return true if sharing is allowed between p1 and p2
[ "return", "true", "if", "sharing", "is", "allowed", "between", "p1", "and", "p2" ]
def sharing_allowed(p1, p2): '''return true if sharing is allowed between p1 and p2''' if p1 == p2: return True # don't allow RX and TX of same peripheral to share if p1.endswith('_RX') and p2.endswith('_TX') and p1[:-2] == p2[:-2]: return False # don't allow sharing of two TIMn_UP channels as DShot code can't cope if p1.endswith("_UP") and p2.endswith("_UP") and p1.startswith("TIM") and p2.startswith("TIM"): return False return True
[ "def", "sharing_allowed", "(", "p1", ",", "p2", ")", ":", "if", "p1", "==", "p2", ":", "return", "True", "# don't allow RX and TX of same peripheral to share", "if", "p1", ".", "endswith", "(", "'_RX'", ")", "and", "p2", ".", "endswith", "(", "'_TX'", ")", "and", "p1", "[", ":", "-", "2", "]", "==", "p2", "[", ":", "-", "2", "]", ":", "return", "False", "# don't allow sharing of two TIMn_UP channels as DShot code can't cope", "if", "p1", ".", "endswith", "(", "\"_UP\"", ")", "and", "p2", ".", "endswith", "(", "\"_UP\"", ")", "and", "p1", ".", "startswith", "(", "\"TIM\"", ")", "and", "p2", ".", "startswith", "(", "\"TIM\"", ")", ":", "return", "False", "return", "True" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/AP_HAL_ChibiOS/hwdef/scripts/dma_resolver.py#L254-L264
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/mimetypes.py
python
MimeTypes.guess_all_extensions
(self, type, strict=True)
return extensions
Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
Guess the extensions for a file based on its MIME type.
[ "Guess", "the", "extensions", "for", "a", "file", "based", "on", "its", "MIME", "type", "." ]
def guess_all_extensions(self, type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ type = type.lower() extensions = self.types_map_inv[True].get(type, []) if not strict: for ext in self.types_map_inv[False].get(type, []): if ext not in extensions: extensions.append(ext) return extensions
[ "def", "guess_all_extensions", "(", "self", ",", "type", ",", "strict", "=", "True", ")", ":", "type", "=", "type", ".", "lower", "(", ")", "extensions", "=", "self", ".", "types_map_inv", "[", "True", "]", ".", "get", "(", "type", ",", "[", "]", ")", "if", "not", "strict", ":", "for", "ext", "in", "self", ".", "types_map_inv", "[", "False", "]", ".", "get", "(", "type", ",", "[", "]", ")", ":", "if", "ext", "not", "in", "extensions", ":", "extensions", ".", "append", "(", "ext", ")", "return", "extensions" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mimetypes.py#L151-L168
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/ConfigSet.py
python
ConfigSet.stash
(self)
Stores the object state to provide transactionality semantics:: env = ConfigSet() env.stash() try: env.append_value('CFLAGS', '-O3') call_some_method(env) finally: env.revert() The history is kept in a stack, and is lost during the serialization by :py:meth:`ConfigSet.store`
Stores the object state to provide transactionality semantics::
[ "Stores", "the", "object", "state", "to", "provide", "transactionality", "semantics", "::" ]
def stash(self): """ Stores the object state to provide transactionality semantics:: env = ConfigSet() env.stash() try: env.append_value('CFLAGS', '-O3') call_some_method(env) finally: env.revert() The history is kept in a stack, and is lost during the serialization by :py:meth:`ConfigSet.store` """ orig = self.table tbl = self.table = self.table.copy() for x in tbl.keys(): tbl[x] = copy.deepcopy(tbl[x]) self.undo_stack = self.undo_stack + [orig]
[ "def", "stash", "(", "self", ")", ":", "orig", "=", "self", ".", "table", "tbl", "=", "self", ".", "table", "=", "self", ".", "table", ".", "copy", "(", ")", "for", "x", "in", "tbl", ".", "keys", "(", ")", ":", "tbl", "[", "x", "]", "=", "copy", ".", "deepcopy", "(", "tbl", "[", "x", "]", ")", "self", ".", "undo_stack", "=", "self", ".", "undo_stack", "+", "[", "orig", "]" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/ConfigSet.py#L330-L348
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/re2/lib/codereview/codereview.py
python
undo
(ui, repo, clname, **opts)
return clpatch_or_undo(ui, repo, clname, opts, mode="undo")
undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description.
undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description.
[ "undo", "the", "effect", "of", "a", "CL", "Creates", "a", "new", "CL", "that", "undoes", "an", "earlier", "CL", ".", "After", "creating", "the", "CL", "opens", "the", "CL", "text", "for", "editing", "so", "that", "you", "can", "add", "the", "reason", "for", "the", "undo", "to", "the", "description", "." ]
def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. """ if repo[None].branch() != "default": return "cannot run hg undo outside default branch" return clpatch_or_undo(ui, repo, clname, opts, mode="undo")
[ "def", "undo", "(", "ui", ",", "repo", ",", "clname", ",", "*", "*", "opts", ")", ":", "if", "repo", "[", "None", "]", ".", "branch", "(", ")", "!=", "\"default\"", ":", "return", "\"cannot run hg undo outside default branch\"", "return", "clpatch_or_undo", "(", "ui", ",", "repo", ",", "clname", ",", "opts", ",", "mode", "=", "\"undo\"", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/re2/lib/codereview/codereview.py#L1418-L1427
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
llvm/utils/lit/lit/Util.py
python
executeCommand
(command, cwd=None, env=None, input=None, timeout=0)
return out, err, exitCode
Execute command ``command`` (list of arguments or string) with. * working directory ``cwd`` (str), use None to use the current working directory * environment ``env`` (dict), use None for none * Input to the command ``input`` (str), use string to pass no input. * Max execution time ``timeout`` (int) seconds. Use 0 for no timeout. Returns a tuple (out, err, exitCode) where * ``out`` (str) is the standard output of running the command * ``err`` (str) is the standard error of running the command * ``exitCode`` (int) is the exitCode of running the command If the timeout is hit an ``ExecuteCommandTimeoutException`` is raised.
Execute command ``command`` (list of arguments or string) with.
[ "Execute", "command", "command", "(", "list", "of", "arguments", "or", "string", ")", "with", "." ]
def executeCommand(command, cwd=None, env=None, input=None, timeout=0): """Execute command ``command`` (list of arguments or string) with. * working directory ``cwd`` (str), use None to use the current working directory * environment ``env`` (dict), use None for none * Input to the command ``input`` (str), use string to pass no input. * Max execution time ``timeout`` (int) seconds. Use 0 for no timeout. Returns a tuple (out, err, exitCode) where * ``out`` (str) is the standard output of running the command * ``err`` (str) is the standard error of running the command * ``exitCode`` (int) is the exitCode of running the command If the timeout is hit an ``ExecuteCommandTimeoutException`` is raised. """ if input is not None: input = to_bytes(input) p = subprocess.Popen(command, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, close_fds=kUseCloseFDs) timerObject = None # FIXME: Because of the way nested function scopes work in Python 2.x we # need to use a reference to a mutable object rather than a plain # bool. In Python 3 we could use the "nonlocal" keyword but we need # to support Python 2 as well. hitTimeOut = [False] try: if timeout > 0: def killProcess(): # We may be invoking a shell so we need to kill the # process and all its children. hitTimeOut[0] = True killProcessAndChildren(p.pid) timerObject = threading.Timer(timeout, killProcess) timerObject.start() out, err = p.communicate(input=input) exitCode = p.wait() finally: if timerObject != None: timerObject.cancel() # Ensure the resulting output is always of string type. out = to_string(out) err = to_string(err) if hitTimeOut[0]: raise ExecuteCommandTimeoutException( msg='Reached timeout of {} seconds'.format(timeout), out=out, err=err, exitCode=exitCode ) # Detect Ctrl-C in subprocess. if exitCode == -signal.SIGINT: raise KeyboardInterrupt return out, err, exitCode
[ "def", "executeCommand", "(", "command", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "input", "=", "None", ",", "timeout", "=", "0", ")", ":", "if", "input", "is", "not", "None", ":", "input", "=", "to_bytes", "(", "input", ")", "p", "=", "subprocess", ".", "Popen", "(", "command", ",", "cwd", "=", "cwd", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "env", "=", "env", ",", "close_fds", "=", "kUseCloseFDs", ")", "timerObject", "=", "None", "# FIXME: Because of the way nested function scopes work in Python 2.x we", "# need to use a reference to a mutable object rather than a plain", "# bool. In Python 3 we could use the \"nonlocal\" keyword but we need", "# to support Python 2 as well.", "hitTimeOut", "=", "[", "False", "]", "try", ":", "if", "timeout", ">", "0", ":", "def", "killProcess", "(", ")", ":", "# We may be invoking a shell so we need to kill the", "# process and all its children.", "hitTimeOut", "[", "0", "]", "=", "True", "killProcessAndChildren", "(", "p", ".", "pid", ")", "timerObject", "=", "threading", ".", "Timer", "(", "timeout", ",", "killProcess", ")", "timerObject", ".", "start", "(", ")", "out", ",", "err", "=", "p", ".", "communicate", "(", "input", "=", "input", ")", "exitCode", "=", "p", ".", "wait", "(", ")", "finally", ":", "if", "timerObject", "!=", "None", ":", "timerObject", ".", "cancel", "(", ")", "# Ensure the resulting output is always of string type.", "out", "=", "to_string", "(", "out", ")", "err", "=", "to_string", "(", "err", ")", "if", "hitTimeOut", "[", "0", "]", ":", "raise", "ExecuteCommandTimeoutException", "(", "msg", "=", "'Reached timeout of {} seconds'", ".", "format", "(", "timeout", ")", ",", "out", "=", "out", ",", "err", "=", "err", ",", "exitCode", "=", "exitCode", ")", "# Detect Ctrl-C in subprocess.", "if", "exitCode", "==", "-", "signal", ".", "SIGINT", ":", "raise", "KeyboardInterrupt", "return", "out", ",", "err", ",", "exitCode" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/utils/lit/lit/Util.py#L332-L397
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/interpreter.py
python
InterpreterAlaCarte.__init__
(self, locals, rawin, stdin, stdout, stderr, ps1='main prompt', ps2='continuation prompt')
Create an interactive interpreter object.
Create an interactive interpreter object.
[ "Create", "an", "interactive", "interpreter", "object", "." ]
def __init__(self, locals, rawin, stdin, stdout, stderr, ps1='main prompt', ps2='continuation prompt'): """Create an interactive interpreter object.""" Interpreter.__init__(self, locals=locals, rawin=rawin, stdin=stdin, stdout=stdout, stderr=stderr) sys.ps1 = ps1 sys.ps2 = ps2
[ "def", "__init__", "(", "self", ",", "locals", ",", "rawin", ",", "stdin", ",", "stdout", ",", "stderr", ",", "ps1", "=", "'main prompt'", ",", "ps2", "=", "'continuation prompt'", ")", ":", "Interpreter", ".", "__init__", "(", "self", ",", "locals", "=", "locals", ",", "rawin", "=", "rawin", ",", "stdin", "=", "stdin", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ")", "sys", ".", "ps1", "=", "ps1", "sys", ".", "ps2", "=", "ps2" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/interpreter.py#L162-L168
opengm/opengm
decdacf4caad223b0ab5478d38a855f8767a394f
src/interfaces/python/opengm/__init__.py
python
loadGm
(f, d='gm', operator='adder')
return gm
save a graphical model to a hdf5 file: Args: f : filepath g : dataset (defaut : 'gm') operator : operator of the graphical model ('adder' / 'multiplier')
save a graphical model to a hdf5 file: Args: f : filepath g : dataset (defaut : 'gm') operator : operator of the graphical model ('adder' / 'multiplier')
[ "save", "a", "graphical", "model", "to", "a", "hdf5", "file", ":", "Args", ":", "f", ":", "filepath", "g", ":", "dataset", "(", "defaut", ":", "gm", ")", "operator", ":", "operator", "of", "the", "graphical", "model", "(", "adder", "/", "multiplier", ")" ]
def loadGm(f, d='gm', operator='adder'): """ save a graphical model to a hdf5 file: Args: f : filepath g : dataset (defaut : 'gm') operator : operator of the graphical model ('adder' / 'multiplier') """ if(operator=='adder'): gm=adder.GraphicalModel() elif(operator=='multiplier'): gm=multiplier.GraphicalModel() else: raise RuntimeError("unknown operator: "+ operator) hdf5.loadGraphicalModel(gm,f,d) return gm
[ "def", "loadGm", "(", "f", ",", "d", "=", "'gm'", ",", "operator", "=", "'adder'", ")", ":", "if", "(", "operator", "==", "'adder'", ")", ":", "gm", "=", "adder", ".", "GraphicalModel", "(", ")", "elif", "(", "operator", "==", "'multiplier'", ")", ":", "gm", "=", "multiplier", ".", "GraphicalModel", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"unknown operator: \"", "+", "operator", ")", "hdf5", ".", "loadGraphicalModel", "(", "gm", ",", "f", ",", "d", ")", "return", "gm" ]
https://github.com/opengm/opengm/blob/decdacf4caad223b0ab5478d38a855f8767a394f/src/interfaces/python/opengm/__init__.py#L81-L95
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/util.py
python
positional
(max_positional_args)
A decorator to declare that only the first N arguments may be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after * must be a keyword: fn(10, 'kw1', 'kw2') # Raises exception. fn(10, kwonly1='kw1') # Ok. Example: To define a function like above, do: @positional(1) def fn(pos1, kwonly1=None, kwonly2=None): ... If no default value is provided to a keyword argument, it becomes a required keyword argument: @positional(0) def fn(required_kw): ... This must be called with the keyword parameter: fn() # Raises exception. fn(10) # Raises exception. fn(required_kw=10) # Ok. When defining instance or class methods always remember to account for 'self' and 'cls': class MyClass(object): @positional(2) def my_method(self, pos1, kwonly1=None): ... @classmethod @positional(2) def my_method(cls, pos1, kwonly1=None): ... One can omit the argument to 'positional' altogether, and then no arguments with default values may be passed positionally. This would be equivalent to placing a '*' before the first argument with a default value in Python 3. If there are no arguments with default values, and no argument is given to 'positional', an error is raised. @positional def fn(arg1, arg2, required_kw1=None, required_kw2=0): ... fn(1, 3, 5) # Raises exception. fn(1, 3) # Ok. fn(1, 3, required_kw1=5) # Ok. Args: max_positional_arguments: Maximum number of positional arguments. All parameters after the this index must be keyword only. Returns: A decorator that prevents using arguments after max_positional_args from being used as positional parameters. Raises: TypeError if a keyword-only argument is provided as a positional parameter. ValueError if no maximum number of arguments is provided and the function has no arguments with default values.
A decorator to declare that only the first N arguments may be positional.
[ "A", "decorator", "to", "declare", "that", "only", "the", "first", "N", "arguments", "may", "be", "positional", "." ]
def positional(max_positional_args): """A decorator to declare that only the first N arguments may be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after * must be a keyword: fn(10, 'kw1', 'kw2') # Raises exception. fn(10, kwonly1='kw1') # Ok. Example: To define a function like above, do: @positional(1) def fn(pos1, kwonly1=None, kwonly2=None): ... If no default value is provided to a keyword argument, it becomes a required keyword argument: @positional(0) def fn(required_kw): ... This must be called with the keyword parameter: fn() # Raises exception. fn(10) # Raises exception. fn(required_kw=10) # Ok. When defining instance or class methods always remember to account for 'self' and 'cls': class MyClass(object): @positional(2) def my_method(self, pos1, kwonly1=None): ... @classmethod @positional(2) def my_method(cls, pos1, kwonly1=None): ... One can omit the argument to 'positional' altogether, and then no arguments with default values may be passed positionally. This would be equivalent to placing a '*' before the first argument with a default value in Python 3. If there are no arguments with default values, and no argument is given to 'positional', an error is raised. @positional def fn(arg1, arg2, required_kw1=None, required_kw2=0): ... fn(1, 3, 5) # Raises exception. fn(1, 3) # Ok. fn(1, 3, required_kw1=5) # Ok. Args: max_positional_arguments: Maximum number of positional arguments. All parameters after the this index must be keyword only. Returns: A decorator that prevents using arguments after max_positional_args from being used as positional parameters. Raises: TypeError if a keyword-only argument is provided as a positional parameter. ValueError if no maximum number of arguments is provided and the function has no arguments with default values. """ def positional_decorator(wrapped): def positional_wrapper(*args, **kwargs): if len(args) > max_positional_args: plural_s = '' if max_positional_args != 1: plural_s = 's' raise TypeError('%s() takes at most %d positional argument%s ' '(%d given)' % (wrapped.__name__, max_positional_args, plural_s, len(args))) return wrapped(*args, **kwargs) return positional_wrapper if isinstance(max_positional_args, six.integer_types): return positional_decorator else: args, _, _, defaults = inspect.getargspec(max_positional_args) if defaults is None: raise ValueError( 'Functions with no keyword arguments must specify ' 'max_positional_args') return positional(len(args) - len(defaults))(max_positional_args)
[ "def", "positional", "(", "max_positional_args", ")", ":", "def", "positional_decorator", "(", "wrapped", ")", ":", "def", "positional_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "max_positional_args", ":", "plural_s", "=", "''", "if", "max_positional_args", "!=", "1", ":", "plural_s", "=", "'s'", "raise", "TypeError", "(", "'%s() takes at most %d positional argument%s '", "'(%d given)'", "%", "(", "wrapped", ".", "__name__", ",", "max_positional_args", ",", "plural_s", ",", "len", "(", "args", ")", ")", ")", "return", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "positional_wrapper", "if", "isinstance", "(", "max_positional_args", ",", "six", ".", "integer_types", ")", ":", "return", "positional_decorator", "else", ":", "args", ",", "_", ",", "_", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "max_positional_args", ")", "if", "defaults", "is", "None", ":", "raise", "ValueError", "(", "'Functions with no keyword arguments must specify '", "'max_positional_args'", ")", "return", "positional", "(", "len", "(", "args", ")", "-", "len", "(", "defaults", ")", ")", "(", "max_positional_args", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/util.py#L86-L183
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/optimal_learning/python/comparison.py
python
EqualityComparisonMixin._get_comparable_members
(self)
return [(field, value) for field, value in members if not(field.startswith('__') and field.endswith('__'))]
r"""Return a list of fields to use in comparing two ``EqualityComparisonMixin`` subclasses for equality. Ignores fields that look like "__\(.*\)__". Ignores routines but NOT @property decorated functions, b/c this decorator converts the decorated to an attribute. :return: (field, value) pairs representing the group of fields to compare on :rtype: list
r"""Return a list of fields to use in comparing two ``EqualityComparisonMixin`` subclasses for equality.
[ "r", "Return", "a", "list", "of", "fields", "to", "use", "in", "comparing", "two", "EqualityComparisonMixin", "subclasses", "for", "equality", "." ]
def _get_comparable_members(self): r"""Return a list of fields to use in comparing two ``EqualityComparisonMixin`` subclasses for equality. Ignores fields that look like "__\(.*\)__". Ignores routines but NOT @property decorated functions, b/c this decorator converts the decorated to an attribute. :return: (field, value) pairs representing the group of fields to compare on :rtype: list """ members = inspect.getmembers(self, lambda field: not(inspect.isroutine(field))) return [(field, value) for field, value in members if not(field.startswith('__') and field.endswith('__'))]
[ "def", "_get_comparable_members", "(", "self", ")", ":", "members", "=", "inspect", ".", "getmembers", "(", "self", ",", "lambda", "field", ":", "not", "(", "inspect", ".", "isroutine", "(", "field", ")", ")", ")", "return", "[", "(", "field", ",", "value", ")", "for", "field", ",", "value", "in", "members", "if", "not", "(", "field", ".", "startswith", "(", "'__'", ")", "and", "field", ".", "endswith", "(", "'__'", ")", ")", "]" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/comparison.py#L62-L75
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/TreeWidget.py
python
listicons
(icondir=ICONDIR)
Utility to display the available icons.
Utility to display the available icons.
[ "Utility", "to", "display", "the", "available", "icons", "." ]
def listicons(icondir=ICONDIR): """Utility to display the available icons.""" root = Tk() import glob list = glob.glob(os.path.join(icondir, "*.gif")) list.sort() images = [] row = column = 0 for file in list: name = os.path.splitext(os.path.basename(file))[0] image = PhotoImage(file=file, master=root) images.append(image) label = Label(root, image=image, bd=1, relief="raised") label.grid(row=row, column=column) label = Label(root, text=name) label.grid(row=row+1, column=column) column = column + 1 if column >= 10: row = row+2 column = 0 root.images = images
[ "def", "listicons", "(", "icondir", "=", "ICONDIR", ")", ":", "root", "=", "Tk", "(", ")", "import", "glob", "list", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "icondir", ",", "\"*.gif\"", ")", ")", "list", ".", "sort", "(", ")", "images", "=", "[", "]", "row", "=", "column", "=", "0", "for", "file", "in", "list", ":", "name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "file", ")", ")", "[", "0", "]", "image", "=", "PhotoImage", "(", "file", "=", "file", ",", "master", "=", "root", ")", "images", ".", "append", "(", "image", ")", "label", "=", "Label", "(", "root", ",", "image", "=", "image", ",", "bd", "=", "1", ",", "relief", "=", "\"raised\"", ")", "label", ".", "grid", "(", "row", "=", "row", ",", "column", "=", "column", ")", "label", "=", "Label", "(", "root", ",", "text", "=", "name", ")", "label", ".", "grid", "(", "row", "=", "row", "+", "1", ",", "column", "=", "column", ")", "column", "=", "column", "+", "1", "if", "column", ">=", "10", ":", "row", "=", "row", "+", "2", "column", "=", "0", "root", ".", "images", "=", "images" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/TreeWidget.py#L36-L56
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/wizard.py
python
WizardPage.GetBitmap
(*args, **kwargs)
return _wizard.WizardPage_GetBitmap(*args, **kwargs)
GetBitmap(self) -> Bitmap
GetBitmap(self) -> Bitmap
[ "GetBitmap", "(", "self", ")", "-", ">", "Bitmap" ]
def GetBitmap(*args, **kwargs): """GetBitmap(self) -> Bitmap""" return _wizard.WizardPage_GetBitmap(*args, **kwargs)
[ "def", "GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_wizard", ".", "WizardPage_GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/wizard.py#L125-L127
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/impl/masterslave.py
python
ROSHandler.remappings
(cls, methodName)
@internal @param cls: class to register remappings on @type cls: Class: class to register remappings on @return: parameters (by pos) that should be remapped because they are names @rtype: list
[]
def remappings(cls, methodName): """ @internal @param cls: class to register remappings on @type cls: Class: class to register remappings on @return: parameters (by pos) that should be remapped because they are names @rtype: list """ if methodName in cls._remap_table: return cls._remap_table[methodName] else: return []
[ "def", "remappings", "(", "cls", ",", "methodName", ")", ":", "if", "methodName", "in", "cls", ".", "_remap_table", ":", "return", "cls", ".", "_remap_table", "[", "methodName", "]", "else", ":", "return", "[", "]" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/masterslave.py#L257-L268
D-X-Y/caffe-faster-rcnn
eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb
scripts/cpp_lint.py
python
FileInfo.FullName
(self)
return os.path.abspath(self._filename).replace('\\', '/')
Make Windows paths like Unix.
Make Windows paths like Unix.
[ "Make", "Windows", "paths", "like", "Unix", "." ]
def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/')
[ "def", "FullName", "(", "self", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "self", ".", "_filename", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")" ]
https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/scripts/cpp_lint.py#L885-L887
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/gluon/data/dataloader.py
python
default_mp_batchify_fn
(data)
Collate data into batch. Use shared memory for stacking.
Collate data into batch. Use shared memory for stacking.
[ "Collate", "data", "into", "batch", ".", "Use", "shared", "memory", "for", "stacking", "." ]
def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0)) return nd.stack(*data, out=out) elif isinstance(data[0], tuple): data = zip(*data) return [default_mp_batchify_fn(i) for i in data] else: data = np.asarray(data) return nd.array(data, dtype=data.dtype, ctx=context.Context('cpu_shared', 0))
[ "def", "default_mp_batchify_fn", "(", "data", ")", ":", "if", "isinstance", "(", "data", "[", "0", "]", ",", "nd", ".", "NDArray", ")", ":", "out", "=", "nd", ".", "empty", "(", "(", "len", "(", "data", ")", ",", ")", "+", "data", "[", "0", "]", ".", "shape", ",", "dtype", "=", "data", "[", "0", "]", ".", "dtype", ",", "ctx", "=", "context", ".", "Context", "(", "'cpu_shared'", ",", "0", ")", ")", "return", "nd", ".", "stack", "(", "*", "data", ",", "out", "=", "out", ")", "elif", "isinstance", "(", "data", "[", "0", "]", ",", "tuple", ")", ":", "data", "=", "zip", "(", "*", "data", ")", "return", "[", "default_mp_batchify_fn", "(", "i", ")", "for", "i", "in", "data", "]", "else", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", "return", "nd", ".", "array", "(", "data", ",", "dtype", "=", "data", ".", "dtype", ",", "ctx", "=", "context", ".", "Context", "(", "'cpu_shared'", ",", "0", ")", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/gluon/data/dataloader.py#L99-L111
strukturag/libheif
0082fea96ee70a20c8906a0373bedec0c01777bc
scripts/cpplint.py
python
CheckHeaderFileIncluded
(filename, include_state, error)
Logs an error if a .cc file does not include its header.
Logs an error if a .cc file does not include its header.
[ "Logs", "an", "error", "if", "a", ".", "cc", "file", "does", "not", "include", "its", "header", "." ]
def CheckHeaderFileIncluded(filename, include_state, error): """Logs an error if a .cc file does not include its header.""" # Do not check test files fileinfo = FileInfo(filename) if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()): return headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h' if not os.path.exists(headerfile): return headername = FileInfo(headerfile).RepositoryName() first_include = 0 for section_list in include_state.include_list: for f in section_list: if headername in f[0] or f[0] in headername: return if not first_include: first_include = f[1] error(filename, first_include, 'build/include', 5, '%s should include its header file %s' % (fileinfo.RepositoryName(), headername))
[ "def", "CheckHeaderFileIncluded", "(", "filename", ",", "include_state", ",", "error", ")", ":", "# Do not check test files", "fileinfo", "=", "FileInfo", "(", "filename", ")", "if", "Search", "(", "_TEST_FILE_SUFFIX", ",", "fileinfo", ".", "BaseName", "(", ")", ")", ":", "return", "headerfile", "=", "filename", "[", "0", ":", "len", "(", "filename", ")", "-", "len", "(", "fileinfo", ".", "Extension", "(", ")", ")", "]", "+", "'.h'", "if", "not", "os", ".", "path", ".", "exists", "(", "headerfile", ")", ":", "return", "headername", "=", "FileInfo", "(", "headerfile", ")", ".", "RepositoryName", "(", ")", "first_include", "=", "0", "for", "section_list", "in", "include_state", ".", "include_list", ":", "for", "f", "in", "section_list", ":", "if", "headername", "in", "f", "[", "0", "]", "or", "f", "[", "0", "]", "in", "headername", ":", "return", "if", "not", "first_include", ":", "first_include", "=", "f", "[", "1", "]", "error", "(", "filename", ",", "first_include", ",", "'build/include'", ",", "5", ",", "'%s should include its header file %s'", "%", "(", "fileinfo", ".", "RepositoryName", "(", ")", ",", "headername", ")", ")" ]
https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L1862-L1884
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/appdirs.py
python
user_log_dir
(appname=None, appauthor=None, version=None, opinion=True)
return path
r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user log directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option.
r"""Return full path to the user-specific log dir for this application.
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "log", "dir", "for", "this", "application", "." ]
def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user log directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. """ if system == "darwin": path = os.path.join( os.path.expanduser('~/Library/Logs'), appname) elif system == "win32": path = user_data_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "Logs") else: path = user_cache_dir(appname, appauthor, version) version = False if opinion: path = os.path.join(path, "log") if appname and version: path = os.path.join(path, version) return path
[ "def", "user_log_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "opinion", "=", "True", ")", ":", "if", "system", "==", "\"darwin\"", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~/Library/Logs'", ")", ",", "appname", ")", "elif", "system", "==", "\"win32\"", ":", "path", "=", "user_data_dir", "(", "appname", ",", "appauthor", ",", "version", ")", "version", "=", "False", "if", "opinion", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"Logs\"", ")", "else", ":", "path", "=", "user_cache_dir", "(", "appname", ",", "appauthor", ",", "version", ")", "version", "=", "False", "if", "opinion", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"log\"", ")", "if", "appname", "and", "version", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "version", ")", "return", "path" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/appdirs.py#L356-L404
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/mox3/mox3/mox.py
python
MockMethod.AndRaise
(self, exception)
Set the exception to raise when this method is called. Args: # exception: the exception to raise when this method is called. exception: Exception
Set the exception to raise when this method is called.
[ "Set", "the", "exception", "to", "raise", "when", "this", "method", "is", "called", "." ]
def AndRaise(self, exception): """Set the exception to raise when this method is called. Args: # exception: the exception to raise when this method is called. exception: Exception """ self._exception = exception
[ "def", "AndRaise", "(", "self", ",", "exception", ")", ":", "self", ".", "_exception", "=", "exception" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/mox3/mox3/mox.py#L1303-L1311
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/instrument.py
python
Instrument.open_interest
(self)
return self._open_interest
Gets the open_interest of this Instrument. # noqa: E501 :return: The open_interest of this Instrument. # noqa: E501 :rtype: float
Gets the open_interest of this Instrument. # noqa: E501
[ "Gets", "the", "open_interest", "of", "this", "Instrument", ".", "#", "noqa", ":", "E501" ]
def open_interest(self): """Gets the open_interest of this Instrument. # noqa: E501 :return: The open_interest of this Instrument. # noqa: E501 :rtype: float """ return self._open_interest
[ "def", "open_interest", "(", "self", ")", ":", "return", "self", ".", "_open_interest" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument.py#L2452-L2459
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/web.py
python
RequestHandler.settings
(self)
return self.application.settings
An alias for `self.application.settings <Application.settings>`.
An alias for `self.application.settings <Application.settings>`.
[ "An", "alias", "for", "self", ".", "application", ".", "settings", "<Application", ".", "settings", ">", "." ]
def settings(self) -> Dict[str, Any]: """An alias for `self.application.settings <Application.settings>`.""" return self.application.settings
[ "def", "settings", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "self", ".", "application", ".", "settings" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/web.py#L259-L261
bcrusco/Forward-Plus-Renderer
1f130f1ae58882f651d94695823044f9833cfa30
Forward-Plus/Forward-Plus/external/assimp-3.1.1/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py
python
GLRenderer.prepare_gl_buffers
(self, mesh)
Creates 3 buffer objets for each mesh, to store the vertices, the normals, and the faces indices.
Creates 3 buffer objets for each mesh, to store the vertices, the normals, and the faces indices.
[ "Creates", "3", "buffer", "objets", "for", "each", "mesh", "to", "store", "the", "vertices", "the", "normals", "and", "the", "faces", "indices", "." ]
def prepare_gl_buffers(self, mesh): """ Creates 3 buffer objets for each mesh, to store the vertices, the normals, and the faces indices. """ mesh.gl = {} # Fill the buffer for vertex positions mesh.gl["vertices"] = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, mesh.gl["vertices"]) glBufferData(GL_ARRAY_BUFFER, mesh.vertices, GL_STATIC_DRAW) # Fill the buffer for normals mesh.gl["normals"] = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, mesh.gl["normals"]) glBufferData(GL_ARRAY_BUFFER, mesh.normals, GL_STATIC_DRAW) # Fill the buffer for vertex positions mesh.gl["triangles"] = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["triangles"]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh.faces, GL_STATIC_DRAW) # Unbind buffers glBindBuffer(GL_ARRAY_BUFFER,0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0)
[ "def", "prepare_gl_buffers", "(", "self", ",", "mesh", ")", ":", "mesh", ".", "gl", "=", "{", "}", "# Fill the buffer for vertex positions", "mesh", ".", "gl", "[", "\"vertices\"", "]", "=", "glGenBuffers", "(", "1", ")", "glBindBuffer", "(", "GL_ARRAY_BUFFER", ",", "mesh", ".", "gl", "[", "\"vertices\"", "]", ")", "glBufferData", "(", "GL_ARRAY_BUFFER", ",", "mesh", ".", "vertices", ",", "GL_STATIC_DRAW", ")", "# Fill the buffer for normals", "mesh", ".", "gl", "[", "\"normals\"", "]", "=", "glGenBuffers", "(", "1", ")", "glBindBuffer", "(", "GL_ARRAY_BUFFER", ",", "mesh", ".", "gl", "[", "\"normals\"", "]", ")", "glBufferData", "(", "GL_ARRAY_BUFFER", ",", "mesh", ".", "normals", ",", "GL_STATIC_DRAW", ")", "# Fill the buffer for vertex positions", "mesh", ".", "gl", "[", "\"triangles\"", "]", "=", "glGenBuffers", "(", "1", ")", "glBindBuffer", "(", "GL_ELEMENT_ARRAY_BUFFER", ",", "mesh", ".", "gl", "[", "\"triangles\"", "]", ")", "glBufferData", "(", "GL_ELEMENT_ARRAY_BUFFER", ",", "mesh", ".", "faces", ",", "GL_STATIC_DRAW", ")", "# Unbind buffers", "glBindBuffer", "(", "GL_ARRAY_BUFFER", ",", "0", ")", "glBindBuffer", "(", "GL_ELEMENT_ARRAY_BUFFER", ",", "0", ")" ]
https://github.com/bcrusco/Forward-Plus-Renderer/blob/1f130f1ae58882f651d94695823044f9833cfa30/Forward-Plus/Forward-Plus/external/assimp-3.1.1/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py#L63-L95
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/fx/prepare.py
python
is_output_dtype_supported_by_backend
( node: Node, node_name_to_target_dtype: Dict[str, Dict[str, Optional[torch.dtype]]], dtype_config: Dict[str, torch.dtype], )
return output_dtype is None or \ output_dtype == node_name_to_target_dtype[node.name]["output_activation_dtype"]
Check if the configured qconfig for the output is supported by the backend or not
Check if the configured qconfig for the output is supported by the backend or not
[ "Check", "if", "the", "configured", "qconfig", "for", "the", "output", "is", "supported", "by", "the", "backend", "or", "not" ]
def is_output_dtype_supported_by_backend( node: Node, node_name_to_target_dtype: Dict[str, Dict[str, Optional[torch.dtype]]], dtype_config: Dict[str, torch.dtype], ) -> bool: """ Check if the configured qconfig for the output is supported by the backend or not """ output_dtype = dtype_config.get("output_dtype", None) return output_dtype is None or \ output_dtype == node_name_to_target_dtype[node.name]["output_activation_dtype"]
[ "def", "is_output_dtype_supported_by_backend", "(", "node", ":", "Node", ",", "node_name_to_target_dtype", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Optional", "[", "torch", ".", "dtype", "]", "]", "]", ",", "dtype_config", ":", "Dict", "[", "str", ",", "torch", ".", "dtype", "]", ",", ")", "->", "bool", ":", "output_dtype", "=", "dtype_config", ".", "get", "(", "\"output_dtype\"", ",", "None", ")", "return", "output_dtype", "is", "None", "or", "output_dtype", "==", "node_name_to_target_dtype", "[", "node", ".", "name", "]", "[", "\"output_activation_dtype\"", "]" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/prepare.py#L153-L163
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py
python
_IsPresent
(item)
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
[ "Given", "a", "(", "FieldDescriptor", "value", ")", "tuple", "from", "_fields", "return", "true", "if", "the", "value", "should", "be", "included", "in", "the", "list", "returned", "by", "ListFields", "()", "." ]
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return item[1]._is_present_in_parent else: return True
[ "def", "_IsPresent", "(", "item", ")", ":", "if", "item", "[", "0", "]", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "return", "bool", "(", "item", "[", "1", "]", ")", "elif", "item", "[", "0", "]", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "return", "item", "[", "1", "]", ".", "_is_present_in_parent", "else", ":", "return", "True" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L612-L621
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/probability/distributions/normal.py
python
Normal.sample
(self, size=None)
return np.random.normal(self.loc, self.scale, size)
r"""Generate samples of `size` from the normal distribution parameterized by `self._loc` and `self._scale` Parameters ---------- size : Tuple, Scalar, or None Size of samples to be generated. If size=None, the output shape will be `broadcast(loc, scale).shape` Returns ------- Tensor Samples from Normal distribution.
r"""Generate samples of `size` from the normal distribution parameterized by `self._loc` and `self._scale`
[ "r", "Generate", "samples", "of", "size", "from", "the", "normal", "distribution", "parameterized", "by", "self", ".", "_loc", "and", "self", ".", "_scale" ]
def sample(self, size=None): r"""Generate samples of `size` from the normal distribution parameterized by `self._loc` and `self._scale` Parameters ---------- size : Tuple, Scalar, or None Size of samples to be generated. If size=None, the output shape will be `broadcast(loc, scale).shape` Returns ------- Tensor Samples from Normal distribution. """ return np.random.normal(self.loc, self.scale, size)
[ "def", "sample", "(", "self", ",", "size", "=", "None", ")", ":", "return", "np", ".", "random", ".", "normal", "(", "self", ".", "loc", ",", "self", ".", "scale", ",", "size", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/normal.py#L73-L88
PlatformLab/RAMCloud
b1866af19124325a6dfd8cbc267e2e3ef1f965d1
scripts/recoverymetrics.py
python
values
(s)
return [p[1] for p in s]
Return a sequence of the second items from a sequence.
Return a sequence of the second items from a sequence.
[ "Return", "a", "sequence", "of", "the", "second", "items", "from", "a", "sequence", "." ]
def values(s): """Return a sequence of the second items from a sequence.""" return [p[1] for p in s]
[ "def", "values", "(", "s", ")", ":", "return", "[", "p", "[", "1", "]", "for", "p", "in", "s", "]" ]
https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/recoverymetrics.py#L120-L122
AojunZhou/Incremental-Network-Quantization
c7f6a609d5817d8424ce224209cf4c50f1e4de50
tools/extra/resize_and_crop_images.py
python
OpenCVResizeCrop.resize_and_crop_image
(self, input_file, output_file, output_side_length = 256)
Takes an image name, resize it and crop the center square
Takes an image name, resize it and crop the center square
[ "Takes", "an", "image", "name", "resize", "it", "and", "crop", "the", "center", "square" ]
def resize_and_crop_image(self, input_file, output_file, output_side_length = 256): '''Takes an image name, resize it and crop the center square ''' img = cv2.imread(input_file) height, width, depth = img.shape new_height = output_side_length new_width = output_side_length if height > width: new_height = output_side_length * height / width else: new_width = output_side_length * width / height resized_img = cv2.resize(img, (new_width, new_height)) height_offset = (new_height - output_side_length) / 2 width_offset = (new_width - output_side_length) / 2 cropped_img = resized_img[height_offset:height_offset + output_side_length, width_offset:width_offset + output_side_length] cv2.imwrite(output_file, cropped_img)
[ "def", "resize_and_crop_image", "(", "self", ",", "input_file", ",", "output_file", ",", "output_side_length", "=", "256", ")", ":", "img", "=", "cv2", ".", "imread", "(", "input_file", ")", "height", ",", "width", ",", "depth", "=", "img", ".", "shape", "new_height", "=", "output_side_length", "new_width", "=", "output_side_length", "if", "height", ">", "width", ":", "new_height", "=", "output_side_length", "*", "height", "/", "width", "else", ":", "new_width", "=", "output_side_length", "*", "width", "/", "height", "resized_img", "=", "cv2", ".", "resize", "(", "img", ",", "(", "new_width", ",", "new_height", ")", ")", "height_offset", "=", "(", "new_height", "-", "output_side_length", ")", "/", "2", "width_offset", "=", "(", "new_width", "-", "output_side_length", ")", "/", "2", "cropped_img", "=", "resized_img", "[", "height_offset", ":", "height_offset", "+", "output_side_length", ",", "width_offset", ":", "width_offset", "+", "output_side_length", "]", "cv2", ".", "imwrite", "(", "output_file", ",", "cropped_img", ")" ]
https://github.com/AojunZhou/Incremental-Network-Quantization/blob/c7f6a609d5817d8424ce224209cf4c50f1e4de50/tools/extra/resize_and_crop_images.py#L20-L36
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBCommunication.IsValid
(self)
return _lldb.SBCommunication_IsValid(self)
IsValid(self) -> bool
IsValid(self) -> bool
[ "IsValid", "(", "self", ")", "-", ">", "bool" ]
def IsValid(self): """IsValid(self) -> bool""" return _lldb.SBCommunication_IsValid(self)
[ "def", "IsValid", "(", "self", ")", ":", "return", "_lldb", ".", "SBCommunication_IsValid", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L2425-L2427
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
llvm/bindings/python/llvm/common.py
python
LLVMObject.from_param
(self)
return self._as_parameter_
ctypes function that converts this object to a function parameter.
ctypes function that converts this object to a function parameter.
[ "ctypes", "function", "that", "converts", "this", "object", "to", "a", "function", "parameter", "." ]
def from_param(self): """ctypes function that converts this object to a function parameter.""" return self._as_parameter_
[ "def", "from_param", "(", "self", ")", ":", "return", "self", ".", "_as_parameter_" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/llvm/bindings/python/llvm/common.py#L59-L61
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBValue.GetStaticValue
(self)
return _lldb.SBValue_GetStaticValue(self)
GetStaticValue(self) -> SBValue
GetStaticValue(self) -> SBValue
[ "GetStaticValue", "(", "self", ")", "-", ">", "SBValue" ]
def GetStaticValue(self): """GetStaticValue(self) -> SBValue""" return _lldb.SBValue_GetStaticValue(self)
[ "def", "GetStaticValue", "(", "self", ")", ":", "return", "_lldb", ".", "SBValue_GetStaticValue", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11884-L11886
cvmfs/cvmfs
4637bdb5153178eadf885c1acf37bdc5c685bf8a
cpplint.py
python
CheckRValueReference
(filename, clean_lines, linenum, nesting_state, error)
Check for rvalue references. 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: The function to call with any errors found.
Check for rvalue references.
[ "Check", "for", "rvalue", "references", "." ]
def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error): """Check for rvalue references. 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: The function to call with any errors found. """ # Find lines missing spaces around &&. # TODO(unknown): currently we don't check for rvalue references # with spaces surrounding the && to avoid false positives with # boolean expressions. line = clean_lines.elided[linenum] match = Match(r'^(.*\S)&&', line) if not match: match = Match(r'(.*)&&\S', line) if (not match) or '(&&)' in line or Search(r'\boperator\s*$', match.group(1)): return # Either poorly formed && or an rvalue reference, check the context # to get a more accurate error message. Mostly we want to determine # if what's to the left of "&&" is a type or not. typenames = GetTemplateArgs(clean_lines, linenum) and_pos = len(match.group(1)) if IsRValueType(typenames, clean_lines, nesting_state, linenum, and_pos): if not IsRValueAllowed(clean_lines, linenum, typenames): error(filename, linenum, 'build/c++11', 3, 'RValue references are an unapproved C++ feature.') else: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around &&')
[ "def", "CheckRValueReference", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Find lines missing spaces around &&.", "# TODO(unknown): currently we don't check for rvalue references", "# with spaces surrounding the && to avoid false positives with", "# boolean expressions.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Match", "(", "r'^(.*\\S)&&'", ",", "line", ")", "if", "not", "match", ":", "match", "=", "Match", "(", "r'(.*)&&\\S'", ",", "line", ")", "if", "(", "not", "match", ")", "or", "'(&&)'", "in", "line", "or", "Search", "(", "r'\\boperator\\s*$'", ",", "match", ".", "group", "(", "1", ")", ")", ":", "return", "# Either poorly formed && or an rvalue reference, check the context", "# to get a more accurate error message. Mostly we want to determine", "# if what's to the left of \"&&\" is a type or not.", "typenames", "=", "GetTemplateArgs", "(", "clean_lines", ",", "linenum", ")", "and_pos", "=", "len", "(", "match", ".", "group", "(", "1", ")", ")", "if", "IsRValueType", "(", "typenames", ",", "clean_lines", ",", "nesting_state", ",", "linenum", ",", "and_pos", ")", ":", "if", "not", "IsRValueAllowed", "(", "clean_lines", ",", "linenum", ",", "typenames", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/c++11'", ",", "3", ",", "'RValue references are an unapproved C++ feature.'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around &&'", ")" ]
https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L3776-L3809
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/ecl_ekf/analysis/detectors.py
python
InAirDetector.log_start
(self)
return self._log_start
log start :return: the start time of the log.
log start :return: the start time of the log.
[ "log", "start", ":", "return", ":", "the", "start", "time", "of", "the", "log", "." ]
def log_start(self) -> Optional[float]: """ log start :return: the start time of the log. """ return self._log_start
[ "def", "log_start", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_log_start" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/ecl_ekf/analysis/detectors.py#L132-L137
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.DragAcceptFiles
(*args, **kwargs)
return _core_.Window_DragAcceptFiles(*args, **kwargs)
DragAcceptFiles(self, bool accept) Enables or disables eligibility for drop file events, EVT_DROP_FILES.
DragAcceptFiles(self, bool accept)
[ "DragAcceptFiles", "(", "self", "bool", "accept", ")" ]
def DragAcceptFiles(*args, **kwargs): """ DragAcceptFiles(self, bool accept) Enables or disables eligibility for drop file events, EVT_DROP_FILES. """ return _core_.Window_DragAcceptFiles(*args, **kwargs)
[ "def", "DragAcceptFiles", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_DragAcceptFiles", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L11434-L11440
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/ML/Data/Stats.py
python
R2
(orig, residSum)
return 1. - residSum / oVar
returns the R2 value for a set of predictions
returns the R2 value for a set of predictions
[ "returns", "the", "R2", "value", "for", "a", "set", "of", "predictions" ]
def R2(orig, residSum): """ returns the R2 value for a set of predictions """ # FIX: this just is not right # # A correct formulation of this (from Excel) for 2 variables is: # r2 = [n*(Sxy) - (Sx)(Sy)]^2 / ([n*(Sx2) - (Sx)^2]*[n*(Sy2) - (Sy)^2]) # # vect = numpy.array(orig) n = vect.shape[0] if n <= 0: return 0., 0. oMean = sum(vect) / n v = vect - oMean oVar = sum(v * v) return 1. - residSum / oVar
[ "def", "R2", "(", "orig", ",", "residSum", ")", ":", "# FIX: this just is not right", "#", "# A correct formulation of this (from Excel) for 2 variables is:", "# r2 = [n*(Sxy) - (Sx)(Sy)]^2 / ([n*(Sx2) - (Sx)^2]*[n*(Sy2) - (Sy)^2])", "#", "#", "vect", "=", "numpy", ".", "array", "(", "orig", ")", "n", "=", "vect", ".", "shape", "[", "0", "]", "if", "n", "<=", "0", ":", "return", "0.", ",", "0.", "oMean", "=", "sum", "(", "vect", ")", "/", "n", "v", "=", "vect", "-", "oMean", "oVar", "=", "sum", "(", "v", "*", "v", ")", "return", "1.", "-", "residSum", "/", "oVar" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/Data/Stats.py#L145-L162
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/idna/intranges.py
python
intranges_contain
(int_, ranges)
return False
Determine if `int_` falls into one of the ranges in `ranges`.
Determine if `int_` falls into one of the ranges in `ranges`.
[ "Determine", "if", "int_", "falls", "into", "one", "of", "the", "ranges", "in", "ranges", "." ]
def intranges_contain(int_, ranges): """Determine if `int_` falls into one of the ranges in `ranges`.""" tuple_ = _encode_range(int_, 0) pos = bisect.bisect_left(ranges, tuple_) # we could be immediately ahead of a tuple (start, end) # with start < int_ <= end if pos > 0: left, right = _decode_range(ranges[pos-1]) if left <= int_ < right: return True # or we could be immediately behind a tuple (int_, end) if pos < len(ranges): left, _ = _decode_range(ranges[pos]) if left == int_: return True return False
[ "def", "intranges_contain", "(", "int_", ",", "ranges", ")", ":", "tuple_", "=", "_encode_range", "(", "int_", ",", "0", ")", "pos", "=", "bisect", ".", "bisect_left", "(", "ranges", ",", "tuple_", ")", "# we could be immediately ahead of a tuple (start, end)", "# with start < int_ <= end", "if", "pos", ">", "0", ":", "left", ",", "right", "=", "_decode_range", "(", "ranges", "[", "pos", "-", "1", "]", ")", "if", "left", "<=", "int_", "<", "right", ":", "return", "True", "# or we could be immediately behind a tuple (int_, end)", "if", "pos", "<", "len", "(", "ranges", ")", ":", "left", ",", "_", "=", "_decode_range", "(", "ranges", "[", "pos", "]", ")", "if", "left", "==", "int_", ":", "return", "True", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/idna/intranges.py#L75-L105
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListMainWindow.GetFirstGradientColour
(self)
return self._firstcolour
Returns the first gradient colour for gradient-style selections.
Returns the first gradient colour for gradient-style selections.
[ "Returns", "the", "first", "gradient", "colour", "for", "gradient", "-", "style", "selections", "." ]
def GetFirstGradientColour(self): """ Returns the first gradient colour for gradient-style selections. """ return self._firstcolour
[ "def", "GetFirstGradientColour", "(", "self", ")", ":", "return", "self", ".", "_firstcolour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L10631-L10634
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
NewEventType
(*args)
return _core_.NewEventType(*args)
NewEventType() -> EventType
NewEventType() -> EventType
[ "NewEventType", "()", "-", ">", "EventType" ]
def NewEventType(*args): """NewEventType() -> EventType""" return _core_.NewEventType(*args)
[ "def", "NewEventType", "(", "*", "args", ")", ":", "return", "_core_", ".", "NewEventType", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L4641-L4643
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/harness-thci/OpenThread_WpanCtl.py
python
OpenThread_WpanCtl.getGlobal
(self)
return globalAddrs
get global unicast IPv6 address set if configuring multiple entries
get global unicast IPv6 address set if configuring multiple entries
[ "get", "global", "unicast", "IPv6", "address", "set", "if", "configuring", "multiple", "entries" ]
def getGlobal(self): """get global unicast IPv6 address set if configuring multiple entries """ print('%s call getGlobal' % self.port) globalAddrs = [] mleid = self.__stripValue(self.__sendCommand(self.wpan_cmd_prefix + 'getprop -v IPv6:MeshLocalAddress')[0]) mleid = ModuleHelper.GetFullIpv6Address(mleid).lower() addrs = self.__sendCommand(self.wpan_cmd_prefix + 'getprop -v IPv6:AllAddresses') # find rloc address firstly as a reference for current mesh local prefix as for some TCs, # mesh local prefix may be updated through pending dataset management. for ip6AddrItem in addrs: if re.match(r'\[|\]', ip6AddrItem): continue if re.match(self.prompt, ip6AddrItem, re.M | re.I): break ip6AddrItem = ip6AddrItem.strip() ip6Addr = self.__stripValue(ip6AddrItem).split(' ')[0] fullIp = ModuleHelper.GetFullIpv6Address(ip6Addr).lower() print('fullip %s' % fullIp) if fullIp.startswith('fe80'): continue if fullIp.startswith(mleid[0:19]): continue print('global') globalAddrs.append(fullIp) return globalAddrs
[ "def", "getGlobal", "(", "self", ")", ":", "print", "(", "'%s call getGlobal'", "%", "self", ".", "port", ")", "globalAddrs", "=", "[", "]", "mleid", "=", "self", ".", "__stripValue", "(", "self", ".", "__sendCommand", "(", "self", ".", "wpan_cmd_prefix", "+", "'getprop -v IPv6:MeshLocalAddress'", ")", "[", "0", "]", ")", "mleid", "=", "ModuleHelper", ".", "GetFullIpv6Address", "(", "mleid", ")", ".", "lower", "(", ")", "addrs", "=", "self", ".", "__sendCommand", "(", "self", ".", "wpan_cmd_prefix", "+", "'getprop -v IPv6:AllAddresses'", ")", "# find rloc address firstly as a reference for current mesh local prefix as for some TCs,", "# mesh local prefix may be updated through pending dataset management.", "for", "ip6AddrItem", "in", "addrs", ":", "if", "re", ".", "match", "(", "r'\\[|\\]'", ",", "ip6AddrItem", ")", ":", "continue", "if", "re", ".", "match", "(", "self", ".", "prompt", ",", "ip6AddrItem", ",", "re", ".", "M", "|", "re", ".", "I", ")", ":", "break", "ip6AddrItem", "=", "ip6AddrItem", ".", "strip", "(", ")", "ip6Addr", "=", "self", ".", "__stripValue", "(", "ip6AddrItem", ")", ".", "split", "(", "' '", ")", "[", "0", "]", "fullIp", "=", "ModuleHelper", ".", "GetFullIpv6Address", "(", "ip6Addr", ")", ".", "lower", "(", ")", "print", "(", "'fullip %s'", "%", "fullIp", ")", "if", "fullIp", ".", "startswith", "(", "'fe80'", ")", ":", "continue", "if", "fullIp", ".", "startswith", "(", "mleid", "[", "0", ":", "19", "]", ")", ":", "continue", "print", "(", "'global'", ")", "globalAddrs", ".", "append", "(", "fullIp", ")", "return", "globalAddrs" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread_WpanCtl.py#L957-L993
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py
python
infer
(restore_checkpoint_path, output_dict, feed_dict=None)
return run_feeds(output_dict=output_dict, feed_dicts=[feed_dict] if feed_dict is not None else [None], restore_checkpoint_path=restore_checkpoint_path)[0]
Restore graph from `restore_checkpoint_path` and run `output_dict` tensors. If `restore_checkpoint_path` is supplied, restore from checkpoint. Otherwise, init all variables. Args: restore_checkpoint_path: A string containing the path to a checkpoint to restore. output_dict: A `dict` mapping string names to `Tensor` objects to run. Tensors must all be from the same graph. feed_dict: `dict` object mapping `Tensor` objects to input values to feed. Returns: Dict of values read from `output_dict` tensors. Keys are the same as `output_dict`, values are the results read from the corresponding `Tensor` in `output_dict`. Raises: ValueError: if `output_dict` or `feed_dicts` is None or empty.
Restore graph from `restore_checkpoint_path` and run `output_dict` tensors.
[ "Restore", "graph", "from", "restore_checkpoint_path", "and", "run", "output_dict", "tensors", "." ]
def infer(restore_checkpoint_path, output_dict, feed_dict=None): """Restore graph from `restore_checkpoint_path` and run `output_dict` tensors. If `restore_checkpoint_path` is supplied, restore from checkpoint. Otherwise, init all variables. Args: restore_checkpoint_path: A string containing the path to a checkpoint to restore. output_dict: A `dict` mapping string names to `Tensor` objects to run. Tensors must all be from the same graph. feed_dict: `dict` object mapping `Tensor` objects to input values to feed. Returns: Dict of values read from `output_dict` tensors. Keys are the same as `output_dict`, values are the results read from the corresponding `Tensor` in `output_dict`. Raises: ValueError: if `output_dict` or `feed_dicts` is None or empty. """ return run_feeds(output_dict=output_dict, feed_dicts=[feed_dict] if feed_dict is not None else [None], restore_checkpoint_path=restore_checkpoint_path)[0]
[ "def", "infer", "(", "restore_checkpoint_path", ",", "output_dict", ",", "feed_dict", "=", "None", ")", ":", "return", "run_feeds", "(", "output_dict", "=", "output_dict", ",", "feed_dicts", "=", "[", "feed_dict", "]", "if", "feed_dict", "is", "not", "None", "else", "[", "None", "]", ",", "restore_checkpoint_path", "=", "restore_checkpoint_path", ")", "[", "0", "]" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py#L855-L878
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/extension.py
python
_have_cython
()
return False
Return True if Cython can be imported.
Return True if Cython can be imported.
[ "Return", "True", "if", "Cython", "can", "be", "imported", "." ]
def _have_cython(): """ Return True if Cython can be imported. """ cython_impl = 'Cython.Distutils.build_ext' try: # from (cython_impl) import build_ext __import__(cython_impl, fromlist=['build_ext']).build_ext return True except Exception: pass return False
[ "def", "_have_cython", "(", ")", ":", "cython_impl", "=", "'Cython.Distutils.build_ext'", "try", ":", "# from (cython_impl) import build_ext", "__import__", "(", "cython_impl", ",", "fromlist", "=", "[", "'build_ext'", "]", ")", ".", "build_ext", "return", "True", "except", "Exception", ":", "pass", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/extension.py#L10-L21
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/idlelib/aboutDialog.py
python
AboutDialog.__init__
(self, parent, title, _htest=False)
_htest - bool, change box location when running htest
_htest - bool, change box location when running htest
[ "_htest", "-", "bool", "change", "box", "location", "when", "running", "htest" ]
def __init__(self, parent, title, _htest=False): """ _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) # place dialog below parent if running htest self.geometry("+%d+%d" % ( parent.winfo_rootx()+30, parent.winfo_rooty()+(30 if not _htest else 100))) self.bg = "#707070" self.fg = "#ffffff" self.CreateWidgets() self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Ok) self.parent = parent self.buttonOk.focus_set() self.bind('<Return>',self.Ok) #dismiss dialog self.bind('<Escape>',self.Ok) #dismiss dialog self.wait_window()
[ "def", "__init__", "(", "self", ",", "parent", ",", "title", ",", "_htest", "=", "False", ")", ":", "Toplevel", ".", "__init__", "(", "self", ",", "parent", ")", "self", ".", "configure", "(", "borderwidth", "=", "5", ")", "# place dialog below parent if running htest", "self", ".", "geometry", "(", "\"+%d+%d\"", "%", "(", "parent", ".", "winfo_rootx", "(", ")", "+", "30", ",", "parent", ".", "winfo_rooty", "(", ")", "+", "(", "30", "if", "not", "_htest", "else", "100", ")", ")", ")", "self", ".", "bg", "=", "\"#707070\"", "self", ".", "fg", "=", "\"#ffffff\"", "self", ".", "CreateWidgets", "(", ")", "self", ".", "resizable", "(", "height", "=", "FALSE", ",", "width", "=", "FALSE", ")", "self", ".", "title", "(", "title", ")", "self", ".", "transient", "(", "parent", ")", "self", ".", "grab_set", "(", ")", "self", ".", "protocol", "(", "\"WM_DELETE_WINDOW\"", ",", "self", ".", "Ok", ")", "self", ".", "parent", "=", "parent", "self", ".", "buttonOk", ".", "focus_set", "(", ")", "self", ".", "bind", "(", "'<Return>'", ",", "self", ".", "Ok", ")", "#dismiss dialog", "self", ".", "bind", "(", "'<Escape>'", ",", "self", ".", "Ok", ")", "#dismiss dialog", "self", ".", "wait_window", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/aboutDialog.py#L13-L35
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/margin.py
python
Margin.amount
(self)
return self._amount
Gets the amount of this Margin. # noqa: E501 :return: The amount of this Margin. # noqa: E501 :rtype: float
Gets the amount of this Margin. # noqa: E501
[ "Gets", "the", "amount", "of", "this", "Margin", ".", "#", "noqa", ":", "E501" ]
def amount(self): """Gets the amount of this Margin. # noqa: E501 :return: The amount of this Margin. # noqa: E501 :rtype: float """ return self._amount
[ "def", "amount", "(", "self", ")", ":", "return", "self", ".", "_amount" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/margin.py#L379-L386
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/mox.py
python
Mox.ResetAll
(self)
Call reset on all mock objects. This does not unset stubs.
Call reset on all mock objects. This does not unset stubs.
[ "Call", "reset", "on", "all", "mock", "objects", ".", "This", "does", "not", "unset", "stubs", "." ]
def ResetAll(self): """Call reset on all mock objects. This does not unset stubs.""" for mock_obj in self._mock_objects: mock_obj._Reset()
[ "def", "ResetAll", "(", "self", ")", ":", "for", "mock_obj", "in", "self", ".", "_mock_objects", ":", "mock_obj", ".", "_Reset", "(", ")" ]
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/mox.py#L202-L206
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridCellEditor.Show
(*args, **kwargs)
return _grid.GridCellEditor_Show(*args, **kwargs)
Show(self, bool show, GridCellAttr attr=None)
Show(self, bool show, GridCellAttr attr=None)
[ "Show", "(", "self", "bool", "show", "GridCellAttr", "attr", "=", "None", ")" ]
def Show(*args, **kwargs): """Show(self, bool show, GridCellAttr attr=None)""" return _grid.GridCellEditor_Show(*args, **kwargs)
[ "def", "Show", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellEditor_Show", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L312-L314
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/email/headerregistry.py
python
Address.addr_spec
(self)
return lp
The addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding.
The addr_spec (username
[ "The", "addr_spec", "(", "username" ]
def addr_spec(self): """The addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding. """ lp = self.username if not parser.DOT_ATOM_ENDS.isdisjoint(lp): lp = parser.quote_string(lp) if self.domain: return lp + '@' + self.domain if not lp: return '<>' return lp
[ "def", "addr_spec", "(", "self", ")", ":", "lp", "=", "self", ".", "username", "if", "not", "parser", ".", "DOT_ATOM_ENDS", ".", "isdisjoint", "(", "lp", ")", ":", "lp", "=", "parser", ".", "quote_string", "(", "lp", ")", "if", "self", ".", "domain", ":", "return", "lp", "+", "'@'", "+", "self", ".", "domain", "if", "not", "lp", ":", "return", "'<>'", "return", "lp" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/headerregistry.py#L73-L84
libornovax/master_thesis_code
6eca474ed3cae673afde010caef338cf7349f839
scripts/data/kitti2pgp.py
python
read_camera_matrix
(line)
return P
Reads a camera matrix P (3x4) stored in the row-major scheme. Input: line: Row-major stored matrix separated by spaces, first element is the matrix name Returns: camera matrix P 4x4
Reads a camera matrix P (3x4) stored in the row-major scheme.
[ "Reads", "a", "camera", "matrix", "P", "(", "3x4", ")", "stored", "in", "the", "row", "-", "major", "scheme", "." ]
def read_camera_matrix(line): """ Reads a camera matrix P (3x4) stored in the row-major scheme. Input: line: Row-major stored matrix separated by spaces, first element is the matrix name Returns: camera matrix P 4x4 """ data = line.split(' ') if data[0] != 'P2:': print('ERROR: We need left camera matrix (P2)!') exit(1) P = np.asmatrix([[float(data[1]), float(data[2]), float(data[3]), float(data[4])], [float(data[5]), float(data[6]), float(data[7]), float(data[8])], [float(data[9]), float(data[10]), float(data[11]), float(data[12])]]) return P
[ "def", "read_camera_matrix", "(", "line", ")", ":", "data", "=", "line", ".", "split", "(", "' '", ")", "if", "data", "[", "0", "]", "!=", "'P2:'", ":", "print", "(", "'ERROR: We need left camera matrix (P2)!'", ")", "exit", "(", "1", ")", "P", "=", "np", ".", "asmatrix", "(", "[", "[", "float", "(", "data", "[", "1", "]", ")", ",", "float", "(", "data", "[", "2", "]", ")", ",", "float", "(", "data", "[", "3", "]", ")", ",", "float", "(", "data", "[", "4", "]", ")", "]", ",", "[", "float", "(", "data", "[", "5", "]", ")", ",", "float", "(", "data", "[", "6", "]", ")", ",", "float", "(", "data", "[", "7", "]", ")", ",", "float", "(", "data", "[", "8", "]", ")", "]", ",", "[", "float", "(", "data", "[", "9", "]", ")", ",", "float", "(", "data", "[", "10", "]", ")", ",", "float", "(", "data", "[", "11", "]", ")", ",", "float", "(", "data", "[", "12", "]", ")", "]", "]", ")", "return", "P" ]
https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/data/kitti2pgp.py#L41-L59
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewListCtrl.PrependColumn
(*args, **kwargs)
return _dataview.DataViewListCtrl_PrependColumn(*args, **kwargs)
PrependColumn(self, DataViewColumn column, String varianttype="string") -> bool
PrependColumn(self, DataViewColumn column, String varianttype="string") -> bool
[ "PrependColumn", "(", "self", "DataViewColumn", "column", "String", "varianttype", "=", "string", ")", "-", ">", "bool" ]
def PrependColumn(*args, **kwargs): """PrependColumn(self, DataViewColumn column, String varianttype="string") -> bool""" return _dataview.DataViewListCtrl_PrependColumn(*args, **kwargs)
[ "def", "PrependColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewListCtrl_PrependColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L2121-L2123
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/operator/_abstract_operator.py
python
AbstractOperator.hilbert
(self)
return self._hilbert
r"""The hilbert space associated to this operator.
r"""The hilbert space associated to this operator.
[ "r", "The", "hilbert", "space", "associated", "to", "this", "operator", "." ]
def hilbert(self) -> AbstractHilbert: r"""The hilbert space associated to this operator.""" return self._hilbert
[ "def", "hilbert", "(", "self", ")", "->", "AbstractHilbert", ":", "return", "self", ".", "_hilbert" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/operator/_abstract_operator.py#L35-L37
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/build/property.py
python
PropertyMap.find
(self, properties)
return self.find_replace (properties)
Return the value associated with properties or any subset of it. If more than one subset has value assigned to it, return the value for the longest subset, if it's unique.
Return the value associated with properties or any subset of it. If more than one subset has value assigned to it, return the value for the longest subset, if it's unique.
[ "Return", "the", "value", "associated", "with", "properties", "or", "any", "subset", "of", "it", ".", "If", "more", "than", "one", "subset", "has", "value", "assigned", "to", "it", "return", "the", "value", "for", "the", "longest", "subset", "if", "it", "s", "unique", "." ]
def find (self, properties): """ Return the value associated with properties or any subset of it. If more than one subset has value assigned to it, return the value for the longest subset, if it's unique. """ assert is_iterable_typed(properties, basestring) return self.find_replace (properties)
[ "def", "find", "(", "self", ",", "properties", ")", ":", "assert", "is_iterable_typed", "(", "properties", ",", "basestring", ")", "return", "self", ".", "find_replace", "(", "properties", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/property.py#L598-L605
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.addfile
(self, tarinfo, fileobj=None)
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size.
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size.
[ "Add", "the", "TarInfo", "object", "tarinfo", "to", "the", "archive", ".", "If", "fileobj", "is", "given", "tarinfo", ".", "size", "bytes", "are", "read", "from", "it", "and", "added", "to", "the", "archive", ".", "You", "can", "create", "TarInfo", "objects", "using", "gettarinfo", "()", ".", "On", "Windows", "platforms", "fileobj", "should", "always", "be", "opened", "with", "mode", "rb", "to", "avoid", "irritation", "about", "the", "file", "size", "." ]
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw") tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.format, self.encoding, self.errors) self.fileobj.write(buf) self.offset += len(buf) # If there's data to follow, append it. if fileobj is not None: copyfileobj(fileobj, self.fileobj, tarinfo.size) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE self.members.append(tarinfo)
[ "def", "addfile", "(", "self", ",", "tarinfo", ",", "fileobj", "=", "None", ")", ":", "self", ".", "_check", "(", "\"aw\"", ")", "tarinfo", "=", "copy", ".", "copy", "(", "tarinfo", ")", "buf", "=", "tarinfo", ".", "tobuf", "(", "self", ".", "format", ",", "self", ".", "encoding", ",", "self", ".", "errors", ")", "self", ".", "fileobj", ".", "write", "(", "buf", ")", "self", ".", "offset", "+=", "len", "(", "buf", ")", "# If there's data to follow, append it.", "if", "fileobj", "is", "not", "None", ":", "copyfileobj", "(", "fileobj", ",", "self", ".", "fileobj", ",", "tarinfo", ".", "size", ")", "blocks", ",", "remainder", "=", "divmod", "(", "tarinfo", ".", "size", ",", "BLOCKSIZE", ")", "if", "remainder", ">", "0", ":", "self", ".", "fileobj", ".", "write", "(", "NUL", "*", "(", "BLOCKSIZE", "-", "remainder", ")", ")", "blocks", "+=", "1", "self", ".", "offset", "+=", "blocks", "*", "BLOCKSIZE", "self", ".", "members", ".", "append", "(", "tarinfo", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2100-L2124
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/turnflows.py
python
Turnflows.estimate_entered
(self)
return ids_edge, entered_vec
Estimates the entered number of vehicles for each edge generated by turnflow definitions. Bases are the only the turnflows, not the generated flows (which are not entering an edge). returns ids_edge and entered_vec
Estimates the entered number of vehicles for each edge generated by turnflow definitions. Bases are the only the turnflows, not the generated flows (which are not entering an edge).
[ "Estimates", "the", "entered", "number", "of", "vehicles", "for", "each", "edge", "generated", "by", "turnflow", "definitions", ".", "Bases", "are", "the", "only", "the", "turnflows", "not", "the", "generated", "flows", "(", "which", "are", "not", "entering", "an", "edge", ")", "." ]
def estimate_entered(self): """ Estimates the entered number of vehicles for each edge generated by turnflow definitions. Bases are the only the turnflows, not the generated flows (which are not entering an edge). returns ids_edge and entered_vec """ counter = np.zeros(np.max(self.get_edges().get_ids())+1, int) for id_inter in self.get_ids(): self.turnflowmodes[id_inter].count_entered(counter) ids_edge = np.flatnonzero(counter) entered_vec = counter[ids_edge].copy() return ids_edge, entered_vec
[ "def", "estimate_entered", "(", "self", ")", ":", "counter", "=", "np", ".", "zeros", "(", "np", ".", "max", "(", "self", ".", "get_edges", "(", ")", ".", "get_ids", "(", ")", ")", "+", "1", ",", "int", ")", "for", "id_inter", "in", "self", ".", "get_ids", "(", ")", ":", "self", ".", "turnflowmodes", "[", "id_inter", "]", ".", "count_entered", "(", "counter", ")", "ids_edge", "=", "np", ".", "flatnonzero", "(", "counter", ")", "entered_vec", "=", "counter", "[", "ids_edge", "]", ".", "copy", "(", ")", "return", "ids_edge", ",", "entered_vec" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/turnflows.py#L662-L678
NVIDIAGameWorks/kaolin
e5148d05e9c1e2ce92a07881ce3593b1c5c3f166
kaolin/metrics/render.py
python
mask_iou
(lhs_mask, rhs_mask)
return mask_loss
r"""Compute the Intersection over Union of two segmentation masks. Args: lhs_mask (torch.FloatTensor): A segmentation mask, of shape :math:`(\text{batch_size}, \text{height}, \text{width})`. rhs_mask (torch.FloatTensor): A segmentation mask, of shape :math:`(\text{batch_size}, \text{height}, \text{width})`. Returns: (torch.FloatTensor): The IoU loss, as a torch scalar.
r"""Compute the Intersection over Union of two segmentation masks.
[ "r", "Compute", "the", "Intersection", "over", "Union", "of", "two", "segmentation", "masks", "." ]
def mask_iou(lhs_mask, rhs_mask): r"""Compute the Intersection over Union of two segmentation masks. Args: lhs_mask (torch.FloatTensor): A segmentation mask, of shape :math:`(\text{batch_size}, \text{height}, \text{width})`. rhs_mask (torch.FloatTensor): A segmentation mask, of shape :math:`(\text{batch_size}, \text{height}, \text{width})`. Returns: (torch.FloatTensor): The IoU loss, as a torch scalar. """ batch_size, height, width = lhs_mask.shape assert rhs_mask.shape == lhs_mask.shape sil_mul = lhs_mask * rhs_mask sil_add = lhs_mask + rhs_mask iou_up = torch.sum(sil_mul.reshape(batch_size, -1), dim=1) iou_down = torch.sum((sil_add - sil_mul).reshape(batch_size, -1), dim=1) iou_neg = iou_up / (iou_down + 1e-10) mask_loss = 1.0 - torch.mean(iou_neg) return mask_loss
[ "def", "mask_iou", "(", "lhs_mask", ",", "rhs_mask", ")", ":", "batch_size", ",", "height", ",", "width", "=", "lhs_mask", ".", "shape", "assert", "rhs_mask", ".", "shape", "==", "lhs_mask", ".", "shape", "sil_mul", "=", "lhs_mask", "*", "rhs_mask", "sil_add", "=", "lhs_mask", "+", "rhs_mask", "iou_up", "=", "torch", ".", "sum", "(", "sil_mul", ".", "reshape", "(", "batch_size", ",", "-", "1", ")", ",", "dim", "=", "1", ")", "iou_down", "=", "torch", ".", "sum", "(", "(", "sil_add", "-", "sil_mul", ")", ".", "reshape", "(", "batch_size", ",", "-", "1", ")", ",", "dim", "=", "1", ")", "iou_neg", "=", "iou_up", "/", "(", "iou_down", "+", "1e-10", ")", "mask_loss", "=", "1.0", "-", "torch", ".", "mean", "(", "iou_neg", ")", "return", "mask_loss" ]
https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/metrics/render.py#L18-L40
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiToolBarItem.SetId
(*args, **kwargs)
return _aui.AuiToolBarItem_SetId(*args, **kwargs)
SetId(self, int newId)
SetId(self, int newId)
[ "SetId", "(", "self", "int", "newId", ")" ]
def SetId(*args, **kwargs): """SetId(self, int newId)""" return _aui.AuiToolBarItem_SetId(*args, **kwargs)
[ "def", "SetId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBarItem_SetId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1737-L1739
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py
python
TurtleScreen.clear
(self)
Delete all drawings and all turtles from the TurtleScreen. Reset empty TurtleScreen to its initial state: white background, no backgroundimage, no eventbindings and tracing on. No argument. Example (for a TurtleScreen instance named screen): >>> screen.clear() Note: this method is not available as function.
Delete all drawings and all turtles from the TurtleScreen.
[ "Delete", "all", "drawings", "and", "all", "turtles", "from", "the", "TurtleScreen", "." ]
def clear(self): """Delete all drawings and all turtles from the TurtleScreen. Reset empty TurtleScreen to its initial state: white background, no backgroundimage, no eventbindings and tracing on. No argument. Example (for a TurtleScreen instance named screen): >>> screen.clear() Note: this method is not available as function. """ self._delayvalue = _CFG["delay"] self._colormode = _CFG["colormode"] self._delete("all") self._bgpic = self._createimage("") self._bgpicname = "nopic" self._tracing = 1 self._updatecounter = 0 self._turtles = [] self.bgcolor("white") for btn in 1, 2, 3: self.onclick(None, btn) for key in self._keys[:]: self.onkey(None, key) Turtle._pen = None
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_delayvalue", "=", "_CFG", "[", "\"delay\"", "]", "self", ".", "_colormode", "=", "_CFG", "[", "\"colormode\"", "]", "self", ".", "_delete", "(", "\"all\"", ")", "self", ".", "_bgpic", "=", "self", ".", "_createimage", "(", "\"\"", ")", "self", ".", "_bgpicname", "=", "\"nopic\"", "self", ".", "_tracing", "=", "1", "self", ".", "_updatecounter", "=", "0", "self", ".", "_turtles", "=", "[", "]", "self", ".", "bgcolor", "(", "\"white\"", ")", "for", "btn", "in", "1", ",", "2", ",", "3", ":", "self", ".", "onclick", "(", "None", ",", "btn", ")", "for", "key", "in", "self", ".", "_keys", "[", ":", "]", ":", "self", ".", "onkey", "(", "None", ",", "key", ")", "Turtle", ".", "_pen", "=", "None" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L952-L978
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
BookCtrlBase.GetSelection
(*args, **kwargs)
return _core_.BookCtrlBase_GetSelection(*args, **kwargs)
GetSelection(self) -> int
GetSelection(self) -> int
[ "GetSelection", "(", "self", ")", "-", ">", "int" ]
def GetSelection(*args, **kwargs): """GetSelection(self) -> int""" return _core_.BookCtrlBase_GetSelection(*args, **kwargs)
[ "def", "GetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BookCtrlBase_GetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L13550-L13552
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py
python
describe
(thing)
return type(thing).__name__
Produce a short description of the given thing.
Produce a short description of the given thing.
[ "Produce", "a", "short", "description", "of", "the", "given", "thing", "." ]
def describe(thing): """Produce a short description of the given thing.""" if inspect.ismodule(thing): if thing.__name__ in sys.builtin_module_names: return 'built-in module ' + thing.__name__ if hasattr(thing, '__path__'): return 'package ' + thing.__name__ else: return 'module ' + thing.__name__ if inspect.isbuiltin(thing): return 'built-in function ' + thing.__name__ if inspect.isgetsetdescriptor(thing): return 'getset descriptor %s.%s.%s' % ( thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__) if inspect.ismemberdescriptor(thing): return 'member descriptor %s.%s.%s' % ( thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__) if inspect.isclass(thing): return 'class ' + thing.__name__ if inspect.isfunction(thing): return 'function ' + thing.__name__ if inspect.ismethod(thing): return 'method ' + thing.__name__ if type(thing) is types.InstanceType: return 'instance of ' + thing.__class__.__name__ return type(thing).__name__
[ "def", "describe", "(", "thing", ")", ":", "if", "inspect", ".", "ismodule", "(", "thing", ")", ":", "if", "thing", ".", "__name__", "in", "sys", ".", "builtin_module_names", ":", "return", "'built-in module '", "+", "thing", ".", "__name__", "if", "hasattr", "(", "thing", ",", "'__path__'", ")", ":", "return", "'package '", "+", "thing", ".", "__name__", "else", ":", "return", "'module '", "+", "thing", ".", "__name__", "if", "inspect", ".", "isbuiltin", "(", "thing", ")", ":", "return", "'built-in function '", "+", "thing", ".", "__name__", "if", "inspect", ".", "isgetsetdescriptor", "(", "thing", ")", ":", "return", "'getset descriptor %s.%s.%s'", "%", "(", "thing", ".", "__objclass__", ".", "__module__", ",", "thing", ".", "__objclass__", ".", "__name__", ",", "thing", ".", "__name__", ")", "if", "inspect", ".", "ismemberdescriptor", "(", "thing", ")", ":", "return", "'member descriptor %s.%s.%s'", "%", "(", "thing", ".", "__objclass__", ".", "__module__", ",", "thing", ".", "__objclass__", ".", "__name__", ",", "thing", ".", "__name__", ")", "if", "inspect", ".", "isclass", "(", "thing", ")", ":", "return", "'class '", "+", "thing", ".", "__name__", "if", "inspect", ".", "isfunction", "(", "thing", ")", ":", "return", "'function '", "+", "thing", ".", "__name__", "if", "inspect", ".", "ismethod", "(", "thing", ")", ":", "return", "'method '", "+", "thing", ".", "__name__", "if", "type", "(", "thing", ")", "is", "types", ".", "InstanceType", ":", "return", "'instance of '", "+", "thing", ".", "__class__", ".", "__name__", "return", "type", "(", "thing", ")", ".", "__name__" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py#L1437-L1464
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_i18n.py
python
LangListCombo.__init__
(self, parent, id_, default=None)
Creates a combobox with a list of all translations for the editor as well as displaying the countries flag next to the item in the list. @param default: The default item to show in the combo box
Creates a combobox with a list of all translations for the editor as well as displaying the countries flag next to the item in the list.
[ "Creates", "a", "combobox", "with", "a", "list", "of", "all", "translations", "for", "the", "editor", "as", "well", "as", "displaying", "the", "countries", "flag", "next", "to", "the", "item", "in", "the", "list", "." ]
def __init__(self, parent, id_, default=None): """Creates a combobox with a list of all translations for the editor as well as displaying the countries flag next to the item in the list. @param default: The default item to show in the combo box """ lang_ids = GetLocaleDict(GetAvailLocales()).values() lang_items = langlist.CreateLanguagesResourceLists(langlist.LC_ONLY, \ lang_ids) wx.combo.BitmapComboBox.__init__(self, parent, id_, size=wx.Size(250, 26), style=wx.CB_READONLY) for lang_d in lang_items[1]: bit_m = lang_items[0].GetBitmap(lang_items[1].index(lang_d)) self.Append(lang_d, bit_m) if default: self.SetValue(default)
[ "def", "__init__", "(", "self", ",", "parent", ",", "id_", ",", "default", "=", "None", ")", ":", "lang_ids", "=", "GetLocaleDict", "(", "GetAvailLocales", "(", ")", ")", ".", "values", "(", ")", "lang_items", "=", "langlist", ".", "CreateLanguagesResourceLists", "(", "langlist", ".", "LC_ONLY", ",", "lang_ids", ")", "wx", ".", "combo", ".", "BitmapComboBox", ".", "__init__", "(", "self", ",", "parent", ",", "id_", ",", "size", "=", "wx", ".", "Size", "(", "250", ",", "26", ")", ",", "style", "=", "wx", ".", "CB_READONLY", ")", "for", "lang_d", "in", "lang_items", "[", "1", "]", ":", "bit_m", "=", "lang_items", "[", "0", "]", ".", "GetBitmap", "(", "lang_items", "[", "1", "]", ".", "index", "(", "lang_d", ")", ")", "self", ".", "Append", "(", "lang_d", ",", "bit_m", ")", "if", "default", ":", "self", ".", "SetValue", "(", "default", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_i18n.py#L103-L122
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/_psbsd.py
python
Process.get_open_files
(self)
Return files opened by process as a list of namedtuples.
Return files opened by process as a list of namedtuples.
[ "Return", "files", "opened", "by", "process", "as", "a", "list", "of", "namedtuples", "." ]
def get_open_files(self): """Return files opened by process as a list of namedtuples.""" # XXX - C implementation available on FreeBSD >= 8 only # else fallback on lsof parser if hasattr(_psutil_bsd, "get_process_open_files"): rawlist = _psutil_bsd.get_process_open_files(self.pid) return [nt_openfile(path, fd) for path, fd in rawlist] else: lsof = _psposix.LsofParser(self.pid, self._process_name) return lsof.get_process_open_files()
[ "def", "get_open_files", "(", "self", ")", ":", "# XXX - C implementation available on FreeBSD >= 8 only", "# else fallback on lsof parser", "if", "hasattr", "(", "_psutil_bsd", ",", "\"get_process_open_files\"", ")", ":", "rawlist", "=", "_psutil_bsd", ".", "get_process_open_files", "(", "self", ".", "pid", ")", "return", "[", "nt_openfile", "(", "path", ",", "fd", ")", "for", "path", ",", "fd", "in", "rawlist", "]", "else", ":", "lsof", "=", "_psposix", ".", "LsofParser", "(", "self", ".", "pid", ",", "self", ".", "_process_name", ")", "return", "lsof", ".", "get_process_open_files", "(", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_psbsd.py#L295-L304
SGL-UT/GPSTk
2340ec1cbdbd0b80a204920127798697bc616b30
swig/doxy2swig.py
python
Doxy2SWIG.generate
(self)
Parses the file set in the initialization. The resulting data is stored in `self.pieces`.
Parses the file set in the initialization. The resulting data is stored in `self.pieces`.
[ "Parses", "the", "file", "set", "in", "the", "initialization", ".", "The", "resulting", "data", "is", "stored", "in", "self", ".", "pieces", "." ]
def generate(self): """Parses the file set in the initialization. The resulting data is stored in `self.pieces`. """ self.parse(self.xmldoc)
[ "def", "generate", "(", "self", ")", ":", "self", ".", "parse", "(", "self", ".", "xmldoc", ")" ]
https://github.com/SGL-UT/GPSTk/blob/2340ec1cbdbd0b80a204920127798697bc616b30/swig/doxy2swig.py#L97-L102
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/utils/runtime_info.py
python
RTInfoElement.get_name
(self)
Get name of RTInfoElement.
Get name of RTInfoElement.
[ "Get", "name", "of", "RTInfoElement", "." ]
def get_name(self): """ Get name of RTInfoElement. """
[ "def", "get_name", "(", "self", ")", ":" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/runtime_info.py#L62-L65
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
lldb/examples/python/in_call_stack.py
python
in_call_stack
(frame, bp_loc, arg_dict, _)
return False
Only break if the given name is in the current call stack.
Only break if the given name is in the current call stack.
[ "Only", "break", "if", "the", "given", "name", "is", "in", "the", "current", "call", "stack", "." ]
def in_call_stack(frame, bp_loc, arg_dict, _): """Only break if the given name is in the current call stack.""" name = arg_dict.GetValueForKey('name').GetStringValue(1000) thread = frame.GetThread() found = False for frame in thread.frames: # Check the symbol. symbol = frame.GetSymbol() if symbol and name in frame.GetSymbol().GetName(): return True # Check the function. function = frame.GetFunction() if function and name in function.GetName(): return True return False
[ "def", "in_call_stack", "(", "frame", ",", "bp_loc", ",", "arg_dict", ",", "_", ")", ":", "name", "=", "arg_dict", ".", "GetValueForKey", "(", "'name'", ")", ".", "GetStringValue", "(", "1000", ")", "thread", "=", "frame", ".", "GetThread", "(", ")", "found", "=", "False", "for", "frame", "in", "thread", ".", "frames", ":", "# Check the symbol.", "symbol", "=", "frame", ".", "GetSymbol", "(", ")", "if", "symbol", "and", "name", "in", "frame", ".", "GetSymbol", "(", ")", ".", "GetName", "(", ")", ":", "return", "True", "# Check the function.", "function", "=", "frame", ".", "GetFunction", "(", ")", "if", "function", "and", "name", "in", "function", ".", "GetName", "(", ")", ":", "return", "True", "return", "False" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/examples/python/in_call_stack.py#L10-L24
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/latex.py
python
RowStringConverter.index_levels
(self)
return self.frame.index.nlevels
Integer number of levels in index.
Integer number of levels in index.
[ "Integer", "number", "of", "levels", "in", "index", "." ]
def index_levels(self) -> int: """Integer number of levels in index.""" return self.frame.index.nlevels
[ "def", "index_levels", "(", "self", ")", "->", "int", ":", "return", "self", ".", "frame", ".", "index", ".", "nlevels" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/latex.py#L125-L127
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/MetaSearch/util.py
python
normalize_text
(text)
return text.replace('\n', '')
tidy up string
tidy up string
[ "tidy", "up", "string" ]
def normalize_text(text): """tidy up string""" return text.replace('\n', '')
[ "def", "normalize_text", "(", "text", ")", ":", "return", "text", ".", "replace", "(", "'\\n'", ",", "''", ")" ]
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/MetaSearch/util.py#L156-L159
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/weakref.py
python
finalize.__call__
(self, _=None)
If alive then mark as dead and return func(*args, **kwargs); otherwise return None
If alive then mark as dead and return func(*args, **kwargs); otherwise return None
[ "If", "alive", "then", "mark", "as", "dead", "and", "return", "func", "(", "*", "args", "**", "kwargs", ")", ";", "otherwise", "return", "None" ]
def __call__(self, _=None): """If alive then mark as dead and return func(*args, **kwargs); otherwise return None""" info = self._registry.pop(self, None) if info and not self._shutdown: return info.func(*info.args, **(info.kwargs or {}))
[ "def", "__call__", "(", "self", ",", "_", "=", "None", ")", ":", "info", "=", "self", ".", "_registry", ".", "pop", "(", "self", ",", "None", ")", "if", "info", "and", "not", "self", ".", "_shutdown", ":", "return", "info", ".", "func", "(", "*", "info", ".", "args", ",", "*", "*", "(", "info", ".", "kwargs", "or", "{", "}", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/weakref.py#L567-L572
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/jinja2/runtime.py
python
BlockReference.super
(self)
return BlockReference(self.name, self._context, self._stack, self._depth + 1)
Super the block.
Super the block.
[ "Super", "the", "block", "." ]
def super(self): """Super the block.""" if self._depth + 1 >= len(self._stack): return self._context.environment. \ undefined('there is no parent block called %r.' % self.name, name='super') return BlockReference(self.name, self._context, self._stack, self._depth + 1)
[ "def", "super", "(", "self", ")", ":", "if", "self", ".", "_depth", "+", "1", ">=", "len", "(", "self", ".", "_stack", ")", ":", "return", "self", ".", "_context", ".", "environment", ".", "undefined", "(", "'there is no parent block called %r.'", "%", "self", ".", "name", ",", "name", "=", "'super'", ")", "return", "BlockReference", "(", "self", ".", "name", ",", "self", ".", "_context", ",", "self", ".", "_stack", ",", "self", ".", "_depth", "+", "1", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/runtime.py#L334-L341
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/MSCommon/common.py
python
is_win64
()
return _is_win64
Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.
Return true if running on windows 64 bits.
[ "Return", "true", "if", "running", "on", "windows", "64", "bits", "." ]
def is_win64(): """Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.""" # Unfortunately, python does not provide a useful way to determine # if the underlying Windows OS is 32-bit or 64-bit. Worse, whether # the Python itself is 32-bit or 64-bit affects what it returns, # so nothing in sys.* or os.* help. # Apparently the best solution is to use env vars that Windows # sets. If PROCESSOR_ARCHITECTURE is not x86, then the python # process is running in 64 bit mode (on a 64-bit OS, 64-bit # hardware, obviously). # If this python is 32-bit but the OS is 64, Windows will set # ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null. # (Checking for HKLM\Software\Wow6432Node in the registry doesn't # work, because some 32-bit installers create it.) global _is_win64 if _is_win64 is None: # I structured these tests to make it easy to add new ones or # add exceptions in the future, because this is a bit fragile. _is_win64 = False if os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') != 'x86': _is_win64 = True if os.environ.get('PROCESSOR_ARCHITEW6432'): _is_win64 = True if os.environ.get('ProgramW6432'): _is_win64 = True return _is_win64
[ "def", "is_win64", "(", ")", ":", "# Unfortunately, python does not provide a useful way to determine", "# if the underlying Windows OS is 32-bit or 64-bit. Worse, whether", "# the Python itself is 32-bit or 64-bit affects what it returns,", "# so nothing in sys.* or os.* help.", "# Apparently the best solution is to use env vars that Windows", "# sets. If PROCESSOR_ARCHITECTURE is not x86, then the python", "# process is running in 64 bit mode (on a 64-bit OS, 64-bit", "# hardware, obviously).", "# If this python is 32-bit but the OS is 64, Windows will set", "# ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null.", "# (Checking for HKLM\\Software\\Wow6432Node in the registry doesn't", "# work, because some 32-bit installers create it.)", "global", "_is_win64", "if", "_is_win64", "is", "None", ":", "# I structured these tests to make it easy to add new ones or", "# add exceptions in the future, because this is a bit fragile.", "_is_win64", "=", "False", "if", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITECTURE'", ",", "'x86'", ")", "!=", "'x86'", ":", "_is_win64", "=", "True", "if", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITEW6432'", ")", ":", "_is_win64", "=", "True", "if", "os", ".", "environ", ".", "get", "(", "'ProgramW6432'", ")", ":", "_is_win64", "=", "True", "return", "_is_win64" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/MSCommon/common.py#L56-L84
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/convert_to_constants.py
python
convert_variables_to_constants_from_session_graph
( session, graph_def, output_node_names, variable_names_allowlist=None, variable_names_denylist=None)
return graph_def
Replaces all the variables in a graph with constants of the same values. This function works similarly to convert_variables_to_constants_v2, but it retrieves the constant values from a Session instead of from a ConcreteFunction. This is useful when converting graphs generated from TensorFlow V1, where ConcreteFunctions are not available. This also differs from graph_util.convert_variables_to_constants in that it supports resource variables when V2 control flow constructions are present. Args: session: Active TensorFlow session containing the variables. graph_def: A GraphDef to convert. output_node_names: List of name strings for the result nodes of the graph. variable_names_allowlist: The set of variable names to convert (by default, all variables are converted). variable_names_denylist: The set of variable names to omit converting to constants. Returns: An optimized GraphDef.
Replaces all the variables in a graph with constants of the same values.
[ "Replaces", "all", "the", "variables", "in", "a", "graph", "with", "constants", "of", "the", "same", "values", "." ]
def convert_variables_to_constants_from_session_graph( session, graph_def, output_node_names, variable_names_allowlist=None, variable_names_denylist=None): """Replaces all the variables in a graph with constants of the same values. This function works similarly to convert_variables_to_constants_v2, but it retrieves the constant values from a Session instead of from a ConcreteFunction. This is useful when converting graphs generated from TensorFlow V1, where ConcreteFunctions are not available. This also differs from graph_util.convert_variables_to_constants in that it supports resource variables when V2 control flow constructions are present. Args: session: Active TensorFlow session containing the variables. graph_def: A GraphDef to convert. output_node_names: List of name strings for the result nodes of the graph. variable_names_allowlist: The set of variable names to convert (by default, all variables are converted). variable_names_denylist: The set of variable names to omit converting to constants. Returns: An optimized GraphDef. """ # TODO(b/176982859): Find a more satisfying way to update shape information # than clearing it, or migrate users to a workflow that does not require # freezing. for function in graph_def.library.function: if "_input_shapes" in function.attr: for input_arg, shape_attribute in zip( function.signature.input_arg, function.attr["_input_shapes"].list.shape): if dtypes.as_dtype(input_arg.type) == dtypes.resource: shape_attribute.unknown_rank = True graph_def, _ = _replace_variables_by_constants( converter_data=_SessionConverterData( session=session, graph_def=graph_def, output_node_names=output_node_names, variable_names_allowlist=variable_names_allowlist, variable_names_denylist=variable_names_denylist)) return graph_def
[ "def", "convert_variables_to_constants_from_session_graph", "(", "session", ",", "graph_def", ",", "output_node_names", ",", "variable_names_allowlist", "=", "None", ",", "variable_names_denylist", "=", "None", ")", ":", "# TODO(b/176982859): Find a more satisfying way to update shape information", "# than clearing it, or migrate users to a workflow that does not require", "# freezing.", "for", "function", "in", "graph_def", ".", "library", ".", "function", ":", "if", "\"_input_shapes\"", "in", "function", ".", "attr", ":", "for", "input_arg", ",", "shape_attribute", "in", "zip", "(", "function", ".", "signature", ".", "input_arg", ",", "function", ".", "attr", "[", "\"_input_shapes\"", "]", ".", "list", ".", "shape", ")", ":", "if", "dtypes", ".", "as_dtype", "(", "input_arg", ".", "type", ")", "==", "dtypes", ".", "resource", ":", "shape_attribute", ".", "unknown_rank", "=", "True", "graph_def", ",", "_", "=", "_replace_variables_by_constants", "(", "converter_data", "=", "_SessionConverterData", "(", "session", "=", "session", ",", "graph_def", "=", "graph_def", ",", "output_node_names", "=", "output_node_names", ",", "variable_names_allowlist", "=", "variable_names_allowlist", ",", "variable_names_denylist", "=", "variable_names_denylist", ")", ")", "return", "graph_def" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/convert_to_constants.py#L1237-L1281
nileshkulkarni/csm
0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc
csm/nnutils/train_utils.py
python
Trainer.define_criterion
(self)
Should be implemented by the child class.
Should be implemented by the child class.
[ "Should", "be", "implemented", "by", "the", "child", "class", "." ]
def define_criterion(self): '''Should be implemented by the child class.''' raise NotImplementedError
[ "def", "define_criterion", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/nnutils/train_utils.py#L106-L108
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/hmac.py
python
HMAC.digest
(self)
return h.digest()
Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function.
Return the hash value of this hashing object.
[ "Return", "the", "hash", "value", "of", "this", "hashing", "object", "." ]
def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self._current() return h.digest()
[ "def", "digest", "(", "self", ")", ":", "h", "=", "self", ".", "_current", "(", ")", "return", "h", ".", "digest", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/hmac.py#L106-L114
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBDebugger.RunCommandInterpreter
(self, auto_handle_events, spawn_thread, options, num_errors, quit_requested, stopped_for_crash)
return _lldb.SBDebugger_RunCommandInterpreter(self, auto_handle_events, spawn_thread, options, num_errors, quit_requested, stopped_for_crash)
RunCommandInterpreter(SBDebugger self, bool auto_handle_events, bool spawn_thread, SBCommandInterpreterRunOptions options, int & num_errors, bool & quit_requested, bool & stopped_for_crash) Launch a command interpreter session. Commands are read from standard input or from the input handle specified for the debugger object. Output/errors are similarly redirected to standard output/error or the configured handles. @param[in] auto_handle_events If true, automatically handle resulting events. @param[in] spawn_thread If true, start a new thread for IO handling. @param[in] options Parameter collection of type SBCommandInterpreterRunOptions. @param[in] num_errors Initial error counter. @param[in] quit_requested Initial quit request flag. @param[in] stopped_for_crash Initial crash flag. @return A tuple with the number of errors encountered by the interpreter, a boolean indicating whether quitting the interpreter was requested and another boolean set to True in case of a crash. Example: # Start an interactive lldb session from a script (with a valid debugger object # created beforehand): n_errors, quit_requested, has_crashed = debugger.RunCommandInterpreter(True, False, lldb.SBCommandInterpreterRunOptions(), 0, False, False)
RunCommandInterpreter(SBDebugger self, bool auto_handle_events, bool spawn_thread, SBCommandInterpreterRunOptions options, int & num_errors, bool & quit_requested, bool & stopped_for_crash)
[ "RunCommandInterpreter", "(", "SBDebugger", "self", "bool", "auto_handle_events", "bool", "spawn_thread", "SBCommandInterpreterRunOptions", "options", "int", "&", "num_errors", "bool", "&", "quit_requested", "bool", "&", "stopped_for_crash", ")" ]
def RunCommandInterpreter(self, auto_handle_events, spawn_thread, options, num_errors, quit_requested, stopped_for_crash): """ RunCommandInterpreter(SBDebugger self, bool auto_handle_events, bool spawn_thread, SBCommandInterpreterRunOptions options, int & num_errors, bool & quit_requested, bool & stopped_for_crash) Launch a command interpreter session. Commands are read from standard input or from the input handle specified for the debugger object. Output/errors are similarly redirected to standard output/error or the configured handles. @param[in] auto_handle_events If true, automatically handle resulting events. @param[in] spawn_thread If true, start a new thread for IO handling. @param[in] options Parameter collection of type SBCommandInterpreterRunOptions. @param[in] num_errors Initial error counter. @param[in] quit_requested Initial quit request flag. @param[in] stopped_for_crash Initial crash flag. @return A tuple with the number of errors encountered by the interpreter, a boolean indicating whether quitting the interpreter was requested and another boolean set to True in case of a crash. Example: # Start an interactive lldb session from a script (with a valid debugger object # created beforehand): n_errors, quit_requested, has_crashed = debugger.RunCommandInterpreter(True, False, lldb.SBCommandInterpreterRunOptions(), 0, False, False) """ return _lldb.SBDebugger_RunCommandInterpreter(self, auto_handle_events, spawn_thread, options, num_errors, quit_requested, stopped_for_crash)
[ "def", "RunCommandInterpreter", "(", "self", ",", "auto_handle_events", ",", "spawn_thread", ",", "options", ",", "num_errors", ",", "quit_requested", ",", "stopped_for_crash", ")", ":", "return", "_lldb", ".", "SBDebugger_RunCommandInterpreter", "(", "self", ",", "auto_handle_events", ",", "spawn_thread", ",", "options", ",", "num_errors", ",", "quit_requested", ",", "stopped_for_crash", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L4287-L4314
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow2/load.py
python
TF2Loader._graph_def_from_model
(self, outputs=None)
Overwrites TFLoader._graph_def_from_model()
Overwrites TFLoader._graph_def_from_model()
[ "Overwrites", "TFLoader", ".", "_graph_def_from_model", "()" ]
def _graph_def_from_model(self, outputs=None): """Overwrites TFLoader._graph_def_from_model()""" msg = ( "Expected model format: [SavedModel | [concrete_function] | " "tf.keras.Model | .h5], got {}" ) if ( isinstance(self.model, list) or isinstance(self.model, _tf.keras.Model) or isinstance(self.model, _string_types) ): cfs = [] if isinstance(self.model, list): cfs = self.model if isinstance(self.model, _tf.keras.Model): cfs = self._concrete_fn_from_tf_keras_or_h5(self.model) elif isinstance(self.model, _string_types): if not _os_path.exists(self.model): raise ValueError( 'Input model "{}" does not exist'.format(self.model) ) elif _os_path.isfile(self.model) and self.model.endswith(".h5"): cfs = self._concrete_fn_from_tf_keras_or_h5(self.model) elif _os_path.isdir(self.model): saved_model = _tf.saved_model.load(self.model) sv = saved_model.signatures.values() cfs = sv if isinstance(sv, list) else list(sv) else: raise NotImplementedError(msg.format(self.model)) graph_def = self._graph_def_from_concrete_fn(cfs) return self.extract_sub_graph(graph_def, outputs) else: raise NotImplementedError(msg.format(self.model))
[ "def", "_graph_def_from_model", "(", "self", ",", "outputs", "=", "None", ")", ":", "msg", "=", "(", "\"Expected model format: [SavedModel | [concrete_function] | \"", "\"tf.keras.Model | .h5], got {}\"", ")", "if", "(", "isinstance", "(", "self", ".", "model", ",", "list", ")", "or", "isinstance", "(", "self", ".", "model", ",", "_tf", ".", "keras", ".", "Model", ")", "or", "isinstance", "(", "self", ".", "model", ",", "_string_types", ")", ")", ":", "cfs", "=", "[", "]", "if", "isinstance", "(", "self", ".", "model", ",", "list", ")", ":", "cfs", "=", "self", ".", "model", "if", "isinstance", "(", "self", ".", "model", ",", "_tf", ".", "keras", ".", "Model", ")", ":", "cfs", "=", "self", ".", "_concrete_fn_from_tf_keras_or_h5", "(", "self", ".", "model", ")", "elif", "isinstance", "(", "self", ".", "model", ",", "_string_types", ")", ":", "if", "not", "_os_path", ".", "exists", "(", "self", ".", "model", ")", ":", "raise", "ValueError", "(", "'Input model \"{}\" does not exist'", ".", "format", "(", "self", ".", "model", ")", ")", "elif", "_os_path", ".", "isfile", "(", "self", ".", "model", ")", "and", "self", ".", "model", ".", "endswith", "(", "\".h5\"", ")", ":", "cfs", "=", "self", ".", "_concrete_fn_from_tf_keras_or_h5", "(", "self", ".", "model", ")", "elif", "_os_path", ".", "isdir", "(", "self", ".", "model", ")", ":", "saved_model", "=", "_tf", ".", "saved_model", ".", "load", "(", "self", ".", "model", ")", "sv", "=", "saved_model", ".", "signatures", ".", "values", "(", ")", "cfs", "=", "sv", "if", "isinstance", "(", "sv", ",", "list", ")", "else", "list", "(", "sv", ")", "else", ":", "raise", "NotImplementedError", "(", "msg", ".", "format", "(", "self", ".", "model", ")", ")", "graph_def", "=", "self", ".", "_graph_def_from_concrete_fn", "(", "cfs", ")", "return", "self", ".", "extract_sub_graph", "(", "graph_def", ",", "outputs", ")", "else", ":", "raise", "NotImplementedError", "(", "msg", ".", "format", "(", "self", ".", "model", ")", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow2/load.py#L77-L110