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
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/factorization/python/ops/factorization_ops.py
python
WALSModel.col_weights
(self)
return self._col_weights
Returns a list of tensors corresponding to col weight shards.
Returns a list of tensors corresponding to col weight shards.
[ "Returns", "a", "list", "of", "tensors", "corresponding", "to", "col", "weight", "shards", "." ]
def col_weights(self): """Returns a list of tensors corresponding to col weight shards.""" return self._col_weights
[ "def", "col_weights", "(", "self", ")", ":", "return", "self", ".", "_col_weights" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L314-L316
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/utils/tensorboard/writer.py
python
SummaryWriter.add_scalars
(self, main_tag, tag_scalar_dict, global_step=None, walltime=None)
Adds many scalar data to summary. Args: main_tag (string): The parent name for the tags tag_scalar_dict (dict): Key-value pair storing the tag and corresponding values global_step (int): Global step value to record walltime (float): Optional override default walltime (time.time()) seconds after epoch of event Examples:: from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter() r = 5 for i in range(100): writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r), 'xcosx':i*np.cos(i/r), 'tanx': np.tan(i/r)}, i) writer.close() # This call adds three values to the same scalar plot with the tag # 'run_14h' in TensorBoard's scalar section. Expected result: .. image:: _static/img/tensorboard/add_scalars.png :scale: 50 %
Adds many scalar data to summary.
[ "Adds", "many", "scalar", "data", "to", "summary", "." ]
def add_scalars(self, main_tag, tag_scalar_dict, global_step=None, walltime=None): """Adds many scalar data to summary. Args: main_tag (string): The parent name for the tags tag_scalar_dict (dict): Key-value pair storing the tag and corresponding values global_step (int): Global step value to record walltime (float): Optional override default walltime (time.time()) seconds after epoch of event Examples:: from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter() r = 5 for i in range(100): writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r), 'xcosx':i*np.cos(i/r), 'tanx': np.tan(i/r)}, i) writer.close() # This call adds three values to the same scalar plot with the tag # 'run_14h' in TensorBoard's scalar section. Expected result: .. image:: _static/img/tensorboard/add_scalars.png :scale: 50 % """ torch._C._log_api_usage_once("tensorboard.logging.add_scalars") walltime = time.time() if walltime is None else walltime fw_logdir = self._get_file_writer().get_logdir() for tag, scalar_value in tag_scalar_dict.items(): fw_tag = fw_logdir + "/" + main_tag.replace("/", "_") + "_" + tag assert self.all_writers is not None if fw_tag in self.all_writers.keys(): fw = self.all_writers[fw_tag] else: fw = FileWriter(fw_tag, self.max_queue, self.flush_secs, self.filename_suffix) self.all_writers[fw_tag] = fw if self._check_caffe2_blob(scalar_value): from caffe2.python import workspace scalar_value = workspace.FetchBlob(scalar_value) fw.add_summary(scalar(main_tag, scalar_value), global_step, walltime)
[ "def", "add_scalars", "(", "self", ",", "main_tag", ",", "tag_scalar_dict", ",", "global_step", "=", "None", ",", "walltime", "=", "None", ")", ":", "torch", ".", "_C", ".", "_log_api_usage_once", "(", "\"tensorboard.logging.add_scalars\"", ")", "walltime", "=", "time", ".", "time", "(", ")", "if", "walltime", "is", "None", "else", "walltime", "fw_logdir", "=", "self", ".", "_get_file_writer", "(", ")", ".", "get_logdir", "(", ")", "for", "tag", ",", "scalar_value", "in", "tag_scalar_dict", ".", "items", "(", ")", ":", "fw_tag", "=", "fw_logdir", "+", "\"/\"", "+", "main_tag", ".", "replace", "(", "\"/\"", ",", "\"_\"", ")", "+", "\"_\"", "+", "tag", "assert", "self", ".", "all_writers", "is", "not", "None", "if", "fw_tag", "in", "self", ".", "all_writers", ".", "keys", "(", ")", ":", "fw", "=", "self", ".", "all_writers", "[", "fw_tag", "]", "else", ":", "fw", "=", "FileWriter", "(", "fw_tag", ",", "self", ".", "max_queue", ",", "self", ".", "flush_secs", ",", "self", ".", "filename_suffix", ")", "self", ".", "all_writers", "[", "fw_tag", "]", "=", "fw", "if", "self", ".", "_check_caffe2_blob", "(", "scalar_value", ")", ":", "from", "caffe2", ".", "python", "import", "workspace", "scalar_value", "=", "workspace", ".", "FetchBlob", "(", "scalar_value", ")", "fw", ".", "add_summary", "(", "scalar", "(", "main_tag", ",", "scalar_value", ")", ",", "global_step", ",", "walltime", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/tensorboard/writer.py#L359-L404
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py
python
_ClassBuilder._add_method_dunders
(self, method)
return method
Add __module__ and __qualname__ to a *method* if possible.
Add __module__ and __qualname__ to a *method* if possible.
[ "Add", "__module__", "and", "__qualname__", "to", "a", "*", "method", "*", "if", "possible", "." ]
def _add_method_dunders(self, method): """ Add __module__ and __qualname__ to a *method* if possible. """ try: method.__module__ = self._cls.__module__ except AttributeError: pass try: method.__qualname__ = ".".join( (self._cls.__qualname__, method.__name__) ) except AttributeError: pass return method
[ "def", "_add_method_dunders", "(", "self", ",", "method", ")", ":", "try", ":", "method", ".", "__module__", "=", "self", ".", "_cls", ".", "__module__", "except", "AttributeError", ":", "pass", "try", ":", "method", ".", "__qualname__", "=", "\".\"", ".", "join", "(", "(", "self", ".", "_cls", ".", "__qualname__", ",", "method", ".", "__name__", ")", ")", "except", "AttributeError", ":", "pass", "return", "method" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py#L715-L731
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
remoting/host/installer/build-installer-archive.py
python
copyZipIntoArchive
(out_dir, files_root, zip_file)
Expands the zip_file into the out_dir, preserving the directory structure. Args: out_dir: Target directory where unzipped files are copied. files_root: Path prefix which is stripped of zip_file before appending it to the out_dir. zip_file: Relative path (and filename) to the zip file.
Expands the zip_file into the out_dir, preserving the directory structure.
[ "Expands", "the", "zip_file", "into", "the", "out_dir", "preserving", "the", "directory", "structure", "." ]
def copyZipIntoArchive(out_dir, files_root, zip_file): """Expands the zip_file into the out_dir, preserving the directory structure. Args: out_dir: Target directory where unzipped files are copied. files_root: Path prefix which is stripped of zip_file before appending it to the out_dir. zip_file: Relative path (and filename) to the zip file. """ base_zip_name = os.path.basename(zip_file) # We don't use the 'zipfile' module here because it doesn't restore all the # file permissions correctly. We use the 'unzip' command manually. old_dir = os.getcwd(); os.chdir(os.path.dirname(zip_file)) subprocess.call(['unzip', '-qq', '-o', base_zip_name]) os.chdir(old_dir) # Unzip into correct dir in out_dir. out_zip_path = remapSrcFile(out_dir, files_root, zip_file) out_zip_dir = os.path.dirname(out_zip_path) (src_dir, ignore1) = os.path.splitext(zip_file) (base_dir_name, ignore2) = os.path.splitext(base_zip_name) shutil.copytree(src_dir, os.path.join(out_zip_dir, base_dir_name))
[ "def", "copyZipIntoArchive", "(", "out_dir", ",", "files_root", ",", "zip_file", ")", ":", "base_zip_name", "=", "os", ".", "path", ".", "basename", "(", "zip_file", ")", "# We don't use the 'zipfile' module here because it doesn't restore all the", "# file permissions correctly. We use the 'unzip' command manually.", "old_dir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "os", ".", "path", ".", "dirname", "(", "zip_file", ")", ")", "subprocess", ".", "call", "(", "[", "'unzip'", ",", "'-qq'", ",", "'-o'", ",", "base_zip_name", "]", ")", "os", ".", "chdir", "(", "old_dir", ")", "# Unzip into correct dir in out_dir.", "out_zip_path", "=", "remapSrcFile", "(", "out_dir", ",", "files_root", ",", "zip_file", ")", "out_zip_dir", "=", "os", ".", "path", ".", "dirname", "(", "out_zip_path", ")", "(", "src_dir", ",", "ignore1", ")", "=", "os", ".", "path", ".", "splitext", "(", "zip_file", ")", "(", "base_dir_name", ",", "ignore2", ")", "=", "os", ".", "path", ".", "splitext", "(", "base_zip_name", ")", "shutil", ".", "copytree", "(", "src_dir", ",", "os", ".", "path", ".", "join", "(", "out_zip_dir", ",", "base_dir_name", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/remoting/host/installer/build-installer-archive.py#L144-L168
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/variables.py
python
initialize_all_variables
()
return initialize_variables(all_variables())
Returns an Op that initializes all variables. This is just a shortcut for `initialize_variables(all_variables())` Returns: An Op that initializes all variables in the graph.
Returns an Op that initializes all variables.
[ "Returns", "an", "Op", "that", "initializes", "all", "variables", "." ]
def initialize_all_variables(): """Returns an Op that initializes all variables. This is just a shortcut for `initialize_variables(all_variables())` Returns: An Op that initializes all variables in the graph. """ return initialize_variables(all_variables())
[ "def", "initialize_all_variables", "(", ")", ":", "return", "initialize_variables", "(", "all_variables", "(", ")", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/variables.py#L933-L941
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/lib/dumping_callback.py
python
_DumpingCallback._instrument_symbolic_tensors
(self, tensors, op_type, op_name, tfdbg_context_id, tensor_ids)
return instrumented_tensors
Add debugging instrumentation for symbolic (i.e., non-eager) tensors. The detailed fashion in which the tensors are instrumented is determined by the tensor_debug_mode configured for the currently enabled dumping callback. Args: tensors: A tuple of Tensors to instrument. It is assumed that their ordering corresponds to the ordering of output tensors of an original op. Output slot indices (0-based) will be generated based on the ordering. op_type: Type name of the op that emits the Tensors (e.g., "MatMul"). op_name: Name of the op that emits the Tensors (e.g., "dense_1/MatMul"). tfdbg_context_id: A unique ID for the context that the op belongs to (e.g., a graph). tensor_ids: A list of unique ID numbers for the tensors, for tfdbg's internal use. Returns: Non-eager Tensors that override the `tensors` as the output of the op that originally generated `tensors`. In some cases (e.g., non-V1 graph mode), this may be `None`, as the instrumentation can simply rely on automatic control dependencies (see `auto_control_deps.py`) instead of tensor overriding.
Add debugging instrumentation for symbolic (i.e., non-eager) tensors.
[ "Add", "debugging", "instrumentation", "for", "symbolic", "(", "i", ".", "e", ".", "non", "-", "eager", ")", "tensors", "." ]
def _instrument_symbolic_tensors(self, tensors, op_type, op_name, tfdbg_context_id, tensor_ids): """Add debugging instrumentation for symbolic (i.e., non-eager) tensors. The detailed fashion in which the tensors are instrumented is determined by the tensor_debug_mode configured for the currently enabled dumping callback. Args: tensors: A tuple of Tensors to instrument. It is assumed that their ordering corresponds to the ordering of output tensors of an original op. Output slot indices (0-based) will be generated based on the ordering. op_type: Type name of the op that emits the Tensors (e.g., "MatMul"). op_name: Name of the op that emits the Tensors (e.g., "dense_1/MatMul"). tfdbg_context_id: A unique ID for the context that the op belongs to (e.g., a graph). tensor_ids: A list of unique ID numbers for the tensors, for tfdbg's internal use. Returns: Non-eager Tensors that override the `tensors` as the output of the op that originally generated `tensors`. In some cases (e.g., non-V1 graph mode), this may be `None`, as the instrumentation can simply rely on automatic control dependencies (see `auto_control_deps.py`) instead of tensor overriding. """ tensor_debug_mode = self._tensor_debug_mode debug_urls = ["file://%s" % self._dump_root] is_v1_graph_mode = not ops.executing_eagerly_outside_functions() instrumented_tensors = [] if is_v1_graph_mode else None for output_slot, tensor in enumerate(tensors): with self._symbolic_tensor_counter_lock: debug_identity_name = ("DebugIdentityV2_%d" % self._symbolic_tensor_counter) debug_identity_op_kwargs = { "tfdbg_context_id": tfdbg_context_id, "op_name": op_name, "output_slot": output_slot, "tensor_debug_mode": self._tensor_debug_mode, "debug_urls": debug_urls, "name": debug_identity_name, "circular_buffer_size": self._circular_buffer_size, "tfdbg_run_id": self._tfdbg_run_id, } if tensor_debug_mode == debug_event_pb2.TensorDebugMode.NO_TENSOR: if (not self._should_dump_tensor(op_type, tensor.dtype) or not tensor.dtype.is_numpy_compatible): if is_v1_graph_mode: instrumented_tensors.append(tensor) continue if is_v1_graph_mode and not tensor.dtype.is_numpy_compatible: # Avoid instrumenting Placeholder under is_v1_graph_mode. Doing that # would cause runtime complaint about Placeholders not being fed. instrumented_tensors.append(tensor) continue # Except in V1 graph mode + control flow, debug_identity_v2 triggers # auto control dependency because it's a stateful op. debug_tensor = gen_debug_ops.debug_identity_v2( # Use an empty (shape=[0]) float32 tensor for the NO_TENSOR mode # as a low-overhead placeholder, since no actual tensor value is # traced. constant_op.constant([], dtype=dtypes.float32), **debug_identity_op_kwargs) if is_v1_graph_mode: instrumented_tensors.append(self._process_v1_graph_mode_tensor( op_type, tensor, debug_tensor, tensor_debug_mode)) elif tensor_debug_mode in (debug_event_pb2.TensorDebugMode.CURT_HEALTH, debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, debug_event_pb2.TensorDebugMode.FULL_HEALTH, debug_event_pb2.TensorDebugMode.SHAPE): dtype = tensor.dtype dtype_is_dumpable = ( tensor_debug_mode in ( debug_event_pb2.TensorDebugMode.CURT_HEALTH, debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, debug_event_pb2.TensorDebugMode.FULL_HEALTH) and dtype.is_floating or tensor_debug_mode == debug_event_pb2.TensorDebugMode.SHAPE and (dtype.is_floating or dtype.is_integer or dtype.is_bool)) if (not self._should_dump_tensor(op_type, tensor.dtype) or not dtype_is_dumpable): if is_v1_graph_mode: instrumented_tensors.append(tensor) continue debug_tensor = gen_debug_ops.debug_identity_v2( gen_debug_ops.debug_numeric_summary_v2( tensor, tensor_id=tensor_ids[output_slot], tensor_debug_mode=self._tensor_debug_mode, output_dtype=dtypes.float64), **debug_identity_op_kwargs) if is_v1_graph_mode: instrumented_tensors.append(self._process_v1_graph_mode_tensor( op_type, tensor, debug_tensor, tensor_debug_mode)) elif tensor_debug_mode == debug_event_pb2.TensorDebugMode.FULL_TENSOR: if (not self._should_dump_tensor(op_type, tensor.dtype) or not tensor.dtype.is_numpy_compatible): # Instrumenting DT_VARIANT and DT_RESOURCE type tensors under # V1 graph mode is known to have issues. TODO(cais): Investigate. if is_v1_graph_mode: instrumented_tensors.append(tensor) continue debug_tensor = gen_debug_ops.debug_identity_v2( tensor, **debug_identity_op_kwargs) if is_v1_graph_mode: instrumented_tensors.append(self._process_v1_graph_mode_tensor( op_type, tensor, debug_tensor, tensor_debug_mode)) else: raise NotImplementedError( "Symbolic tensor instrumentation is not implemented for debug mode " "%s" % self._tensor_debug_mode) return instrumented_tensors
[ "def", "_instrument_symbolic_tensors", "(", "self", ",", "tensors", ",", "op_type", ",", "op_name", ",", "tfdbg_context_id", ",", "tensor_ids", ")", ":", "tensor_debug_mode", "=", "self", ".", "_tensor_debug_mode", "debug_urls", "=", "[", "\"file://%s\"", "%", "self", ".", "_dump_root", "]", "is_v1_graph_mode", "=", "not", "ops", ".", "executing_eagerly_outside_functions", "(", ")", "instrumented_tensors", "=", "[", "]", "if", "is_v1_graph_mode", "else", "None", "for", "output_slot", ",", "tensor", "in", "enumerate", "(", "tensors", ")", ":", "with", "self", ".", "_symbolic_tensor_counter_lock", ":", "debug_identity_name", "=", "(", "\"DebugIdentityV2_%d\"", "%", "self", ".", "_symbolic_tensor_counter", ")", "debug_identity_op_kwargs", "=", "{", "\"tfdbg_context_id\"", ":", "tfdbg_context_id", ",", "\"op_name\"", ":", "op_name", ",", "\"output_slot\"", ":", "output_slot", ",", "\"tensor_debug_mode\"", ":", "self", ".", "_tensor_debug_mode", ",", "\"debug_urls\"", ":", "debug_urls", ",", "\"name\"", ":", "debug_identity_name", ",", "\"circular_buffer_size\"", ":", "self", ".", "_circular_buffer_size", ",", "\"tfdbg_run_id\"", ":", "self", ".", "_tfdbg_run_id", ",", "}", "if", "tensor_debug_mode", "==", "debug_event_pb2", ".", "TensorDebugMode", ".", "NO_TENSOR", ":", "if", "(", "not", "self", ".", "_should_dump_tensor", "(", "op_type", ",", "tensor", ".", "dtype", ")", "or", "not", "tensor", ".", "dtype", ".", "is_numpy_compatible", ")", ":", "if", "is_v1_graph_mode", ":", "instrumented_tensors", ".", "append", "(", "tensor", ")", "continue", "if", "is_v1_graph_mode", "and", "not", "tensor", ".", "dtype", ".", "is_numpy_compatible", ":", "# Avoid instrumenting Placeholder under is_v1_graph_mode. Doing that", "# would cause runtime complaint about Placeholders not being fed.", "instrumented_tensors", ".", "append", "(", "tensor", ")", "continue", "# Except in V1 graph mode + control flow, debug_identity_v2 triggers", "# auto control dependency because it's a stateful op.", "debug_tensor", "=", "gen_debug_ops", ".", "debug_identity_v2", "(", "# Use an empty (shape=[0]) float32 tensor for the NO_TENSOR mode", "# as a low-overhead placeholder, since no actual tensor value is", "# traced.", "constant_op", ".", "constant", "(", "[", "]", ",", "dtype", "=", "dtypes", ".", "float32", ")", ",", "*", "*", "debug_identity_op_kwargs", ")", "if", "is_v1_graph_mode", ":", "instrumented_tensors", ".", "append", "(", "self", ".", "_process_v1_graph_mode_tensor", "(", "op_type", ",", "tensor", ",", "debug_tensor", ",", "tensor_debug_mode", ")", ")", "elif", "tensor_debug_mode", "in", "(", "debug_event_pb2", ".", "TensorDebugMode", ".", "CURT_HEALTH", ",", "debug_event_pb2", ".", "TensorDebugMode", ".", "CONCISE_HEALTH", ",", "debug_event_pb2", ".", "TensorDebugMode", ".", "FULL_HEALTH", ",", "debug_event_pb2", ".", "TensorDebugMode", ".", "SHAPE", ")", ":", "dtype", "=", "tensor", ".", "dtype", "dtype_is_dumpable", "=", "(", "tensor_debug_mode", "in", "(", "debug_event_pb2", ".", "TensorDebugMode", ".", "CURT_HEALTH", ",", "debug_event_pb2", ".", "TensorDebugMode", ".", "CONCISE_HEALTH", ",", "debug_event_pb2", ".", "TensorDebugMode", ".", "FULL_HEALTH", ")", "and", "dtype", ".", "is_floating", "or", "tensor_debug_mode", "==", "debug_event_pb2", ".", "TensorDebugMode", ".", "SHAPE", "and", "(", "dtype", ".", "is_floating", "or", "dtype", ".", "is_integer", "or", "dtype", ".", "is_bool", ")", ")", "if", "(", "not", "self", ".", "_should_dump_tensor", "(", "op_type", ",", "tensor", ".", "dtype", ")", "or", "not", "dtype_is_dumpable", ")", ":", "if", "is_v1_graph_mode", ":", "instrumented_tensors", ".", "append", "(", "tensor", ")", "continue", "debug_tensor", "=", "gen_debug_ops", ".", "debug_identity_v2", "(", "gen_debug_ops", ".", "debug_numeric_summary_v2", "(", "tensor", ",", "tensor_id", "=", "tensor_ids", "[", "output_slot", "]", ",", "tensor_debug_mode", "=", "self", ".", "_tensor_debug_mode", ",", "output_dtype", "=", "dtypes", ".", "float64", ")", ",", "*", "*", "debug_identity_op_kwargs", ")", "if", "is_v1_graph_mode", ":", "instrumented_tensors", ".", "append", "(", "self", ".", "_process_v1_graph_mode_tensor", "(", "op_type", ",", "tensor", ",", "debug_tensor", ",", "tensor_debug_mode", ")", ")", "elif", "tensor_debug_mode", "==", "debug_event_pb2", ".", "TensorDebugMode", ".", "FULL_TENSOR", ":", "if", "(", "not", "self", ".", "_should_dump_tensor", "(", "op_type", ",", "tensor", ".", "dtype", ")", "or", "not", "tensor", ".", "dtype", ".", "is_numpy_compatible", ")", ":", "# Instrumenting DT_VARIANT and DT_RESOURCE type tensors under", "# V1 graph mode is known to have issues. TODO(cais): Investigate.", "if", "is_v1_graph_mode", ":", "instrumented_tensors", ".", "append", "(", "tensor", ")", "continue", "debug_tensor", "=", "gen_debug_ops", ".", "debug_identity_v2", "(", "tensor", ",", "*", "*", "debug_identity_op_kwargs", ")", "if", "is_v1_graph_mode", ":", "instrumented_tensors", ".", "append", "(", "self", ".", "_process_v1_graph_mode_tensor", "(", "op_type", ",", "tensor", ",", "debug_tensor", ",", "tensor_debug_mode", ")", ")", "else", ":", "raise", "NotImplementedError", "(", "\"Symbolic tensor instrumentation is not implemented for debug mode \"", "\"%s\"", "%", "self", ".", "_tensor_debug_mode", ")", "return", "instrumented_tensors" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/dumping_callback.py#L328-L443
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._HasExplicitIdlActions
(self, spec)
return any([action.get('explicit_idl_action', 0) for action in spec.get('actions', [])])
Determine if an action should not run midl for .idl files.
Determine if an action should not run midl for .idl files.
[ "Determine", "if", "an", "action", "should", "not", "run", "midl", "for", ".", "idl", "files", "." ]
def _HasExplicitIdlActions(self, spec): """Determine if an action should not run midl for .idl files.""" return any([action.get('explicit_idl_action', 0) for action in spec.get('actions', [])])
[ "def", "_HasExplicitIdlActions", "(", "self", ",", "spec", ")", ":", "return", "any", "(", "[", "action", ".", "get", "(", "'explicit_idl_action'", ",", "0", ")", "for", "action", "in", "spec", ".", "get", "(", "'actions'", ",", "[", "]", ")", "]", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L824-L827
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/tooltip.py
python
OnHoverTooltipBase._hide_event
(self, event=None)
event handler to hide the tooltip
event handler to hide the tooltip
[ "event", "handler", "to", "hide", "the", "tooltip" ]
def _hide_event(self, event=None): """event handler to hide the tooltip""" self.hidetip()
[ "def", "_hide_event", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "hidetip", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/tooltip.py#L119-L121
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/dbgen/scattering_lengths.py
python
make_scattering_lengths
(args)
Controller function for adding scattering lengths.
Controller function for adding scattering lengths.
[ "Controller", "function", "for", "adding", "scattering", "lengths", "." ]
def make_scattering_lengths(args): """Controller function for adding scattering lengths.""" nuc_data, build_dir = args.nuc_data, args.build_dir # Check that the table exists with tb.open_file(nuc_data, 'a', filters=BASIC_FILTERS) as f: if hasattr(f.root, 'neutron') and hasattr(f.root.neutron, 'scattering_lengths'): print("skipping scattering lengths data table creation; already exists.") return # Grab the raw data print("Grabbing the scattering length data.") grab_scattering_lengths(build_dir) # Make scatering table once we have the data print("Making neutron scattering length table.") make_scattering_lengths_table(nuc_data, build_dir)
[ "def", "make_scattering_lengths", "(", "args", ")", ":", "nuc_data", ",", "build_dir", "=", "args", ".", "nuc_data", ",", "args", ".", "build_dir", "# Check that the table exists", "with", "tb", ".", "open_file", "(", "nuc_data", ",", "'a'", ",", "filters", "=", "BASIC_FILTERS", ")", "as", "f", ":", "if", "hasattr", "(", "f", ".", "root", ",", "'neutron'", ")", "and", "hasattr", "(", "f", ".", "root", ".", "neutron", ",", "'scattering_lengths'", ")", ":", "print", "(", "\"skipping scattering lengths data table creation; already exists.\"", ")", "return", "# Grab the raw data", "print", "(", "\"Grabbing the scattering length data.\"", ")", "grab_scattering_lengths", "(", "build_dir", ")", "# Make scatering table once we have the data", "print", "(", "\"Making neutron scattering length table.\"", ")", "make_scattering_lengths_table", "(", "nuc_data", ",", "build_dir", ")" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/dbgen/scattering_lengths.py#L144-L160
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/CrystalField/fitting.py
python
CrystalFieldFit.fit
(self)
Run Fit algorithm. Update function parameters.
Run Fit algorithm. Update function parameters.
[ "Run", "Fit", "algorithm", ".", "Update", "function", "parameters", "." ]
def fit(self): """ Run Fit algorithm. Update function parameters. """ self.check_consistency() if isinstance(self._input_workspace, list): return self._fit_multi() else: return self._fit_single()
[ "def", "fit", "(", "self", ")", ":", "self", ".", "check_consistency", "(", ")", "if", "isinstance", "(", "self", ".", "_input_workspace", ",", "list", ")", ":", "return", "self", ".", "_fit_multi", "(", ")", "else", ":", "return", "self", ".", "_fit_single", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/CrystalField/fitting.py#L1241-L1249
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/text/utils.py
python
Vocab.from_list
(cls, word_list, special_tokens=None, special_first=True)
return vocab
Build a vocab object from a list of word. Args: word_list(list): A list of string where each element is a word of type string. special_tokens(list, optional): A list of strings, each one is a special token. For example special_tokens=["<pad>","<unk>"] (default=None, no special tokens will be added). special_first(bool, optional): Whether special_tokens is prepended or appended to vocab. If special_tokens is specified and special_first is set to True, special_tokens will be prepended (default=True). Returns: Vocab, vocab built from the `list`. Examples: >>> vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True)
Build a vocab object from a list of word.
[ "Build", "a", "vocab", "object", "from", "a", "list", "of", "word", "." ]
def from_list(cls, word_list, special_tokens=None, special_first=True): """ Build a vocab object from a list of word. Args: word_list(list): A list of string where each element is a word of type string. special_tokens(list, optional): A list of strings, each one is a special token. For example special_tokens=["<pad>","<unk>"] (default=None, no special tokens will be added). special_first(bool, optional): Whether special_tokens is prepended or appended to vocab. If special_tokens is specified and special_first is set to True, special_tokens will be prepended (default=True). Returns: Vocab, vocab built from the `list`. Examples: >>> vocab = text.Vocab.from_list(["w1", "w2", "w3"], special_tokens=["<unk>"], special_first=True) """ if special_tokens is None: special_tokens = [] vocab = Vocab() vocab.c_vocab = cde.Vocab.from_list(word_list, special_tokens, special_first) return vocab
[ "def", "from_list", "(", "cls", ",", "word_list", ",", "special_tokens", "=", "None", ",", "special_first", "=", "True", ")", ":", "if", "special_tokens", "is", "None", ":", "special_tokens", "=", "[", "]", "vocab", "=", "Vocab", "(", ")", "vocab", ".", "c_vocab", "=", "cde", ".", "Vocab", ".", "from_list", "(", "word_list", ",", "special_tokens", ",", "special_first", ")", "return", "vocab" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/text/utils.py#L144-L165
OGRECave/ogre-next
287307980e6de8910f04f3cc0994451b075071fd
Tools/BlenderExport/ogrepkg/gui.py
python
Widget.__init__
(self, parent, size = Size())
return
Constructor. Overwrite the constructor to get event numbers for all used actions via a call to <code>parent._addButtonAction()</code>. @param name The widget name must be unique. @param size Size hints.
Constructor. Overwrite the constructor to get event numbers for all used actions via a call to <code>parent._addButtonAction()</code>.
[ "Constructor", ".", "Overwrite", "the", "constructor", "to", "get", "event", "numbers", "for", "all", "used", "actions", "via", "a", "call", "to", "<code", ">", "parent", ".", "_addButtonAction", "()", "<", "/", "code", ">", "." ]
def __init__(self, parent, size = Size()): """Constructor. Overwrite the constructor to get event numbers for all used actions via a call to <code>parent._addButtonAction()</code>. @param name The widget name must be unique. @param size Size hints. """ self.parent = parent self.size = size self.parent._addWidget(self) return
[ "def", "__init__", "(", "self", ",", "parent", ",", "size", "=", "Size", "(", ")", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "size", "=", "size", "self", ".", "parent", ".", "_addWidget", "(", "self", ")", "return" ]
https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/BlenderExport/ogrepkg/gui.py#L93-L105
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic_io.py
python
_prettyPrintExpr
(expr,astr,parseCompatible)
return res
Returns a string representing this expression, where astr is a list of strings representing each argument
Returns a string representing this expression, where astr is a list of strings representing each argument
[ "Returns", "a", "string", "representing", "this", "expression", "where", "astr", "is", "a", "list", "of", "strings", "representing", "each", "argument" ]
def _prettyPrintExpr(expr,astr,parseCompatible): """Returns a string representing this expression, where astr is a list of strings representing each argument""" if not isinstance(expr,OperatorExpression): return exprToStr(expr,parseCompatible) if len(expr.functionInfo.printers) > 0: if parseCompatible and 'parse' in expr.functionInfo.printers: return expr.functionInfo.printers['parse'](expr,astr) if not parseCompatible and 'str' in expr.functionInfo.printers: return expr.functionInfo.printers['str'](expr,astr) if expr.functionInfo.name in _prefix_operators: prefix = _prefix_operators[expr.functionInfo.name] assert len(expr.args) == 1,"Weird, prefix operator %s has %d arguments? %s"%(expr.functionInfo.name,len(astr),",".join(astr)) return prefix + astr[0] if expr.functionInfo.name in _infix_operators: assert len(expr.args) == 2,"Weird, infix operator %s has %d arguments? %s"%(expr.functionInfo.name,len(astr),",".join(astr)) return astr[0] + _infix_operators[expr.functionInfo.name] + astr[1] if expr.functionInfo.name == 'setitem': vconst = to_const(expr.args[0]) iconst = to_const(expr.args[1]) if vconst is not None and iconst is not None: if hasattr(iconst,'__iter__'): indexset = set(iconst) if parseCompatible: astr[0] = '[' + ','.join(['0' if i in indexset else str(v) for i,v in enumerate(vconst)])+']' else: astr[0] = '[' + ','.join(['*' if i in indexset else str(v) for i,v in enumerate(vconst)])+']' if expr.functionInfo.name == 'getitem': if isinstance(expr.args[0],OperatorExpression) and astr[0][0] != '(' and expr.args[0].functionInfo.name in _infix_operators: astr[0] = '(' + astr[0] + ')' #if expr.functionInfo.name == 'getslice': # if len(astr) <= 2: # astr.append('') # if len(astr) <= 3: # astr.append('') # return astr[0] + '[%s:%s:%s]'%(astr[1],astr[2],astr[3]) if isinstance(expr.args[1],slice): start,stop,step = expr.args[1].start,expr.args[1].stop,expr.args[1].step astr[1] = "%s:%s%s"%(("" if start is None else str(start)), ("" if (stop is None or stop > 900000000000) else str(stop)), ("" if step is None else ":"+str(step))) return astr[0] + '[' +astr[1] + ']' #default if len(astr) > 1 and sum(len(a) for a in astr) > 80-2-len(expr.functionInfo.name): res = expr.functionInfo.name + "(" res += ',\n '.join([indent(a,2) for a in astr]) + ')' else: res = expr.functionInfo.name + "(" res += ','.join(astr) + ')' return res
[ "def", "_prettyPrintExpr", "(", "expr", ",", "astr", ",", "parseCompatible", ")", ":", "if", "not", "isinstance", "(", "expr", ",", "OperatorExpression", ")", ":", "return", "exprToStr", "(", "expr", ",", "parseCompatible", ")", "if", "len", "(", "expr", ".", "functionInfo", ".", "printers", ")", ">", "0", ":", "if", "parseCompatible", "and", "'parse'", "in", "expr", ".", "functionInfo", ".", "printers", ":", "return", "expr", ".", "functionInfo", ".", "printers", "[", "'parse'", "]", "(", "expr", ",", "astr", ")", "if", "not", "parseCompatible", "and", "'str'", "in", "expr", ".", "functionInfo", ".", "printers", ":", "return", "expr", ".", "functionInfo", ".", "printers", "[", "'str'", "]", "(", "expr", ",", "astr", ")", "if", "expr", ".", "functionInfo", ".", "name", "in", "_prefix_operators", ":", "prefix", "=", "_prefix_operators", "[", "expr", ".", "functionInfo", ".", "name", "]", "assert", "len", "(", "expr", ".", "args", ")", "==", "1", ",", "\"Weird, prefix operator %s has %d arguments? %s\"", "%", "(", "expr", ".", "functionInfo", ".", "name", ",", "len", "(", "astr", ")", ",", "\",\"", ".", "join", "(", "astr", ")", ")", "return", "prefix", "+", "astr", "[", "0", "]", "if", "expr", ".", "functionInfo", ".", "name", "in", "_infix_operators", ":", "assert", "len", "(", "expr", ".", "args", ")", "==", "2", ",", "\"Weird, infix operator %s has %d arguments? %s\"", "%", "(", "expr", ".", "functionInfo", ".", "name", ",", "len", "(", "astr", ")", ",", "\",\"", ".", "join", "(", "astr", ")", ")", "return", "astr", "[", "0", "]", "+", "_infix_operators", "[", "expr", ".", "functionInfo", ".", "name", "]", "+", "astr", "[", "1", "]", "if", "expr", ".", "functionInfo", ".", "name", "==", "'setitem'", ":", "vconst", "=", "to_const", "(", "expr", ".", "args", "[", "0", "]", ")", "iconst", "=", "to_const", "(", "expr", ".", "args", "[", "1", "]", ")", "if", "vconst", "is", "not", "None", "and", "iconst", "is", "not", "None", ":", "if", "hasattr", "(", "iconst", ",", "'__iter__'", ")", ":", "indexset", "=", "set", "(", "iconst", ")", "if", "parseCompatible", ":", "astr", "[", "0", "]", "=", "'['", "+", "','", ".", "join", "(", "[", "'0'", "if", "i", "in", "indexset", "else", "str", "(", "v", ")", "for", "i", ",", "v", "in", "enumerate", "(", "vconst", ")", "]", ")", "+", "']'", "else", ":", "astr", "[", "0", "]", "=", "'['", "+", "','", ".", "join", "(", "[", "'*'", "if", "i", "in", "indexset", "else", "str", "(", "v", ")", "for", "i", ",", "v", "in", "enumerate", "(", "vconst", ")", "]", ")", "+", "']'", "if", "expr", ".", "functionInfo", ".", "name", "==", "'getitem'", ":", "if", "isinstance", "(", "expr", ".", "args", "[", "0", "]", ",", "OperatorExpression", ")", "and", "astr", "[", "0", "]", "[", "0", "]", "!=", "'('", "and", "expr", ".", "args", "[", "0", "]", ".", "functionInfo", ".", "name", "in", "_infix_operators", ":", "astr", "[", "0", "]", "=", "'('", "+", "astr", "[", "0", "]", "+", "')'", "#if expr.functionInfo.name == 'getslice':", "# if len(astr) <= 2:", "# astr.append('')", "# if len(astr) <= 3:", "# astr.append('')", "# return astr[0] + '[%s:%s:%s]'%(astr[1],astr[2],astr[3])", "if", "isinstance", "(", "expr", ".", "args", "[", "1", "]", ",", "slice", ")", ":", "start", ",", "stop", ",", "step", "=", "expr", ".", "args", "[", "1", "]", ".", "start", ",", "expr", ".", "args", "[", "1", "]", ".", "stop", ",", "expr", ".", "args", "[", "1", "]", ".", "step", "astr", "[", "1", "]", "=", "\"%s:%s%s\"", "%", "(", "(", "\"\"", "if", "start", "is", "None", "else", "str", "(", "start", ")", ")", ",", "(", "\"\"", "if", "(", "stop", "is", "None", "or", "stop", ">", "900000000000", ")", "else", "str", "(", "stop", ")", ")", ",", "(", "\"\"", "if", "step", "is", "None", "else", "\":\"", "+", "str", "(", "step", ")", ")", ")", "return", "astr", "[", "0", "]", "+", "'['", "+", "astr", "[", "1", "]", "+", "']'", "#default", "if", "len", "(", "astr", ")", ">", "1", "and", "sum", "(", "len", "(", "a", ")", "for", "a", "in", "astr", ")", ">", "80", "-", "2", "-", "len", "(", "expr", ".", "functionInfo", ".", "name", ")", ":", "res", "=", "expr", ".", "functionInfo", ".", "name", "+", "\"(\"", "res", "+=", "',\\n '", ".", "join", "(", "[", "indent", "(", "a", ",", "2", ")", "for", "a", "in", "astr", "]", ")", "+", "')'", "else", ":", "res", "=", "expr", ".", "functionInfo", ".", "name", "+", "\"(\"", "res", "+=", "','", ".", "join", "(", "astr", ")", "+", "')'", "return", "res" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic_io.py#L56-L105
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/common/timers.py
python
Timer.__init__
(self, timer_name)
Creates timer. Timer name is name that will be in logs.
Creates timer. Timer name is name that will be in logs.
[ "Creates", "timer", ".", "Timer", "name", "is", "name", "that", "will", "be", "in", "logs", "." ]
def __init__(self, timer_name): """ Creates timer. Timer name is name that will be in logs. """ self.timer_name = timer_name self.start_time = None self.end_time = None self.section_name = None self.timers = []
[ "def", "__init__", "(", "self", ",", "timer_name", ")", ":", "self", ".", "timer_name", "=", "timer_name", "self", ".", "start_time", "=", "None", "self", ".", "end_time", "=", "None", "self", ".", "section_name", "=", "None", "self", ".", "timers", "=", "[", "]" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/common/timers.py#L5-L13
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/wiredtiger/dist/stat.py
python
print_func
(name, handle, statlist)
Print the structures/functions for the stat.c file.
Print the structures/functions for the stat.c file.
[ "Print", "the", "structures", "/", "functions", "for", "the", "stat", ".", "c", "file", "." ]
def print_func(name, handle, statlist): '''Print the structures/functions for the stat.c file.''' f.write('\n') f.write('static const char * const __stats_' + name + '_desc[] = {\n') for l in statlist: f.write('\t"' + l.desc + '",\n') f.write('};\n') f.write(''' int __wt_stat_''' + name + '''_desc(WT_CURSOR_STAT *cst, int slot, const char **p) { \tWT_UNUSED(cst); \t*p = __stats_''' + name + '''_desc[slot]; \treturn (0); } ''') f.write(''' void __wt_stat_''' + name + '_init_single(WT_' + name.upper() + '''_STATS *stats) { \tmemset(stats, 0, sizeof(*stats)); } ''') if handle != None: f.write(''' int __wt_stat_''' + name + '''_init( WT_SESSION_IMPL *session, ''' + handle + ''' *handle) { \tint i; \tWT_RET(__wt_calloc(session, (size_t)WT_COUNTER_SLOTS, \t sizeof(*handle->stat_array), &handle->stat_array)); \tfor (i = 0; i < WT_COUNTER_SLOTS; ++i) { \t\thandle->stats[i] = &handle->stat_array[i]; \t\t__wt_stat_''' + name + '''_init_single(handle->stats[i]); \t} \treturn (0); } void __wt_stat_''' + name + '''_discard( WT_SESSION_IMPL *session, ''' + handle + ''' *handle) { \t__wt_free(session, handle->stat_array); } ''') f.write(''' void __wt_stat_''' + name + '_clear_single(WT_' + name.upper() + '''_STATS *stats) { ''') for l in statlist: # no_clear: don't clear the value. if 'no_clear' in l.flags: f.write('\t\t/* not clearing ' + l.name + ' */\n') else: f.write('\tstats->' + l.name + ' = 0;\n') f.write('}\n') if name != 'session': f.write(''' void __wt_stat_''' + name + '_clear_all(WT_' + name.upper() + '''_STATS **stats) { \tu_int i; \tfor (i = 0; i < WT_COUNTER_SLOTS; ++i) \t\t__wt_stat_''' + name + '''_clear_single(stats[i]); } ''') # Single structure aggregation is currently only used by data sources. if name == 'dsrc': f.write(''' void __wt_stat_''' + name + '''_aggregate_single( WT_''' + name.upper() + '_STATS *from, WT_' + name.upper() + '''_STATS *to) { ''') for l in statlist: if 'max_aggregate' in l.flags: o = '\tif (from->' + l.name + ' > to->' + l.name + ')\n' +\ '\t\tto->' + l.name + ' = from->' + l.name + ';\n' else: o = '\tto->' + l.name + ' += from->' + l.name + ';\n' if len(o) > 72: # Account for the leading tab. o = o.replace(' += ', ' +=\n\t ') f.write(o) f.write('}\n') if name != 'session': f.write(''' void __wt_stat_''' + name + '''_aggregate( WT_''' + name.upper() + '_STATS **from, WT_' + name.upper() + '''_STATS *to) { ''') # Connection level aggregation does not currently have any computation # of a maximum value; I'm leaving in support for it, but don't declare # a temporary variable until it's needed. for l in statlist: if 'max_aggregate' in l.flags: f.write('\tint64_t v;\n\n') break; for l in statlist: if 'max_aggregate' in l.flags: o = '\tif ((v = WT_STAT_READ(from, ' + l.name + ')) > ' +\ 'to->' + l.name + ')\n' if len(o) > 72: # Account for the leading tab. o = o.replace(' > ', ' >\n\t ') o +='\t\tto->' + l.name + ' = v;\n' else: o = '\tto->' + l.name + ' += WT_STAT_READ(from, ' + l.name +\ ');\n' if len(o) > 72: # Account for the leading tab. o = o.replace(' += ', ' +=\n\t ') f.write(o) f.write('}\n')
[ "def", "print_func", "(", "name", ",", "handle", ",", "statlist", ")", ":", "f", ".", "write", "(", "'\\n'", ")", "f", ".", "write", "(", "'static const char * const __stats_'", "+", "name", "+", "'_desc[] = {\\n'", ")", "for", "l", "in", "statlist", ":", "f", ".", "write", "(", "'\\t\"'", "+", "l", ".", "desc", "+", "'\",\\n'", ")", "f", ".", "write", "(", "'};\\n'", ")", "f", ".", "write", "(", "'''\nint\n__wt_stat_'''", "+", "name", "+", "'''_desc(WT_CURSOR_STAT *cst, int slot, const char **p)\n{\n\\tWT_UNUSED(cst);\n\\t*p = __stats_'''", "+", "name", "+", "'''_desc[slot];\n\\treturn (0);\n}\n'''", ")", "f", ".", "write", "(", "'''\nvoid\n__wt_stat_'''", "+", "name", "+", "'_init_single(WT_'", "+", "name", ".", "upper", "(", ")", "+", "'''_STATS *stats)\n{\n\\tmemset(stats, 0, sizeof(*stats));\n}\n'''", ")", "if", "handle", "!=", "None", ":", "f", ".", "write", "(", "'''\nint\n__wt_stat_'''", "+", "name", "+", "'''_init(\n WT_SESSION_IMPL *session, '''", "+", "handle", "+", "''' *handle)\n{\n\\tint i;\n\n\\tWT_RET(__wt_calloc(session, (size_t)WT_COUNTER_SLOTS,\n\\t sizeof(*handle->stat_array), &handle->stat_array));\n\n\\tfor (i = 0; i < WT_COUNTER_SLOTS; ++i) {\n\\t\\thandle->stats[i] = &handle->stat_array[i];\n\\t\\t__wt_stat_'''", "+", "name", "+", "'''_init_single(handle->stats[i]);\n\\t}\n\\treturn (0);\n}\n\nvoid\n__wt_stat_'''", "+", "name", "+", "'''_discard(\n WT_SESSION_IMPL *session, '''", "+", "handle", "+", "''' *handle)\n{\n\\t__wt_free(session, handle->stat_array);\n}\n'''", ")", "f", ".", "write", "(", "'''\nvoid\n__wt_stat_'''", "+", "name", "+", "'_clear_single(WT_'", "+", "name", ".", "upper", "(", ")", "+", "'''_STATS *stats)\n{\n'''", ")", "for", "l", "in", "statlist", ":", "# no_clear: don't clear the value.", "if", "'no_clear'", "in", "l", ".", "flags", ":", "f", ".", "write", "(", "'\\t\\t/* not clearing '", "+", "l", ".", "name", "+", "' */\\n'", ")", "else", ":", "f", ".", "write", "(", "'\\tstats->'", "+", "l", ".", "name", "+", "' = 0;\\n'", ")", "f", ".", "write", "(", "'}\\n'", ")", "if", "name", "!=", "'session'", ":", "f", ".", "write", "(", "'''\nvoid\n__wt_stat_'''", "+", "name", "+", "'_clear_all(WT_'", "+", "name", ".", "upper", "(", ")", "+", "'''_STATS **stats)\n{\n\\tu_int i;\n\n\\tfor (i = 0; i < WT_COUNTER_SLOTS; ++i)\n\\t\\t__wt_stat_'''", "+", "name", "+", "'''_clear_single(stats[i]);\n}\n'''", ")", "# Single structure aggregation is currently only used by data sources.", "if", "name", "==", "'dsrc'", ":", "f", ".", "write", "(", "'''\nvoid\n__wt_stat_'''", "+", "name", "+", "'''_aggregate_single(\n WT_'''", "+", "name", ".", "upper", "(", ")", "+", "'_STATS *from, WT_'", "+", "name", ".", "upper", "(", ")", "+", "'''_STATS *to)\n{\n'''", ")", "for", "l", "in", "statlist", ":", "if", "'max_aggregate'", "in", "l", ".", "flags", ":", "o", "=", "'\\tif (from->'", "+", "l", ".", "name", "+", "' > to->'", "+", "l", ".", "name", "+", "')\\n'", "+", "'\\t\\tto->'", "+", "l", ".", "name", "+", "' = from->'", "+", "l", ".", "name", "+", "';\\n'", "else", ":", "o", "=", "'\\tto->'", "+", "l", ".", "name", "+", "' += from->'", "+", "l", ".", "name", "+", "';\\n'", "if", "len", "(", "o", ")", ">", "72", ":", "# Account for the leading tab.", "o", "=", "o", ".", "replace", "(", "' += '", ",", "' +=\\n\\t '", ")", "f", ".", "write", "(", "o", ")", "f", ".", "write", "(", "'}\\n'", ")", "if", "name", "!=", "'session'", ":", "f", ".", "write", "(", "'''\nvoid\n__wt_stat_'''", "+", "name", "+", "'''_aggregate(\n WT_'''", "+", "name", ".", "upper", "(", ")", "+", "'_STATS **from, WT_'", "+", "name", ".", "upper", "(", ")", "+", "'''_STATS *to)\n{\n'''", ")", "# Connection level aggregation does not currently have any computation", "# of a maximum value; I'm leaving in support for it, but don't declare", "# a temporary variable until it's needed.", "for", "l", "in", "statlist", ":", "if", "'max_aggregate'", "in", "l", ".", "flags", ":", "f", ".", "write", "(", "'\\tint64_t v;\\n\\n'", ")", "break", "for", "l", "in", "statlist", ":", "if", "'max_aggregate'", "in", "l", ".", "flags", ":", "o", "=", "'\\tif ((v = WT_STAT_READ(from, '", "+", "l", ".", "name", "+", "')) > '", "+", "'to->'", "+", "l", ".", "name", "+", "')\\n'", "if", "len", "(", "o", ")", ">", "72", ":", "# Account for the leading tab.", "o", "=", "o", ".", "replace", "(", "' > '", ",", "' >\\n\\t '", ")", "o", "+=", "'\\t\\tto->'", "+", "l", ".", "name", "+", "' = v;\\n'", "else", ":", "o", "=", "'\\tto->'", "+", "l", ".", "name", "+", "' += WT_STAT_READ(from, '", "+", "l", ".", "name", "+", "');\\n'", "if", "len", "(", "o", ")", ">", "72", ":", "# Account for the leading tab.", "o", "=", "o", ".", "replace", "(", "' += '", ",", "' +=\\n\\t '", ")", "f", ".", "write", "(", "o", ")", "f", ".", "write", "(", "'}\\n'", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/wiredtiger/dist/stat.py#L133-L256
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py
python
Cursor.type
(self)
return self._type
Retrieve the Type (if any) of the entity pointed at by the cursor.
Retrieve the Type (if any) of the entity pointed at by the cursor.
[ "Retrieve", "the", "Type", "(", "if", "any", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def type(self): """ Retrieve the Type (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_type'): self._type = conf.lib.clang_getCursorType(self) return self._type
[ "def", "type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_type'", ")", ":", "self", ".", "_type", "=", "conf", ".", "lib", ".", "clang_getCursorType", "(", "self", ")", "return", "self", ".", "_type" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py#L1503-L1510
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/media.py
python
MediaCtrl.Tell
(*args, **kwargs)
return _media.MediaCtrl_Tell(*args, **kwargs)
Tell(self) -> wxFileOffset
Tell(self) -> wxFileOffset
[ "Tell", "(", "self", ")", "-", ">", "wxFileOffset" ]
def Tell(*args, **kwargs): """Tell(self) -> wxFileOffset""" return _media.MediaCtrl_Tell(*args, **kwargs)
[ "def", "Tell", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_media", ".", "MediaCtrl_Tell", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/media.py#L137-L139
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/utils/lit/lit/util.py
python
detectCPUs
()
return 1
Detects the number of CPUs on a system. Cribbed from pp.
Detects the number of CPUs on a system.
[ "Detects", "the", "number", "of", "CPUs", "on", "a", "system", "." ]
def detectCPUs(): """Detects the number of CPUs on a system. Cribbed from pp. """ # Linux, Unix and MacOS: if hasattr(os, 'sysconf'): if 'SC_NPROCESSORS_ONLN' in os.sysconf_names: # Linux & Unix: ncpus = os.sysconf('SC_NPROCESSORS_ONLN') if isinstance(ncpus, int) and ncpus > 0: return ncpus else: # OSX: return int(subprocess.check_output(['sysctl', '-n', 'hw.ncpu'], stderr=subprocess.STDOUT)) # Windows: if 'NUMBER_OF_PROCESSORS' in os.environ: ncpus = int(os.environ['NUMBER_OF_PROCESSORS']) if ncpus > 0: # With more than 32 processes, process creation often fails with # "Too many open files". FIXME: Check if there's a better fix. return min(ncpus, 32) return 1
[ "def", "detectCPUs", "(", ")", ":", "# Linux, Unix and MacOS:", "if", "hasattr", "(", "os", ",", "'sysconf'", ")", ":", "if", "'SC_NPROCESSORS_ONLN'", "in", "os", ".", "sysconf_names", ":", "# Linux & Unix:", "ncpus", "=", "os", ".", "sysconf", "(", "'SC_NPROCESSORS_ONLN'", ")", "if", "isinstance", "(", "ncpus", ",", "int", ")", "and", "ncpus", ">", "0", ":", "return", "ncpus", "else", ":", "# OSX:", "return", "int", "(", "subprocess", ".", "check_output", "(", "[", "'sysctl'", ",", "'-n'", ",", "'hw.ncpu'", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ")", "# Windows:", "if", "'NUMBER_OF_PROCESSORS'", "in", "os", ".", "environ", ":", "ncpus", "=", "int", "(", "os", ".", "environ", "[", "'NUMBER_OF_PROCESSORS'", "]", ")", "if", "ncpus", ">", "0", ":", "# With more than 32 processes, process creation often fails with", "# \"Too many open files\". FIXME: Check if there's a better fix.", "return", "min", "(", "ncpus", ",", "32", ")", "return", "1" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/utils/lit/lit/util.py#L105-L128
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/motionplanning.py
python
CSpaceInterface.addFeasibilityTest
(self, name: "char const *", pyFeas: "PyObject *")
return _motionplanning.CSpaceInterface_addFeasibilityTest(self, name, pyFeas)
r""" addFeasibilityTest(CSpaceInterface self, char const * name, PyObject * pyFeas)
r""" addFeasibilityTest(CSpaceInterface self, char const * name, PyObject * pyFeas)
[ "r", "addFeasibilityTest", "(", "CSpaceInterface", "self", "char", "const", "*", "name", "PyObject", "*", "pyFeas", ")" ]
def addFeasibilityTest(self, name: "char const *", pyFeas: "PyObject *") -> "void": r""" addFeasibilityTest(CSpaceInterface self, char const * name, PyObject * pyFeas) """ return _motionplanning.CSpaceInterface_addFeasibilityTest(self, name, pyFeas)
[ "def", "addFeasibilityTest", "(", "self", ",", "name", ":", "\"char const *\"", ",", "pyFeas", ":", "\"PyObject *\"", ")", "->", "\"void\"", ":", "return", "_motionplanning", ".", "CSpaceInterface_addFeasibilityTest", "(", "self", ",", "name", ",", "pyFeas", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/motionplanning.py#L510-L516
rootm0s/Protectors
5b3f4d11687a5955caf9c3af30666c4bfc2c19ab
OWASP-ZSC/module/readline_windows/pyreadline/modes/notemacs.py
python
NotEmacsMode.backward_delete_char
(self, e)
Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.
Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.
[ "Delete", "the", "character", "behind", "the", "cursor", ".", "A", "numeric", "argument", "means", "to", "kill", "the", "characters", "instead", "of", "deleting", "them", "." ]
def backward_delete_char(self, e): # (Rubout) '''Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them.''' self.l_buffer.backward_delete_char()
[ "def", "backward_delete_char", "(", "self", ",", "e", ")", ":", "# (Rubout)", "self", ".", "l_buffer", ".", "backward_delete_char", "(", ")" ]
https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/modes/notemacs.py#L261-L264
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
DocMDIChildFrame.OnActivate
(self, event)
Sets the currently active view to be the frame's view. You may need to override (but still call) this function in order to set the keyboard focus for your subwindow.
Sets the currently active view to be the frame's view. You may need to override (but still call) this function in order to set the keyboard focus for your subwindow.
[ "Sets", "the", "currently", "active", "view", "to", "be", "the", "frame", "s", "view", ".", "You", "may", "need", "to", "override", "(", "but", "still", "call", ")", "this", "function", "in", "order", "to", "set", "the", "keyboard", "focus", "for", "your", "subwindow", "." ]
def OnActivate(self, event): """ Sets the currently active view to be the frame's view. You may need to override (but still call) this function in order to set the keyboard focus for your subwindow. """ event.Skip() if self._activated != 0: return True self._activated += 1 wx.MDIChildFrame.Activate(self) if event.GetActive() and self._childView: self._childView.Activate(event.GetActive()) self._activated = 0
[ "def", "OnActivate", "(", "self", ",", "event", ")", ":", "event", ".", "Skip", "(", ")", "if", "self", ".", "_activated", "!=", "0", ":", "return", "True", "self", ".", "_activated", "+=", "1", "wx", ".", "MDIChildFrame", ".", "Activate", "(", "self", ")", "if", "event", ".", "GetActive", "(", ")", "and", "self", ".", "_childView", ":", "self", ".", "_childView", ".", "Activate", "(", "event", ".", "GetActive", "(", ")", ")", "self", ".", "_activated", "=", "0" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L2800-L2813
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
resources/osm_importer/projection.py
python
Projection.project
(long, lat)
return (-z, x)
Return a projected coordinate.
Return a projected coordinate.
[ "Return", "a", "projected", "coordinate", "." ]
def project(long, lat): """Return a projected coordinate.""" if Projection.projection is None: sys.stderr.write("Warning: Projection.project() called before Projection.initProjection()\n") x, z = Projection.projection(long, lat) return (-z, x)
[ "def", "project", "(", "long", ",", "lat", ")", ":", "if", "Projection", ".", "projection", "is", "None", ":", "sys", ".", "stderr", ".", "write", "(", "\"Warning: Projection.project() called before Projection.initProjection()\\n\"", ")", "x", ",", "z", "=", "Projection", ".", "projection", "(", "long", ",", "lat", ")", "return", "(", "-", "z", ",", "x", ")" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/osm_importer/projection.py#L48-L53
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
Context.add
(self, a, b)
Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal('19.00') >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal('1.02E+4') >>> ExtendedContext.add(1, Decimal(2)) Decimal('3') >>> ExtendedContext.add(Decimal(8), 5) Decimal('13') >>> ExtendedContext.add(5, 5) Decimal('10')
Return the sum of the two operands.
[ "Return", "the", "sum", "of", "the", "two", "operands", "." ]
def add(self, a, b): """Return the sum of the two operands. >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) Decimal('19.00') >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) Decimal('1.02E+4') >>> ExtendedContext.add(1, Decimal(2)) Decimal('3') >>> ExtendedContext.add(Decimal(8), 5) Decimal('13') >>> ExtendedContext.add(5, 5) Decimal('10') """ a = _convert_other(a, raiseit=True) r = a.__add__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
[ "def", "add", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "r", "=", "a", ".", "__add__", "(", "b", ",", "context", "=", "self", ")", "if", "r", "is", "NotImplemented", ":", "raise", "TypeError", "(", "\"Unable to convert %s to Decimal\"", "%", "b", ")", "else", ":", "return", "r" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L3978-L3997
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/beast/python/beast/util/String.py
python
remove_comment
(line)
Remove trailing comments from one line.
Remove trailing comments from one line.
[ "Remove", "trailing", "comments", "from", "one", "line", "." ]
def remove_comment(line): """Remove trailing comments from one line.""" start = 0 while True: loc = line.find('#', start) if loc == -1: return line.replace('\\#', '#') elif not (loc and line[loc - 1] == '\\'): return line[:loc].replace('\\#', '#') start = loc + 1
[ "def", "remove_comment", "(", "line", ")", ":", "start", "=", "0", "while", "True", ":", "loc", "=", "line", ".", "find", "(", "'#'", ",", "start", ")", "if", "loc", "==", "-", "1", ":", "return", "line", ".", "replace", "(", "'\\\\#'", ",", "'#'", ")", "elif", "not", "(", "loc", "and", "line", "[", "loc", "-", "1", "]", "==", "'\\\\'", ")", ":", "return", "line", "[", ":", "loc", "]", ".", "replace", "(", "'\\\\#'", ",", "'#'", ")", "start", "=", "loc", "+", "1" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/beast/python/beast/util/String.py#L33-L42
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
third_party/Python/module/pexpect-4.6/pexpect/ANSI.py
python
ANSI.do_modecrap
(self, fsm)
Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone wanted to actually use these, they'd need to add more states to the FSM rather than just improve or override this method.
Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone wanted to actually use these, they'd need to add more states to the FSM rather than just improve or override this method.
[ "Handler", "for", "\\", "x1b", "[", "?<number", ">", "h", "and", "\\", "x1b", "[", "?<number", ">", "l", ".", "If", "anyone", "wanted", "to", "actually", "use", "these", "they", "d", "need", "to", "add", "more", "states", "to", "the", "FSM", "rather", "than", "just", "improve", "or", "override", "this", "method", "." ]
def do_modecrap (self, fsm): '''Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone wanted to actually use these, they'd need to add more states to the FSM rather than just improve or override this method. ''' screen = fsm.memory[0] fsm.memory = [screen]
[ "def", "do_modecrap", "(", "self", ",", "fsm", ")", ":", "screen", "=", "fsm", ".", "memory", "[", "0", "]", "fsm", ".", "memory", "=", "[", "screen", "]" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/ANSI.py#L346-L351
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/imports.py
python
KnowitHandler.parse_string_lines
(self, file_descriptor)
Parse the string line by line
Parse the string line by line
[ "Parse", "the", "string", "line", "by", "line" ]
def parse_string_lines(self, file_descriptor): """Parse the string line by line""" self.curr_xml_state = 0 self.curr_node_name = "" self.curr_node_content = "" self.curr_node_level = 0 self.former_node_level = -1 self.links_list = [] # 0: waiting for \NewEntry or \CurrentEntry # 1: gathering node content for text_line in file_descriptor: text_line = text_line.decode(cons.STR_UTF8, cons.STR_IGNORE) if self.curr_xml_state == 0: if text_line.startswith("\NewEntry ")\ or text_line.startswith("\CurrentEntry "): if text_line[1] == "N": text_to_parse = text_line[10:-1] else: text_to_parse = text_line[14:-1] match = re.match("(\d+) (.*)$", text_to_parse) if not match: print '%s' % text_to_parse self.curr_node_level = int(match.group(1)) self.curr_node_name = match.group(2) #print "node name = '%s', node level = %s" % (self.curr_node_name, self.curr_node_level) if self.curr_node_level <= self.former_node_level: for count in range(self.former_node_level - self.curr_node_level): self.nodes_list.pop() self.nodes_list.pop() self.former_node_level = self.curr_node_level self.curr_node_content = "" self.curr_xml_state = 1 self.nodes_list.append(self.dom.createElement("node")) self.nodes_list[-1].setAttribute("name", self.curr_node_name) self.nodes_list[-1].setAttribute("prog_lang", cons.RICH_TEXT_ID) self.nodes_list[-2].appendChild(self.nodes_list[-1]) else: self.curr_node_name += text_line.replace(cons.CHAR_CR, "").replace(cons.CHAR_NEWLINE, "") + cons.CHAR_SPACE elif self.curr_xml_state == 1: if text_line.startswith("\Link "): link_uri = text_line[6:-1] self.links_list.append([link_uri, ""]) elif text_line.startswith("\Descr "): link_desc = text_line[7:-1] self.links_list[-1][1] = link_desc elif text_line.endswith("</body></html>"+cons.CHAR_NEWLINE): # node content end self.curr_xml_state = 0 self.curr_html_state = 0 self.feed(self.curr_node_content.decode(cons.STR_UTF8, cons.STR_IGNORE)) if self.links_list: self.rich_text_serialize(cons.CHAR_NEWLINE) for link_element in self.links_list: if link_element[0][:4] in ["http", "file"]: if link_element[0][:4] == "http": self.curr_attributes[cons.TAG_LINK] = "webs %s" % link_element[0] elif link_element[0][:4] == "file": self.curr_attributes[cons.TAG_LINK] = "file %s" % base64.b64encode(link_element[0][7:]) self.rich_text_serialize(link_element[1]) self.curr_attributes[cons.TAG_LINK] = "" self.rich_text_serialize(cons.CHAR_NEWLINE) elif link_element[0].startswith("knowit://"): name_dest = link_element[0][9:] self.links_to_node_list.append({'name_dest':name_dest, 'name_source':self.curr_node_name, 'node_desc':link_element[1]}) self.links_list = [] elif self.curr_node_content == "" and text_line == cons.CHAR_NEWLINE: # empty node self.curr_xml_state = 0 self.curr_html_state = 0 else: self.curr_node_content += text_line
[ "def", "parse_string_lines", "(", "self", ",", "file_descriptor", ")", ":", "self", ".", "curr_xml_state", "=", "0", "self", ".", "curr_node_name", "=", "\"\"", "self", ".", "curr_node_content", "=", "\"\"", "self", ".", "curr_node_level", "=", "0", "self", ".", "former_node_level", "=", "-", "1", "self", ".", "links_list", "=", "[", "]", "# 0: waiting for \\NewEntry or \\CurrentEntry", "# 1: gathering node content", "for", "text_line", "in", "file_descriptor", ":", "text_line", "=", "text_line", ".", "decode", "(", "cons", ".", "STR_UTF8", ",", "cons", ".", "STR_IGNORE", ")", "if", "self", ".", "curr_xml_state", "==", "0", ":", "if", "text_line", ".", "startswith", "(", "\"\\NewEntry \"", ")", "or", "text_line", ".", "startswith", "(", "\"\\CurrentEntry \"", ")", ":", "if", "text_line", "[", "1", "]", "==", "\"N\"", ":", "text_to_parse", "=", "text_line", "[", "10", ":", "-", "1", "]", "else", ":", "text_to_parse", "=", "text_line", "[", "14", ":", "-", "1", "]", "match", "=", "re", ".", "match", "(", "\"(\\d+) (.*)$\"", ",", "text_to_parse", ")", "if", "not", "match", ":", "print", "'%s'", "%", "text_to_parse", "self", ".", "curr_node_level", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "self", ".", "curr_node_name", "=", "match", ".", "group", "(", "2", ")", "#print \"node name = '%s', node level = %s\" % (self.curr_node_name, self.curr_node_level)", "if", "self", ".", "curr_node_level", "<=", "self", ".", "former_node_level", ":", "for", "count", "in", "range", "(", "self", ".", "former_node_level", "-", "self", ".", "curr_node_level", ")", ":", "self", ".", "nodes_list", ".", "pop", "(", ")", "self", ".", "nodes_list", ".", "pop", "(", ")", "self", ".", "former_node_level", "=", "self", ".", "curr_node_level", "self", ".", "curr_node_content", "=", "\"\"", "self", ".", "curr_xml_state", "=", "1", "self", ".", "nodes_list", ".", "append", "(", "self", ".", "dom", ".", "createElement", "(", "\"node\"", ")", ")", "self", ".", "nodes_list", "[", "-", "1", "]", ".", "setAttribute", "(", "\"name\"", ",", "self", ".", "curr_node_name", ")", "self", ".", "nodes_list", "[", "-", "1", "]", ".", "setAttribute", "(", "\"prog_lang\"", ",", "cons", ".", "RICH_TEXT_ID", ")", "self", ".", "nodes_list", "[", "-", "2", "]", ".", "appendChild", "(", "self", ".", "nodes_list", "[", "-", "1", "]", ")", "else", ":", "self", ".", "curr_node_name", "+=", "text_line", ".", "replace", "(", "cons", ".", "CHAR_CR", ",", "\"\"", ")", ".", "replace", "(", "cons", ".", "CHAR_NEWLINE", ",", "\"\"", ")", "+", "cons", ".", "CHAR_SPACE", "elif", "self", ".", "curr_xml_state", "==", "1", ":", "if", "text_line", ".", "startswith", "(", "\"\\Link \"", ")", ":", "link_uri", "=", "text_line", "[", "6", ":", "-", "1", "]", "self", ".", "links_list", ".", "append", "(", "[", "link_uri", ",", "\"\"", "]", ")", "elif", "text_line", ".", "startswith", "(", "\"\\Descr \"", ")", ":", "link_desc", "=", "text_line", "[", "7", ":", "-", "1", "]", "self", ".", "links_list", "[", "-", "1", "]", "[", "1", "]", "=", "link_desc", "elif", "text_line", ".", "endswith", "(", "\"</body></html>\"", "+", "cons", ".", "CHAR_NEWLINE", ")", ":", "# node content end", "self", ".", "curr_xml_state", "=", "0", "self", ".", "curr_html_state", "=", "0", "self", ".", "feed", "(", "self", ".", "curr_node_content", ".", "decode", "(", "cons", ".", "STR_UTF8", ",", "cons", ".", "STR_IGNORE", ")", ")", "if", "self", ".", "links_list", ":", "self", ".", "rich_text_serialize", "(", "cons", ".", "CHAR_NEWLINE", ")", "for", "link_element", "in", "self", ".", "links_list", ":", "if", "link_element", "[", "0", "]", "[", ":", "4", "]", "in", "[", "\"http\"", ",", "\"file\"", "]", ":", "if", "link_element", "[", "0", "]", "[", ":", "4", "]", "==", "\"http\"", ":", "self", ".", "curr_attributes", "[", "cons", ".", "TAG_LINK", "]", "=", "\"webs %s\"", "%", "link_element", "[", "0", "]", "elif", "link_element", "[", "0", "]", "[", ":", "4", "]", "==", "\"file\"", ":", "self", ".", "curr_attributes", "[", "cons", ".", "TAG_LINK", "]", "=", "\"file %s\"", "%", "base64", ".", "b64encode", "(", "link_element", "[", "0", "]", "[", "7", ":", "]", ")", "self", ".", "rich_text_serialize", "(", "link_element", "[", "1", "]", ")", "self", ".", "curr_attributes", "[", "cons", ".", "TAG_LINK", "]", "=", "\"\"", "self", ".", "rich_text_serialize", "(", "cons", ".", "CHAR_NEWLINE", ")", "elif", "link_element", "[", "0", "]", ".", "startswith", "(", "\"knowit://\"", ")", ":", "name_dest", "=", "link_element", "[", "0", "]", "[", "9", ":", "]", "self", ".", "links_to_node_list", ".", "append", "(", "{", "'name_dest'", ":", "name_dest", ",", "'name_source'", ":", "self", ".", "curr_node_name", ",", "'node_desc'", ":", "link_element", "[", "1", "]", "}", ")", "self", ".", "links_list", "=", "[", "]", "elif", "self", ".", "curr_node_content", "==", "\"\"", "and", "text_line", "==", "cons", ".", "CHAR_NEWLINE", ":", "# empty node", "self", ".", "curr_xml_state", "=", "0", "self", ".", "curr_html_state", "=", "0", "else", ":", "self", ".", "curr_node_content", "+=", "text_line" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/imports.py#L1623-L1690
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/optim/optimizer.py
python
Optimizer.get_lr_parameter
(self, param)
return lr if isinstance(param, list) else lr[0]
When parameters is grouped and learning rate is different for each group. Get the learning rate of the specified `param`. Args: param (Union[Parameter, list[Parameter]]): The `Parameter` or list of `Parameter`. Returns: Parameter, single `Parameter` or `list[Parameter]` according to the input type. If learning rate is dynamic, `LearningRateSchedule` or `list[LearningRateSchedule]` that used to calculate the learning rate will be returned. Examples: >>> from mindspore import nn >>> net = Net() >>> conv_params = list(filter(lambda x: 'conv' in x.name, net.trainable_params())) >>> no_conv_params = list(filter(lambda x: 'conv' not in x.name, net.trainable_params())) >>> group_params = [{'params': conv_params, 'lr': 0.05}, ... {'params': no_conv_params, 'lr': 0.01}] >>> optim = nn.Momentum(group_params, learning_rate=0.1, momentum=0.9, weight_decay=0.0) >>> conv_lr = optim.get_lr_parameter(conv_params) >>> print(conv_lr[0].asnumpy()) 0.05
When parameters is grouped and learning rate is different for each group. Get the learning rate of the specified `param`.
[ "When", "parameters", "is", "grouped", "and", "learning", "rate", "is", "different", "for", "each", "group", ".", "Get", "the", "learning", "rate", "of", "the", "specified", "param", "." ]
def get_lr_parameter(self, param): """ When parameters is grouped and learning rate is different for each group. Get the learning rate of the specified `param`. Args: param (Union[Parameter, list[Parameter]]): The `Parameter` or list of `Parameter`. Returns: Parameter, single `Parameter` or `list[Parameter]` according to the input type. If learning rate is dynamic, `LearningRateSchedule` or `list[LearningRateSchedule]` that used to calculate the learning rate will be returned. Examples: >>> from mindspore import nn >>> net = Net() >>> conv_params = list(filter(lambda x: 'conv' in x.name, net.trainable_params())) >>> no_conv_params = list(filter(lambda x: 'conv' not in x.name, net.trainable_params())) >>> group_params = [{'params': conv_params, 'lr': 0.05}, ... {'params': no_conv_params, 'lr': 0.01}] >>> optim = nn.Momentum(group_params, learning_rate=0.1, momentum=0.9, weight_decay=0.0) >>> conv_lr = optim.get_lr_parameter(conv_params) >>> print(conv_lr[0].asnumpy()) 0.05 """ def get_lr_value(learning_rate): if isinstance(learning_rate, (_ConvertToCell, _IteratorLearningRate)): return learning_rate.learning_rate return learning_rate if isinstance(param, Parameter): param_list = [param] elif isinstance(param, list): param_list = param else: raise TypeError(f"For 'get_lr_parameter', the 'param' must be 'Parameter' or 'list' type, " f"but got {type(param)}.") lr = [] ids = [id(p) for p in self.parameters] for p in param_list: validator.check_value_type("parameter", p, [Parameter], self.cls_name) if id(p) not in ids: raise ValueError(f"For 'get_lr_parameter', the parameter {p.name} is not in optimizer, please check " f"whether the argument 'param' is correct.") if self.is_group_lr: index = ids.index(id(p)) lr.append(get_lr_value(self.learning_rate[index])) else: lr.append(get_lr_value(self.learning_rate)) return lr if isinstance(param, list) else lr[0]
[ "def", "get_lr_parameter", "(", "self", ",", "param", ")", ":", "def", "get_lr_value", "(", "learning_rate", ")", ":", "if", "isinstance", "(", "learning_rate", ",", "(", "_ConvertToCell", ",", "_IteratorLearningRate", ")", ")", ":", "return", "learning_rate", ".", "learning_rate", "return", "learning_rate", "if", "isinstance", "(", "param", ",", "Parameter", ")", ":", "param_list", "=", "[", "param", "]", "elif", "isinstance", "(", "param", ",", "list", ")", ":", "param_list", "=", "param", "else", ":", "raise", "TypeError", "(", "f\"For 'get_lr_parameter', the 'param' must be 'Parameter' or 'list' type, \"", "f\"but got {type(param)}.\"", ")", "lr", "=", "[", "]", "ids", "=", "[", "id", "(", "p", ")", "for", "p", "in", "self", ".", "parameters", "]", "for", "p", "in", "param_list", ":", "validator", ".", "check_value_type", "(", "\"parameter\"", ",", "p", ",", "[", "Parameter", "]", ",", "self", ".", "cls_name", ")", "if", "id", "(", "p", ")", "not", "in", "ids", ":", "raise", "ValueError", "(", "f\"For 'get_lr_parameter', the parameter {p.name} is not in optimizer, please check \"", "f\"whether the argument 'param' is correct.\"", ")", "if", "self", ".", "is_group_lr", ":", "index", "=", "ids", ".", "index", "(", "id", "(", "p", ")", ")", "lr", ".", "append", "(", "get_lr_value", "(", "self", ".", "learning_rate", "[", "index", "]", ")", ")", "else", ":", "lr", ".", "append", "(", "get_lr_value", "(", "self", ".", "learning_rate", ")", ")", "return", "lr", "if", "isinstance", "(", "param", ",", "list", ")", "else", "lr", "[", "0", "]" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/optim/optimizer.py#L598-L650
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
bin/diagnostics/experimental/plan-graph.py
python
DotParser.find_preceding_scans
(self, rf_id)
return ret
Given a runtime filter id, find all scan nodes that contribute towards that runtime filter creation.
Given a runtime filter id, find all scan nodes that contribute towards that runtime filter creation.
[ "Given", "a", "runtime", "filter", "id", "find", "all", "scan", "nodes", "that", "contribute", "towards", "that", "runtime", "filter", "creation", "." ]
def find_preceding_scans(self, rf_id): """Given a runtime filter id, find all scan nodes that contribute towards that runtime filter creation.""" ret = [] parent = self.rf_parent[rf_id] consumer_scans = set(self.edges[rf_id]) for child in self.edges[parent]: if child == rf_id: continue if not consumer_scans.intersection(self.successor_scans[child]): ret.extend(self.successor_scans[child]) return ret
[ "def", "find_preceding_scans", "(", "self", ",", "rf_id", ")", ":", "ret", "=", "[", "]", "parent", "=", "self", ".", "rf_parent", "[", "rf_id", "]", "consumer_scans", "=", "set", "(", "self", ".", "edges", "[", "rf_id", "]", ")", "for", "child", "in", "self", ".", "edges", "[", "parent", "]", ":", "if", "child", "==", "rf_id", ":", "continue", "if", "not", "consumer_scans", ".", "intersection", "(", "self", ".", "successor_scans", "[", "child", "]", ")", ":", "ret", ".", "extend", "(", "self", ".", "successor_scans", "[", "child", "]", ")", "return", "ret" ]
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/diagnostics/experimental/plan-graph.py#L247-L258
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/idl_parser/idl_parser.py
python
IDLParser.p_ExtendedAttributeIdentList
(self, p)
ExtendedAttributeIdentList : identifier '=' '(' IdentifierList ')
ExtendedAttributeIdentList : identifier '=' '(' IdentifierList ')
[ "ExtendedAttributeIdentList", ":", "identifier", "=", "(", "IdentifierList", ")" ]
def p_ExtendedAttributeIdentList(self, p): """ExtendedAttributeIdentList : identifier '=' '(' IdentifierList ')'""" value = self.BuildAttribute('VALUE', p[4]) p[0] = self.BuildNamed('ExtAttribute', p, 1, value)
[ "def", "p_ExtendedAttributeIdentList", "(", "self", ",", "p", ")", ":", "value", "=", "self", ".", "BuildAttribute", "(", "'VALUE'", ",", "p", "[", "4", "]", ")", "p", "[", "0", "]", "=", "self", ".", "BuildNamed", "(", "'ExtAttribute'", ",", "p", ",", "1", ",", "value", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_parser.py#L1078-L1081
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/base.py
python
Trackable._preload_simple_restoration
(self, name, shape)
return CheckpointInitialValue( checkpoint_position=checkpoint_position, shape=shape)
Return a dependency's value for restore-on-create. Note the restoration is not deleted; if for some reason preload is called and then not assigned to the variable (for example because a custom getter overrides the initializer), the assignment will still happen once the variable is tracked (determined based on checkpoint.restore_uid). Args: name: The object-local name of the dependency holding the variable's value. shape: The shape of the variable being loaded into. Returns: An callable for use as a variable's initializer/initial_value, or None if one should not be set (either because there was no variable with this name in the checkpoint or because it needs more complex deserialization). Any non-trivial deserialization will happen when the variable object is tracked.
Return a dependency's value for restore-on-create.
[ "Return", "a", "dependency", "s", "value", "for", "restore", "-", "on", "-", "create", "." ]
def _preload_simple_restoration(self, name, shape): """Return a dependency's value for restore-on-create. Note the restoration is not deleted; if for some reason preload is called and then not assigned to the variable (for example because a custom getter overrides the initializer), the assignment will still happen once the variable is tracked (determined based on checkpoint.restore_uid). Args: name: The object-local name of the dependency holding the variable's value. shape: The shape of the variable being loaded into. Returns: An callable for use as a variable's initializer/initial_value, or None if one should not be set (either because there was no variable with this name in the checkpoint or because it needs more complex deserialization). Any non-trivial deserialization will happen when the variable object is tracked. """ deferred_dependencies_list = self._deferred_dependencies.get(name, ()) if not deferred_dependencies_list: # Nothing to do; we don't have a restore for this dependency queued up. return for checkpoint_position in deferred_dependencies_list: if not checkpoint_position.is_simple_variable(): # If _any_ pending restoration is too complicated to fit in an # initializer (because it has dependencies, or because there are # multiple Tensors to restore), bail and let the general tracking code # handle it. return None checkpoint_position = max( deferred_dependencies_list, key=lambda restore: restore.checkpoint.restore_uid) return CheckpointInitialValue( checkpoint_position=checkpoint_position, shape=shape)
[ "def", "_preload_simple_restoration", "(", "self", ",", "name", ",", "shape", ")", ":", "deferred_dependencies_list", "=", "self", ".", "_deferred_dependencies", ".", "get", "(", "name", ",", "(", ")", ")", "if", "not", "deferred_dependencies_list", ":", "# Nothing to do; we don't have a restore for this dependency queued up.", "return", "for", "checkpoint_position", "in", "deferred_dependencies_list", ":", "if", "not", "checkpoint_position", ".", "is_simple_variable", "(", ")", ":", "# If _any_ pending restoration is too complicated to fit in an", "# initializer (because it has dependencies, or because there are", "# multiple Tensors to restore), bail and let the general tracking code", "# handle it.", "return", "None", "checkpoint_position", "=", "max", "(", "deferred_dependencies_list", ",", "key", "=", "lambda", "restore", ":", "restore", ".", "checkpoint", ".", "restore_uid", ")", "return", "CheckpointInitialValue", "(", "checkpoint_position", "=", "checkpoint_position", ",", "shape", "=", "shape", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/base.py#L725-L760
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
cmake/std/trilinosprhelpers/sysinfo/SysInfo.py
python
SysInfo.compute_num_usable_cores
(self, req_mem_gb_per_core=3.0, max_cores_allowed=32)
return output
Compute the number of usable cores given memory and size constraints for the problem. Steps: 1) compute max number of CPUs by cpu constraints: min(sys cores, max_cores_allowed) 2) compute max cores by mem constraints: sys_mem_GB / req_mem_gb_per_core 3) return min of (1) and (2) Args: req_mem_gb_per_core (float): The minimum memory (GB) per core required. Default=3.0 max_cores_allowed (int) : The maximum number of cores to use. Default=32 Returns: int: Returns the minimum of (1) and (2)
Compute the number of usable cores given memory and size constraints for the problem.
[ "Compute", "the", "number", "of", "usable", "cores", "given", "memory", "and", "size", "constraints", "for", "the", "problem", "." ]
def compute_num_usable_cores(self, req_mem_gb_per_core=3.0, max_cores_allowed=32): """ Compute the number of usable cores given memory and size constraints for the problem. Steps: 1) compute max number of CPUs by cpu constraints: min(sys cores, max_cores_allowed) 2) compute max cores by mem constraints: sys_mem_GB / req_mem_gb_per_core 3) return min of (1) and (2) Args: req_mem_gb_per_core (float): The minimum memory (GB) per core required. Default=3.0 max_cores_allowed (int) : The maximum number of cores to use. Default=32 Returns: int: Returns the minimum of (1) and (2) """ if max_cores_allowed < 1: max_cores_allowed = 1 output = 1 n_cpu = multiprocessing.cpu_count() mem_G = self.meminfo["mem_gb"] max_cpu_by_param_constraint = min(n_cpu, max_cores_allowed) max_cpu_by_mem_constraint = int(mem_G / req_mem_gb_per_core) output = min(max_cpu_by_mem_constraint, max_cpu_by_param_constraint) return output
[ "def", "compute_num_usable_cores", "(", "self", ",", "req_mem_gb_per_core", "=", "3.0", ",", "max_cores_allowed", "=", "32", ")", ":", "if", "max_cores_allowed", "<", "1", ":", "max_cores_allowed", "=", "1", "output", "=", "1", "n_cpu", "=", "multiprocessing", ".", "cpu_count", "(", ")", "mem_G", "=", "self", ".", "meminfo", "[", "\"mem_gb\"", "]", "max_cpu_by_param_constraint", "=", "min", "(", "n_cpu", ",", "max_cores_allowed", ")", "max_cpu_by_mem_constraint", "=", "int", "(", "mem_G", "/", "req_mem_gb_per_core", ")", "output", "=", "min", "(", "max_cpu_by_mem_constraint", ",", "max_cpu_by_param_constraint", ")", "return", "output" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/cmake/std/trilinosprhelpers/sysinfo/SysInfo.py#L119-L149
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/emscripten/1.37.19/site/source/get_wiki.py
python
CloneWiki
()
Clone the wiki into a temporary location (first cleaning)
Clone the wiki into a temporary location (first cleaning)
[ "Clone", "the", "wiki", "into", "a", "temporary", "location", "(", "first", "cleaning", ")" ]
def CloneWiki(): """ Clone the wiki into a temporary location (first cleaning) """ # Clean up existing repo CleanWiki() # Create directory for output and temporary files try: os.makedirs(wiki_directory) os.makedirs(wiki_temp_directory) print 'Created directory' except: pass # Clone git_clone_command = 'git clone %s %s' % (wiki_repo, wiki_temp_directory) #print git_clone_command os.system(git_clone_command)
[ "def", "CloneWiki", "(", ")", ":", "# Clean up existing repo", "CleanWiki", "(", ")", "# Create directory for output and temporary files", "try", ":", "os", ".", "makedirs", "(", "wiki_directory", ")", "os", ".", "makedirs", "(", "wiki_temp_directory", ")", "print", "'Created directory'", "except", ":", "pass", "# Clone", "git_clone_command", "=", "'git clone %s %s'", "%", "(", "wiki_repo", ",", "wiki_temp_directory", ")", "#print git_clone_command", "os", ".", "system", "(", "git_clone_command", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/emscripten/1.37.19/site/source/get_wiki.py#L77-L96
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/modeling/parameter_sharing.py
python
ParameterSharing
(shared_scopes)
Helper function for sharing scopes. All the parameters within the shared_scopes, will be remapped with the respect of CurrentNamescope() I.e. if one calls ParameterSharing with {'scope_b': 'scope_'a'}, from the scope 'some_global_scope', it'll effectively mean, that all parameters from 'some_global_scope/scope_b' will shared with the parameters from 'some_global_scope/scope_a'
Helper function for sharing scopes. All the parameters within the shared_scopes, will be remapped with the respect of CurrentNamescope()
[ "Helper", "function", "for", "sharing", "scopes", ".", "All", "the", "parameters", "within", "the", "shared_scopes", "will", "be", "remapped", "with", "the", "respect", "of", "CurrentNamescope", "()" ]
def ParameterSharing(shared_scopes): """ Helper function for sharing scopes. All the parameters within the shared_scopes, will be remapped with the respect of CurrentNamescope() I.e. if one calls ParameterSharing with {'scope_b': 'scope_'a'}, from the scope 'some_global_scope', it'll effectively mean, that all parameters from 'some_global_scope/scope_b' will shared with the parameters from 'some_global_scope/scope_a' """ assert isinstance(shared_scopes, dict) shared_scope_overrides = {} current_scope = scope.CurrentNameScope() for k, v in shared_scopes.items(): assert not v.startswith(k), ( "Illegal override for parameter sharing. {} is prefix of {}". format(k, v)) k = current_scope + k v = current_scope + v # Normalize all the scopes, so scope_a and scope_a/ are equivalent k = _normalize_namescope(k) v = _normalize_namescope(v) shared_scope_overrides[k] = v try: parameter_sharing_context.add_scope_overrides(shared_scope_overrides) yield finally: parameter_sharing_context.pop()
[ "def", "ParameterSharing", "(", "shared_scopes", ")", ":", "assert", "isinstance", "(", "shared_scopes", ",", "dict", ")", "shared_scope_overrides", "=", "{", "}", "current_scope", "=", "scope", ".", "CurrentNameScope", "(", ")", "for", "k", ",", "v", "in", "shared_scopes", ".", "items", "(", ")", ":", "assert", "not", "v", ".", "startswith", "(", "k", ")", ",", "(", "\"Illegal override for parameter sharing. {} is prefix of {}\"", ".", "format", "(", "k", ",", "v", ")", ")", "k", "=", "current_scope", "+", "k", "v", "=", "current_scope", "+", "v", "# Normalize all the scopes, so scope_a and scope_a/ are equivalent", "k", "=", "_normalize_namescope", "(", "k", ")", "v", "=", "_normalize_namescope", "(", "v", ")", "shared_scope_overrides", "[", "k", "]", "=", "v", "try", ":", "parameter_sharing_context", ".", "add_scope_overrides", "(", "shared_scope_overrides", ")", "yield", "finally", ":", "parameter_sharing_context", ".", "pop", "(", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/modeling/parameter_sharing.py#L88-L118
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pswindows.py
python
net_if_stats
()
return ret
Get NIC stats (isup, duplex, speed, mtu).
Get NIC stats (isup, duplex, speed, mtu).
[ "Get", "NIC", "stats", "(", "isup", "duplex", "speed", "mtu", ")", "." ]
def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" ret = {} rawdict = cext.net_if_stats() for name, items in rawdict.items(): if not PY3: assert isinstance(name, unicode), type(name) name = py2_strencode(name) isup, duplex, speed, mtu = items if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) ret[name] = _common.snicstats(isup, duplex, speed, mtu) return ret
[ "def", "net_if_stats", "(", ")", ":", "ret", "=", "{", "}", "rawdict", "=", "cext", ".", "net_if_stats", "(", ")", "for", "name", ",", "items", "in", "rawdict", ".", "items", "(", ")", ":", "if", "not", "PY3", ":", "assert", "isinstance", "(", "name", ",", "unicode", ")", ",", "type", "(", "name", ")", "name", "=", "py2_strencode", "(", "name", ")", "isup", ",", "duplex", ",", "speed", ",", "mtu", "=", "items", "if", "hasattr", "(", "_common", ",", "'NicDuplex'", ")", ":", "duplex", "=", "_common", ".", "NicDuplex", "(", "duplex", ")", "ret", "[", "name", "]", "=", "_common", ".", "snicstats", "(", "isup", ",", "duplex", ",", "speed", ",", "mtu", ")", "return", "ret" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pswindows.py#L369-L381
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/graph_kernel/model/model.py
python
Utils.get_attr_type
(attr)
Get attr type
Get attr type
[ "Get", "attr", "type" ]
def get_attr_type(attr): """Get attr type""" if isinstance(attr, bool): return 'bool' if isinstance(attr, str): return 'str' if isinstance(attr, int): return 'int' if isinstance(attr, float): return 'bool' if isinstance(attr, (list, tuple)): if not attr: raise ValueError("Length of attr is 0") if isinstance(attr[0], int): return 'listInt' if isinstance(attr[0], str): return 'listStr' raise ValueError("Unknown type of attr: {}".format(attr))
[ "def", "get_attr_type", "(", "attr", ")", ":", "if", "isinstance", "(", "attr", ",", "bool", ")", ":", "return", "'bool'", "if", "isinstance", "(", "attr", ",", "str", ")", ":", "return", "'str'", "if", "isinstance", "(", "attr", ",", "int", ")", ":", "return", "'int'", "if", "isinstance", "(", "attr", ",", "float", ")", ":", "return", "'bool'", "if", "isinstance", "(", "attr", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "attr", ":", "raise", "ValueError", "(", "\"Length of attr is 0\"", ")", "if", "isinstance", "(", "attr", "[", "0", "]", ",", "int", ")", ":", "return", "'listInt'", "if", "isinstance", "(", "attr", "[", "0", "]", ",", "str", ")", ":", "return", "'listStr'", "raise", "ValueError", "(", "\"Unknown type of attr: {}\"", ".", "format", "(", "attr", ")", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/model/model.py#L25-L42
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/nyan/nyan_structs.py
python
NyanMember.dump
(self, indent_depth, import_tree=None, namespace=None)
return output_str
Returns the nyan string representation of the member.
Returns the nyan string representation of the member.
[ "Returns", "the", "nyan", "string", "representation", "of", "the", "member", "." ]
def dump(self, indent_depth, import_tree=None, namespace=None): """ Returns the nyan string representation of the member. """ output_str = f"{self.name} : {self._member_type.dump()}" if self.is_initialized(): output_str += " %s%s %s" % ("@" * self._override_depth, self._operator.value, self._get_value_str( indent_depth, import_tree=import_tree, namespace=namespace )) return output_str
[ "def", "dump", "(", "self", ",", "indent_depth", ",", "import_tree", "=", "None", ",", "namespace", "=", "None", ")", ":", "output_str", "=", "f\"{self.name} : {self._member_type.dump()}\"", "if", "self", ".", "is_initialized", "(", ")", ":", "output_str", "+=", "\" %s%s %s\"", "%", "(", "\"@\"", "*", "self", ".", "_override_depth", ",", "self", ".", "_operator", ".", "value", ",", "self", ".", "_get_value_str", "(", "indent_depth", ",", "import_tree", "=", "import_tree", ",", "namespace", "=", "namespace", ")", ")", "return", "output_str" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/nyan/nyan_structs.py#L966-L981
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/example.py
python
delete_file
(path)
Delete the specified file. For example: >>> os.mkdir('/test') >>> os.path.exists('/test/file.txt') False >>> create_file('/test/file.txt') >>> os.path.exists('/test/file.txt') True >>> delete_file('/test/file.txt') >>> os.path.exists('/test/file.txt') False
Delete the specified file. For example: >>> os.mkdir('/test') >>> os.path.exists('/test/file.txt') False >>> create_file('/test/file.txt') >>> os.path.exists('/test/file.txt') True >>> delete_file('/test/file.txt') >>> os.path.exists('/test/file.txt') False
[ "Delete", "the", "specified", "file", ".", "For", "example", ":", ">>>", "os", ".", "mkdir", "(", "/", "test", ")", ">>>", "os", ".", "path", ".", "exists", "(", "/", "test", "/", "file", ".", "txt", ")", "False", ">>>", "create_file", "(", "/", "test", "/", "file", ".", "txt", ")", ">>>", "os", ".", "path", ".", "exists", "(", "/", "test", "/", "file", ".", "txt", ")", "True", ">>>", "delete_file", "(", "/", "test", "/", "file", ".", "txt", ")", ">>>", "os", ".", "path", ".", "exists", "(", "/", "test", "/", "file", ".", "txt", ")", "False" ]
def delete_file(path): '''Delete the specified file. For example: >>> os.mkdir('/test') >>> os.path.exists('/test/file.txt') False >>> create_file('/test/file.txt') >>> os.path.exists('/test/file.txt') True >>> delete_file('/test/file.txt') >>> os.path.exists('/test/file.txt') False ''' os.remove(path)
[ "def", "delete_file", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/example.py#L70-L85
NeoGeographyToolkit/StereoPipeline
eedf54a919fb5cce1ab0e280bb0df4050763aa11
src/asp/IceBridge/fetcher_script.py
python
workDirs
()
return (pfePath, lfePath)
When fetching data, return the paths where it is stored temporarily on pfe, and for archival, on lou.
When fetching data, return the paths where it is stored temporarily on pfe, and for archival, on lou.
[ "When", "fetching", "data", "return", "the", "paths", "where", "it", "is", "stored", "temporarily", "on", "pfe", "and", "for", "archival", "on", "lou", "." ]
def workDirs(): '''When fetching data, return the paths where it is stored temporarily on pfe, and for archival, on lou.''' currDir = os.getcwd() m = re.match("^.*?/" + louUser + "/(.*?)$", currDir) if not m: raise Exception("Could not match %s in %s " % (louUser, currDir)) pfePath = '/nobackupp7/' + louUser + '/' + m.group(1) # path on pfe lfePath = '/u/' + louUser + '/' + m.group(1) # path on lfe return (pfePath, lfePath)
[ "def", "workDirs", "(", ")", ":", "currDir", "=", "os", ".", "getcwd", "(", ")", "m", "=", "re", ".", "match", "(", "\"^.*?/\"", "+", "louUser", "+", "\"/(.*?)$\"", ",", "currDir", ")", "if", "not", "m", ":", "raise", "Exception", "(", "\"Could not match %s in %s \"", "%", "(", "louUser", ",", "currDir", ")", ")", "pfePath", "=", "'/nobackupp7/'", "+", "louUser", "+", "'/'", "+", "m", ".", "group", "(", "1", ")", "# path on pfe", "lfePath", "=", "'/u/'", "+", "louUser", "+", "'/'", "+", "m", ".", "group", "(", "1", ")", "# path on lfe", "return", "(", "pfePath", ",", "lfePath", ")" ]
https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/fetcher_script.py#L68-L78
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBTypeSynthetic_CreateWithScriptCode
(data, options=0)
return _lldb.SBTypeSynthetic_CreateWithScriptCode(data, options)
CreateWithScriptCode(char const * data, uint32_t options=0) -> SBTypeSynthetic SBTypeSynthetic_CreateWithScriptCode(char const * data) -> SBTypeSynthetic
CreateWithScriptCode(char const * data, uint32_t options=0) -> SBTypeSynthetic SBTypeSynthetic_CreateWithScriptCode(char const * data) -> SBTypeSynthetic
[ "CreateWithScriptCode", "(", "char", "const", "*", "data", "uint32_t", "options", "=", "0", ")", "-", ">", "SBTypeSynthetic", "SBTypeSynthetic_CreateWithScriptCode", "(", "char", "const", "*", "data", ")", "-", ">", "SBTypeSynthetic" ]
def SBTypeSynthetic_CreateWithScriptCode(data, options=0): """ CreateWithScriptCode(char const * data, uint32_t options=0) -> SBTypeSynthetic SBTypeSynthetic_CreateWithScriptCode(char const * data) -> SBTypeSynthetic """ return _lldb.SBTypeSynthetic_CreateWithScriptCode(data, options)
[ "def", "SBTypeSynthetic_CreateWithScriptCode", "(", "data", ",", "options", "=", "0", ")", ":", "return", "_lldb", ".", "SBTypeSynthetic_CreateWithScriptCode", "(", "data", ",", "options", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L14091-L14096
Illumina/hap.py
84011695b2ff2406c16a335106db6831fb67fdfe
src/python/Tools/parallel.py
python
runParallel
(pool, fun, par, *args, **kwargs)
return result
run a function in parallel on all elements in par :param pool: multiprocessing.Pool or None :param fun: a function :param par: a list of things to map to (each item is passed as the first argument to fun) :param args: more function arguments for fun :param kwargs: more function arguments for fun
run a function in parallel on all elements in par
[ "run", "a", "function", "in", "parallel", "on", "all", "elements", "in", "par" ]
def runParallel(pool, fun, par, *args, **kwargs): """ run a function in parallel on all elements in par :param pool: multiprocessing.Pool or None :param fun: a function :param par: a list of things to map to (each item is passed as the first argument to fun) :param args: more function arguments for fun :param kwargs: more function arguments for fun """ if pool: result = pool.map(parMapper, izip(par, repeat( { "fun": fun, "args": args, "kwargs": kwargs } ))) else: result = [] for c in par: result.append(parMapper( (c, { "fun": fun, "args": args, "kwargs": kwargs } ) )) return result
[ "def", "runParallel", "(", "pool", ",", "fun", ",", "par", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "pool", ":", "result", "=", "pool", ".", "map", "(", "parMapper", ",", "izip", "(", "par", ",", "repeat", "(", "{", "\"fun\"", ":", "fun", ",", "\"args\"", ":", "args", ",", "\"kwargs\"", ":", "kwargs", "}", ")", ")", ")", "else", ":", "result", "=", "[", "]", "for", "c", "in", "par", ":", "result", ".", "append", "(", "parMapper", "(", "(", "c", ",", "{", "\"fun\"", ":", "fun", ",", "\"args\"", ":", "args", ",", "\"kwargs\"", ":", "kwargs", "}", ")", ")", ")", "return", "result" ]
https://github.com/Illumina/hap.py/blob/84011695b2ff2406c16a335106db6831fb67fdfe/src/python/Tools/parallel.py#L85-L101
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TMOut.GetCrLfLn
(self)
return _snap.TMOut_GetCrLfLn(self)
GetCrLfLn(TMOut self) -> TStr Parameters: self: TMOut *
GetCrLfLn(TMOut self) -> TStr
[ "GetCrLfLn", "(", "TMOut", "self", ")", "-", ">", "TStr" ]
def GetCrLfLn(self): """ GetCrLfLn(TMOut self) -> TStr Parameters: self: TMOut * """ return _snap.TMOut_GetCrLfLn(self)
[ "def", "GetCrLfLn", "(", "self", ")", ":", "return", "_snap", ".", "TMOut_GetCrLfLn", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L3109-L3117
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/utils.py
python
infer_storage_options
(urlpath, inherit_storage_options=None)
return options
Infer storage options from URL path and merge it with existing storage options. Parameters ---------- urlpath: str or unicode Either local absolute file path or URL (hdfs://namenode:8020/file.csv) inherit_storage_options: dict (optional) Its contents will get merged with the inferred information from the given path Returns ------- Storage options dict. Examples -------- >>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP {"protocol": "file", "path", "/mnt/datasets/test.csv"} >>> infer_storage_options( ... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1', ... inherit_storage_options={'extra': 'value'}) # doctest: +SKIP {"protocol": "hdfs", "username": "username", "password": "pwd", "host": "node", "port": 123, "path": "/mnt/datasets/test.csv", "url_query": "q=1", "extra": "value"}
Infer storage options from URL path and merge it with existing storage options.
[ "Infer", "storage", "options", "from", "URL", "path", "and", "merge", "it", "with", "existing", "storage", "options", "." ]
def infer_storage_options(urlpath, inherit_storage_options=None): """ Infer storage options from URL path and merge it with existing storage options. Parameters ---------- urlpath: str or unicode Either local absolute file path or URL (hdfs://namenode:8020/file.csv) inherit_storage_options: dict (optional) Its contents will get merged with the inferred information from the given path Returns ------- Storage options dict. Examples -------- >>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP {"protocol": "file", "path", "/mnt/datasets/test.csv"} >>> infer_storage_options( ... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1', ... inherit_storage_options={'extra': 'value'}) # doctest: +SKIP {"protocol": "hdfs", "username": "username", "password": "pwd", "host": "node", "port": 123, "path": "/mnt/datasets/test.csv", "url_query": "q=1", "extra": "value"} """ # Handle Windows paths including disk name in this special case if ( re.match(r"^[a-zA-Z]:[\\/]", urlpath) or re.match(r"^[a-zA-Z0-9]+://", urlpath) is None ): return {"protocol": "file", "path": urlpath} parsed_path = urlsplit(urlpath) protocol = parsed_path.scheme or "file" if parsed_path.fragment: path = "#".join([parsed_path.path, parsed_path.fragment]) else: path = parsed_path.path if protocol == "file": # Special case parsing file protocol URL on Windows according to: # https://msdn.microsoft.com/en-us/library/jj710207.aspx windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path) if windows_path: path = "%s:%s" % windows_path.groups() if protocol in ["http", "https"]: # for HTTP, we don't want to parse, as requests will anyway return {"protocol": protocol, "path": urlpath} options = {"protocol": protocol, "path": path} if parsed_path.netloc: # Parse `hostname` from netloc manually because `parsed_path.hostname` # lowercases the hostname which is not always desirable (e.g. in S3): # https://github.com/dask/dask/issues/1417 options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0] if protocol in ("s3", "gcs", "gs"): options["path"] = options["host"] + options["path"] else: options["host"] = options["host"] if parsed_path.port: options["port"] = parsed_path.port if parsed_path.username: options["username"] = parsed_path.username if parsed_path.password: options["password"] = parsed_path.password if parsed_path.query: options["url_query"] = parsed_path.query if parsed_path.fragment: options["url_fragment"] = parsed_path.fragment if inherit_storage_options: update_storage_options(options, inherit_storage_options) return options
[ "def", "infer_storage_options", "(", "urlpath", ",", "inherit_storage_options", "=", "None", ")", ":", "# Handle Windows paths including disk name in this special case", "if", "(", "re", ".", "match", "(", "r\"^[a-zA-Z]:[\\\\/]\"", ",", "urlpath", ")", "or", "re", ".", "match", "(", "r\"^[a-zA-Z0-9]+://\"", ",", "urlpath", ")", "is", "None", ")", ":", "return", "{", "\"protocol\"", ":", "\"file\"", ",", "\"path\"", ":", "urlpath", "}", "parsed_path", "=", "urlsplit", "(", "urlpath", ")", "protocol", "=", "parsed_path", ".", "scheme", "or", "\"file\"", "if", "parsed_path", ".", "fragment", ":", "path", "=", "\"#\"", ".", "join", "(", "[", "parsed_path", ".", "path", ",", "parsed_path", ".", "fragment", "]", ")", "else", ":", "path", "=", "parsed_path", ".", "path", "if", "protocol", "==", "\"file\"", ":", "# Special case parsing file protocol URL on Windows according to:", "# https://msdn.microsoft.com/en-us/library/jj710207.aspx", "windows_path", "=", "re", ".", "match", "(", "r\"^/([a-zA-Z])[:|]([\\\\/].*)$\"", ",", "path", ")", "if", "windows_path", ":", "path", "=", "\"%s:%s\"", "%", "windows_path", ".", "groups", "(", ")", "if", "protocol", "in", "[", "\"http\"", ",", "\"https\"", "]", ":", "# for HTTP, we don't want to parse, as requests will anyway", "return", "{", "\"protocol\"", ":", "protocol", ",", "\"path\"", ":", "urlpath", "}", "options", "=", "{", "\"protocol\"", ":", "protocol", ",", "\"path\"", ":", "path", "}", "if", "parsed_path", ".", "netloc", ":", "# Parse `hostname` from netloc manually because `parsed_path.hostname`", "# lowercases the hostname which is not always desirable (e.g. in S3):", "# https://github.com/dask/dask/issues/1417", "options", "[", "\"host\"", "]", "=", "parsed_path", ".", "netloc", ".", "rsplit", "(", "\"@\"", ",", "1", ")", "[", "-", "1", "]", ".", "rsplit", "(", "\":\"", ",", "1", ")", "[", "0", "]", "if", "protocol", "in", "(", "\"s3\"", ",", "\"gcs\"", ",", "\"gs\"", ")", ":", "options", "[", "\"path\"", "]", "=", "options", "[", "\"host\"", "]", "+", "options", "[", "\"path\"", "]", "else", ":", "options", "[", "\"host\"", "]", "=", "options", "[", "\"host\"", "]", "if", "parsed_path", ".", "port", ":", "options", "[", "\"port\"", "]", "=", "parsed_path", ".", "port", "if", "parsed_path", ".", "username", ":", "options", "[", "\"username\"", "]", "=", "parsed_path", ".", "username", "if", "parsed_path", ".", "password", ":", "options", "[", "\"password\"", "]", "=", "parsed_path", ".", "password", "if", "parsed_path", ".", "query", ":", "options", "[", "\"url_query\"", "]", "=", "parsed_path", ".", "query", "if", "parsed_path", ".", "fragment", ":", "options", "[", "\"url_fragment\"", "]", "=", "parsed_path", ".", "fragment", "if", "inherit_storage_options", ":", "update_storage_options", "(", "options", ",", "inherit_storage_options", ")", "return", "options" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/utils.py#L12-L90
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
docs/tutorials/Boosting-classifier-accuracy-by-grouping-categories/pets_callback.py
python
get_image_from_camera
(camera)
return None
Function to return an image from our camera using OpenCV
Function to return an image from our camera using OpenCV
[ "Function", "to", "return", "an", "image", "from", "our", "camera", "using", "OpenCV" ]
def get_image_from_camera(camera): """Function to return an image from our camera using OpenCV""" if camera: # if predictor is too slow frames get buffered, this is designed to # flush that buffer ret, frame = camera.read() if not ret: raise Exception("your capture device is not returning images") return frame return None
[ "def", "get_image_from_camera", "(", "camera", ")", ":", "if", "camera", ":", "# if predictor is too slow frames get buffered, this is designed to", "# flush that buffer", "ret", ",", "frame", "=", "camera", ".", "read", "(", ")", "if", "not", "ret", ":", "raise", "Exception", "(", "\"your capture device is not returning images\"", ")", "return", "frame", "return", "None" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/docs/tutorials/Boosting-classifier-accuracy-by-grouping-categories/pets_callback.py#L20-L29
xenia-project/xenia
9b1fdac98665ac091b9660a5d0fbb259ed79e578
third_party/google-styleguide/cpplint/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L697-L701
liulei01/DRBox
b5c76e033c555c9009590ab384e1f7bd3c66c237
scripts/cpp_lint.py
python
CheckForIncludeWhatYouUse
(filename, clean_lines, include_state, error, io=codecs)
Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection.
Reports for missing stl includes.
[ "Reports", "for", "missing", "stl", "includes", "." ]
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's copy the include_state so it is only messed up within this function. include_state = include_state.copy() # Did we find the header for this file (if any) and succesfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_state is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_state.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_state, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_state: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template)
[ "def", "CheckForIncludeWhatYouUse", "(", "filename", ",", "clean_lines", ",", "include_state", ",", "error", ",", "io", "=", "codecs", ")", ":", "required", "=", "{", "}", "# A map of header name to linenumber and the template entity.", "# Example of required: { '<functional>': (1219, 'less<>') }", "for", "linenum", "in", "xrange", "(", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "not", "line", "or", "line", "[", "0", "]", "==", "'#'", ":", "continue", "# String is special -- it is a non-templatized type in STL.", "matched", "=", "_RE_PATTERN_STRING", ".", "search", "(", "line", ")", "if", "matched", ":", "# Don't warn about strings in non-STL namespaces:", "# (We check only the first match per line; good enough.)", "prefix", "=", "line", "[", ":", "matched", ".", "start", "(", ")", "]", "if", "prefix", ".", "endswith", "(", "'std::'", ")", "or", "not", "prefix", ".", "endswith", "(", "'::'", ")", ":", "required", "[", "'<string>'", "]", "=", "(", "linenum", ",", "'string'", ")", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_algorithm_header", ":", "if", "pattern", ".", "search", "(", "line", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The following function is just a speed up, no semantics are changed.", "if", "not", "'<'", "in", "line", ":", "# Reduces the cpu time usage by skipping lines.", "continue", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_templates", ":", "if", "pattern", ".", "search", "(", "line", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The policy is that if you #include something in foo.h you don't need to", "# include it again in foo.cc. Here, we will look at possible includes.", "# Let's copy the include_state so it is only messed up within this function.", "include_state", "=", "include_state", ".", "copy", "(", ")", "# Did we find the header for this file (if any) and succesfully load it?", "header_found", "=", "False", "# Use the absolute path so that matching works properly.", "abs_filename", "=", "FileInfo", "(", "filename", ")", ".", "FullName", "(", ")", "# For Emacs's flymake.", "# If cpplint is invoked from Emacs's flymake, a temporary file is generated", "# by flymake and that file name might end with '_flymake.cc'. In that case,", "# restore original file name here so that the corresponding header file can be", "# found.", "# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'", "# instead of 'foo_flymake.h'", "abs_filename", "=", "re", ".", "sub", "(", "r'_flymake\\.cc$'", ",", "'.cc'", ",", "abs_filename", ")", "# include_state is modified during iteration, so we iterate over a copy of", "# the keys.", "header_keys", "=", "include_state", ".", "keys", "(", ")", "for", "header", "in", "header_keys", ":", "(", "same_module", ",", "common_path", ")", "=", "FilesBelongToSameModule", "(", "abs_filename", ",", "header", ")", "fullpath", "=", "common_path", "+", "header", "if", "same_module", "and", "UpdateIncludeState", "(", "fullpath", ",", "include_state", ",", "io", ")", ":", "header_found", "=", "True", "# If we can't find the header file for a .cc, assume it's because we don't", "# know where to look. In that case we'll give up as we're not sure they", "# didn't include it in the .h file.", "# TODO(unknown): Do a better job of finding .h files so we are confident that", "# not having the .h file means there isn't one.", "if", "filename", ".", "endswith", "(", "'.cc'", ")", "and", "not", "header_found", ":", "return", "# All the lines have been processed, report the errors found.", "for", "required_header_unstripped", "in", "required", ":", "template", "=", "required", "[", "required_header_unstripped", "]", "[", "1", "]", "if", "required_header_unstripped", ".", "strip", "(", "'<>\"'", ")", "not", "in", "include_state", ":", "error", "(", "filename", ",", "required", "[", "required_header_unstripped", "]", "[", "0", "]", ",", "'build/include_what_you_use'", ",", "4", ",", "'Add #include '", "+", "required_header_unstripped", "+", "' for '", "+", "template", ")" ]
https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/scripts/cpp_lint.py#L4487-L4577
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/ndarray/ndarray.py
python
NDArray.__idiv__
(self, other)
x.__rdiv__(y) <=> x/=y
x.__rdiv__(y) <=> x/=y
[ "x", ".", "__rdiv__", "(", "y", ")", "<", "=", ">", "x", "/", "=", "y" ]
def __idiv__(self, other): """x.__rdiv__(y) <=> x/=y """ if not self.writable: raise ValueError('trying to divide from a readonly NDArray') if isinstance(other, NDArray): return op.broadcast_div(self, other, out=self) elif isinstance(other, numeric_types): return _internal._div_scalar(self, float(other), out=self) else: raise TypeError('type %s not supported' % str(type(other)))
[ "def", "__idiv__", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "writable", ":", "raise", "ValueError", "(", "'trying to divide from a readonly NDArray'", ")", "if", "isinstance", "(", "other", ",", "NDArray", ")", ":", "return", "op", ".", "broadcast_div", "(", "self", ",", "other", ",", "out", "=", "self", ")", "elif", "isinstance", "(", "other", ",", "numeric_types", ")", ":", "return", "_internal", ".", "_div_scalar", "(", "self", ",", "float", "(", "other", ")", ",", "out", "=", "self", ")", "else", ":", "raise", "TypeError", "(", "'type %s not supported'", "%", "str", "(", "type", "(", "other", ")", ")", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L275-L284
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGridInterface.GetPropertyBackgroundColour
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetPropertyBackgroundColour(*args, **kwargs)
GetPropertyBackgroundColour(self, PGPropArg id) -> Colour
GetPropertyBackgroundColour(self, PGPropArg id) -> Colour
[ "GetPropertyBackgroundColour", "(", "self", "PGPropArg", "id", ")", "-", ">", "Colour" ]
def GetPropertyBackgroundColour(*args, **kwargs): """GetPropertyBackgroundColour(self, PGPropArg id) -> Colour""" return _propgrid.PropertyGridInterface_GetPropertyBackgroundColour(*args, **kwargs)
[ "def", "GetPropertyBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetPropertyBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1397-L1399
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_trotting_env.py
python
MinitaurTrottingEnv._get_observation_upper_bound
(self)
return np.array(upper_bound)
Get the upper bound of the observation. Returns: A numpy array contains the upper bound of an observation. See GetObservation() for the details of each element of an observation.
Get the upper bound of the observation.
[ "Get", "the", "upper", "bound", "of", "the", "observation", "." ]
def _get_observation_upper_bound(self): """Get the upper bound of the observation. Returns: A numpy array contains the upper bound of an observation. See GetObservation() for the details of each element of an observation. """ upper_bound = [] upper_bound.extend([2 * math.pi] * 2) # Roll, pitch, yaw of the base. upper_bound.extend([2 * math.pi / self._time_step] * 2) # Roll, pitch, yaw rate. if self._use_signal_in_observation: upper_bound.extend([2 * math.pi] * NUM_MOTORS) # Signal if self._use_angle_in_observation: upper_bound.extend([2 * math.pi] * NUM_MOTORS) # Motor angles return np.array(upper_bound)
[ "def", "_get_observation_upper_bound", "(", "self", ")", ":", "upper_bound", "=", "[", "]", "upper_bound", ".", "extend", "(", "[", "2", "*", "math", ".", "pi", "]", "*", "2", ")", "# Roll, pitch, yaw of the base.", "upper_bound", ".", "extend", "(", "[", "2", "*", "math", ".", "pi", "/", "self", ".", "_time_step", "]", "*", "2", ")", "# Roll, pitch, yaw rate.", "if", "self", ".", "_use_signal_in_observation", ":", "upper_bound", ".", "extend", "(", "[", "2", "*", "math", ".", "pi", "]", "*", "NUM_MOTORS", ")", "# Signal", "if", "self", ".", "_use_angle_in_observation", ":", "upper_bound", ".", "extend", "(", "[", "2", "*", "math", ".", "pi", "]", "*", "NUM_MOTORS", ")", "# Motor angles", "return", "np", ".", "array", "(", "upper_bound", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_trotting_env.py#L275-L289
peterljq/OpenMMD
795d4dd660cf7e537ceb599fdb038c5388b33390
VMD 3D Pose Baseline Multi-Objects/packages/lifting/utils/process.py
python
crop_image
(image, obj_pose)
return cropped_image, np.array([offset_left, offset_up])
Crop the image in order to have the person at the center and the final image size is the same as the expected CNN input size. Returns the cropped image and the offset that is used to update the joint positions.
Crop the image in order to have the person at the center and the final image size is the same as the expected CNN input size. Returns the cropped image and the offset that is used to update the joint positions.
[ "Crop", "the", "image", "in", "order", "to", "have", "the", "person", "at", "the", "center", "and", "the", "final", "image", "size", "is", "the", "same", "as", "the", "expected", "CNN", "input", "size", ".", "Returns", "the", "cropped", "image", "and", "the", "offset", "that", "is", "used", "to", "update", "the", "joint", "positions", "." ]
def crop_image(image, obj_pose): """ Crop the image in order to have the person at the center and the final image size is the same as the expected CNN input size. Returns the cropped image and the offset that is used to update the joint positions. """ offset_left = int(obj_pose[0] - config.INPUT_SIZE // 2) offset_up = int(obj_pose[1] - config.INPUT_SIZE // 2) # just for checking that it's inside the image offset_right = int(image.shape[1] - obj_pose[0] - config.INPUT_SIZE // 2) offset_bottom = int(image.shape[0] - obj_pose[1] - config.INPUT_SIZE // 2) pad_left, pad_right, pad_up, pad_bottom = 0, 0, 0, 0 if offset_left < 0: pad_left = -offset_left if offset_right < 0: pad_right = -offset_right if offset_up < 0: pad_up = -offset_up if offset_bottom < 0: pad_bottom = -offset_bottom padded_image = np.lib.pad( image, ((pad_up, pad_bottom), (pad_left, pad_right), (0, 0)), 'constant', constant_values=((0, 0), (0, 0), (0, 0))) cropped_image = padded_image[ offset_up + pad_up: offset_up + pad_up + config.INPUT_SIZE, offset_left + pad_left: offset_left + pad_left + config.INPUT_SIZE] return cropped_image, np.array([offset_left, offset_up])
[ "def", "crop_image", "(", "image", ",", "obj_pose", ")", ":", "offset_left", "=", "int", "(", "obj_pose", "[", "0", "]", "-", "config", ".", "INPUT_SIZE", "//", "2", ")", "offset_up", "=", "int", "(", "obj_pose", "[", "1", "]", "-", "config", ".", "INPUT_SIZE", "//", "2", ")", "# just for checking that it's inside the image", "offset_right", "=", "int", "(", "image", ".", "shape", "[", "1", "]", "-", "obj_pose", "[", "0", "]", "-", "config", ".", "INPUT_SIZE", "//", "2", ")", "offset_bottom", "=", "int", "(", "image", ".", "shape", "[", "0", "]", "-", "obj_pose", "[", "1", "]", "-", "config", ".", "INPUT_SIZE", "//", "2", ")", "pad_left", ",", "pad_right", ",", "pad_up", ",", "pad_bottom", "=", "0", ",", "0", ",", "0", ",", "0", "if", "offset_left", "<", "0", ":", "pad_left", "=", "-", "offset_left", "if", "offset_right", "<", "0", ":", "pad_right", "=", "-", "offset_right", "if", "offset_up", "<", "0", ":", "pad_up", "=", "-", "offset_up", "if", "offset_bottom", "<", "0", ":", "pad_bottom", "=", "-", "offset_bottom", "padded_image", "=", "np", ".", "lib", ".", "pad", "(", "image", ",", "(", "(", "pad_up", ",", "pad_bottom", ")", ",", "(", "pad_left", ",", "pad_right", ")", ",", "(", "0", ",", "0", ")", ")", ",", "'constant'", ",", "constant_values", "=", "(", "(", "0", ",", "0", ")", ",", "(", "0", ",", "0", ")", ",", "(", "0", ",", "0", ")", ")", ")", "cropped_image", "=", "padded_image", "[", "offset_up", "+", "pad_up", ":", "offset_up", "+", "pad_up", "+", "config", ".", "INPUT_SIZE", ",", "offset_left", "+", "pad_left", ":", "offset_left", "+", "pad_left", "+", "config", ".", "INPUT_SIZE", "]", "return", "cropped_image", ",", "np", ".", "array", "(", "[", "offset_left", ",", "offset_up", "]", ")" ]
https://github.com/peterljq/OpenMMD/blob/795d4dd660cf7e537ceb599fdb038c5388b33390/VMD 3D Pose Baseline Multi-Objects/packages/lifting/utils/process.py#L249-L280
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/more-itertools/py3/more_itertools/more.py
python
chunked
(iterable, n, strict=False)
Break *iterable* into lists of length *n*: >>> list(chunked([1, 2, 3, 4, 5, 6], 3)) [[1, 2, 3], [4, 5, 6]] By the default, the last yielded list will have fewer than *n* elements if the length of *iterable* is not divisible by *n*: >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) [[1, 2, 3], [4, 5, 6], [7, 8]] To use a fill-in value instead, see the :func:`grouper` recipe. If the length of *iterable* is not divisible by *n* and *strict* is ``True``, then ``ValueError`` will be raised before the last list is yielded.
Break *iterable* into lists of length *n*:
[ "Break", "*", "iterable", "*", "into", "lists", "of", "length", "*", "n", "*", ":" ]
def chunked(iterable, n, strict=False): """Break *iterable* into lists of length *n*: >>> list(chunked([1, 2, 3, 4, 5, 6], 3)) [[1, 2, 3], [4, 5, 6]] By the default, the last yielded list will have fewer than *n* elements if the length of *iterable* is not divisible by *n*: >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3)) [[1, 2, 3], [4, 5, 6], [7, 8]] To use a fill-in value instead, see the :func:`grouper` recipe. If the length of *iterable* is not divisible by *n* and *strict* is ``True``, then ``ValueError`` will be raised before the last list is yielded. """ iterator = iter(partial(take, n, iter(iterable)), []) if strict: if n is None: raise ValueError('n must not be None when using strict mode.') def ret(): for chunk in iterator: if len(chunk) != n: raise ValueError('iterable is not divisible by n.') yield chunk return iter(ret()) else: return iterator
[ "def", "chunked", "(", "iterable", ",", "n", ",", "strict", "=", "False", ")", ":", "iterator", "=", "iter", "(", "partial", "(", "take", ",", "n", ",", "iter", "(", "iterable", ")", ")", ",", "[", "]", ")", "if", "strict", ":", "if", "n", "is", "None", ":", "raise", "ValueError", "(", "'n must not be None when using strict mode.'", ")", "def", "ret", "(", ")", ":", "for", "chunk", "in", "iterator", ":", "if", "len", "(", "chunk", ")", "!=", "n", ":", "raise", "ValueError", "(", "'iterable is not divisible by n.'", ")", "yield", "chunk", "return", "iter", "(", "ret", "(", ")", ")", "else", ":", "return", "iterator" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py3/more_itertools/more.py#L139-L171
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/mac/Build/cpplint.py
python
FileInfo.BaseName
(self)
return self.Split()[1]
File base name - text after the final slash, before the final period.
File base name - text after the final slash, before the final period.
[ "File", "base", "name", "-", "text", "after", "the", "final", "slash", "before", "the", "final", "period", "." ]
def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1]
[ "def", "BaseName", "(", "self", ")", ":", "return", "self", ".", "Split", "(", ")", "[", "1", "]" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/mac/Build/cpplint.py#L582-L584
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/_collections.py
python
HTTPHeaderDict.pop
(self, key, default=__marker)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
[ "D", ".", "pop", "(", "k", "[", "d", "]", ")", "-", ">", "v", "remove", "specified", "key", "and", "return", "the", "corresponding", "value", ".", "If", "key", "is", "not", "found", "d", "is", "returned", "if", "given", "otherwise", "KeyError", "is", "raised", "." ]
def pop(self, key, default=__marker): """D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. """ # Using the MutableMapping function directly fails due to the private marker. # Using ordinary dict.pop would expose the internal structures. # So let's reinvent the wheel. try: value = self[key] except KeyError: if default is self.__marker: raise return default else: del self[key] return value
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "__marker", ")", ":", "# Using the MutableMapping function directly fails due to the private marker.", "# Using ordinary dict.pop would expose the internal structures.", "# So let's reinvent the wheel.", "try", ":", "value", "=", "self", "[", "key", "]", "except", "KeyError", ":", "if", "default", "is", "self", ".", "__marker", ":", "raise", "return", "default", "else", ":", "del", "self", "[", "key", "]", "return", "value" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/_collections.py#L191-L206
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/local_server.py
python
LocalServer.LocalKmlSearchHandler
(self, handler)
Handle GET request for kml search results.
Handle GET request for kml search results.
[ "Handle", "GET", "request", "for", "kml", "search", "results", "." ]
def LocalKmlSearchHandler(self, handler): """Handle GET request for kml search results.""" if not handler.IsValidRequest(): raise tornado.web.HTTPError(404) try: version = handler.request.arguments["cv"][0] if float(version[:3]) >= 7.1: self.LocalOneBoxKmlSearchHandler(handler) return except KeyError: pass # Unknown version. try: service = handler.request.arguments["service"][0] self.search_services_[service].KmlSearch(handler) return except KeyError: pass # Search service has not been defined; use default. if "displayKeys" in handler.request.arguments.keys(): key = handler.request.arguments["displayKeys"][0] if key in handler.request.arguments.keys(): try: search_term = handler.request.arguments[key][0].lower() except KeyError: # Earth 6.2.2+ will use "q" instead. search_term = handler.request.arguments[ALT_SEARCH_SERVICE_KEY][0] handler.write(tornado.web.globe_.search_db_.KmlSearch(search_term))
[ "def", "LocalKmlSearchHandler", "(", "self", ",", "handler", ")", ":", "if", "not", "handler", ".", "IsValidRequest", "(", ")", ":", "raise", "tornado", ".", "web", ".", "HTTPError", "(", "404", ")", "try", ":", "version", "=", "handler", ".", "request", ".", "arguments", "[", "\"cv\"", "]", "[", "0", "]", "if", "float", "(", "version", "[", ":", "3", "]", ")", ">=", "7.1", ":", "self", ".", "LocalOneBoxKmlSearchHandler", "(", "handler", ")", "return", "except", "KeyError", ":", "pass", "# Unknown version.", "try", ":", "service", "=", "handler", ".", "request", ".", "arguments", "[", "\"service\"", "]", "[", "0", "]", "self", ".", "search_services_", "[", "service", "]", ".", "KmlSearch", "(", "handler", ")", "return", "except", "KeyError", ":", "pass", "# Search service has not been defined; use default.", "if", "\"displayKeys\"", "in", "handler", ".", "request", ".", "arguments", ".", "keys", "(", ")", ":", "key", "=", "handler", ".", "request", ".", "arguments", "[", "\"displayKeys\"", "]", "[", "0", "]", "if", "key", "in", "handler", ".", "request", ".", "arguments", ".", "keys", "(", ")", ":", "try", ":", "search_term", "=", "handler", ".", "request", ".", "arguments", "[", "key", "]", "[", "0", "]", ".", "lower", "(", ")", "except", "KeyError", ":", "# Earth 6.2.2+ will use \"q\" instead.", "search_term", "=", "handler", ".", "request", ".", "arguments", "[", "ALT_SEARCH_SERVICE_KEY", "]", "[", "0", "]", "handler", ".", "write", "(", "tornado", ".", "web", ".", "globe_", ".", "search_db_", ".", "KmlSearch", "(", "search_term", ")", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/local_server.py#L323-L351
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py
python
Tokenizer.TryConsume
(self, token)
return False
Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed.
Tries to consume a given piece of text.
[ "Tries", "to", "consume", "a", "given", "piece", "of", "text", "." ]
def TryConsume(self, token): """Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed. """ if self.token == token: self.NextToken() return True return False
[ "def", "TryConsume", "(", "self", ",", "token", ")", ":", "if", "self", ".", "token", "==", "token", ":", "self", ".", "NextToken", "(", ")", "return", "True", "return", "False" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1002-L1014
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_logic_utils.py
python
close_epr
(fmla)
Convert fmla to E X. A Y. fmla, where X are the skolems in fmla and Y are the variables.
Convert fmla to E X. A Y. fmla, where X are the skolems in fmla and Y are the variables.
[ "Convert", "fmla", "to", "E", "X", ".", "A", "Y", ".", "fmla", "where", "X", "are", "the", "skolems", "in", "fmla", "and", "Y", "are", "the", "variables", "." ]
def close_epr(fmla): """ Convert fmla to E X. A Y. fmla, where X are the skolems in fmla and Y are the variables. """ if isinstance(fmla,And): return And(*[close_epr(f) for f in fmla.args]) skolems = [s for s in used_symbols_ast(fmla) if not s.is_skolem()] variables = list(used_variables_ast(fmla)) # TODO: avoid variable name clashes (shouldn't happen, but just to be safe) skvars = [Variable('V' + s.name,s.sort) for s in skolems] # fmla2 = rename_ast(fmla,dict(zip(skolems,skvars))) # return Exists(skvars,ForAll(variables,fmla2)) if variables == []: return fmla else: return ForAll(variables,fmla)
[ "def", "close_epr", "(", "fmla", ")", ":", "if", "isinstance", "(", "fmla", ",", "And", ")", ":", "return", "And", "(", "*", "[", "close_epr", "(", "f", ")", "for", "f", "in", "fmla", ".", "args", "]", ")", "skolems", "=", "[", "s", "for", "s", "in", "used_symbols_ast", "(", "fmla", ")", "if", "not", "s", ".", "is_skolem", "(", ")", "]", "variables", "=", "list", "(", "used_variables_ast", "(", "fmla", ")", ")", "# TODO: avoid variable name clashes (shouldn't happen, but just to be safe)", "skvars", "=", "[", "Variable", "(", "'V'", "+", "s", ".", "name", ",", "s", ".", "sort", ")", "for", "s", "in", "skolems", "]", "# fmla2 = rename_ast(fmla,dict(zip(skolems,skvars)))", "# return Exists(skvars,ForAll(variables,fmla2))", "if", "variables", "==", "[", "]", ":", "return", "fmla", "else", ":", "return", "ForAll", "(", "variables", ",", "fmla", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_logic_utils.py#L107-L120
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py
python
TransferFuture.set_exception
(self, exception)
Sets the exception on the future.
Sets the exception on the future.
[ "Sets", "the", "exception", "on", "the", "future", "." ]
def set_exception(self, exception): """Sets the exception on the future.""" if not self.done(): raise TransferNotDoneError( 'set_exception can only be called once the transfer is ' 'complete.') self._coordinator.set_exception(exception, override=True)
[ "def", "set_exception", "(", "self", ",", "exception", ")", ":", "if", "not", "self", ".", "done", "(", ")", ":", "raise", "TransferNotDoneError", "(", "'set_exception can only be called once the transfer is '", "'complete.'", ")", "self", ".", "_coordinator", ".", "set_exception", "(", "exception", ",", "override", "=", "True", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py#L82-L88
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
ItemContainer.Set
(*args, **kwargs)
return _core_.ItemContainer_Set(*args, **kwargs)
Set(self, List strings) Replace all the items in the control
Set(self, List strings)
[ "Set", "(", "self", "List", "strings", ")" ]
def Set(*args, **kwargs): """ Set(self, List strings) Replace all the items in the control """ return _core_.ItemContainer_Set(*args, **kwargs)
[ "def", "Set", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "ItemContainer_Set", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12890-L12896
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextCtrl.ApplyAlignmentToSelection
(*args, **kwargs)
return _richtext.RichTextCtrl_ApplyAlignmentToSelection(*args, **kwargs)
ApplyAlignmentToSelection(self, int alignment) -> bool Apply alignment to the selection
ApplyAlignmentToSelection(self, int alignment) -> bool
[ "ApplyAlignmentToSelection", "(", "self", "int", "alignment", ")", "-", ">", "bool" ]
def ApplyAlignmentToSelection(*args, **kwargs): """ ApplyAlignmentToSelection(self, int alignment) -> bool Apply alignment to the selection """ return _richtext.RichTextCtrl_ApplyAlignmentToSelection(*args, **kwargs)
[ "def", "ApplyAlignmentToSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_ApplyAlignmentToSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3979-L3985
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. We also allow a brace on the # following line if it is part of an array initialization and would not fit # within the 80 character limit of the preceding line. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline) and not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'else if\s*\(', line): # could be multi-line if brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) brace_on_right = endline[endpos:].find('{') != -1 if brace_on_left != brace_on_right: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Check single-line if/else bodies. The style guide says 'curly braces are not # required for single-line statements'. We additionally allow multi-line, # single statements, but we reject anything with more than one semicolon in # it. This means that the first semicolon after the if should be at the end of # its line, and the line after that should have an indent level equal to or # lower than the if. We also check for ambiguous if/else nesting without # braces. if_else_match = Search(r'\b(if\s*\(|else\b)', line) if if_else_match and not Match(r'\s*#', line): if_indent = GetIndentLevel(line) endline, endlinenum, endpos = line, linenum, if_else_match.end() if_match = Search(r'\bif\s*\(', line) if if_match: # This could be a multiline if condition, so find the end first. pos = if_match.end() - 1 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) # Check for an opening brace, either directly after the if or on the next # line. If found, this isn't a single-statement conditional. if (not Match(r'\s*{', endline[endpos:]) and not (Match(r'\s*$', endline[endpos:]) and endlinenum < (len(clean_lines.elided) - 1) and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): while (endlinenum < len(clean_lines.elided) and ';' not in clean_lines.elided[endlinenum][endpos:]): endlinenum += 1 endpos = 0 if endlinenum < len(clean_lines.elided): endline = clean_lines.elided[endlinenum] # We allow a mix of whitespace and closing braces (e.g. for one-liner # methods) and a single \ after the semicolon (for macros) endpos = endline.find(';') if not Match(r';[\s}]*(\\?)$', endline[endpos:]): # Semicolon isn't the last character, there's something trailing. # Output a warning if the semicolon is not contained inside # a lambda expression. if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', endline): error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces') elif endlinenum < len(clean_lines.elided) - 1: # Make sure the next line is dedented next_line = clean_lines.elided[endlinenum + 1] next_indent = GetIndentLevel(next_line) # With ambiguous nested if statements, this will error out on the # if that *doesn't* match the else, regardless of whether it's the # inner one or outer one. if (if_match and Match(r'\s*else\b', next_line) and next_indent != if_indent): error(filename, linenum, 'readability/braces', 4, 'Else clause should be indented at the same level as if. ' 'Ambiguous nested if/else chains require braces.') elif next_indent > if_indent: error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces')
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", "# We allow an open brace to start a line in the case where someone is using", "# braces in a block to explicitly create a new scope, which is commonly used", "# to control the lifetime of stack-allocated variables. Braces are also", "# used for brace initializers inside function calls. We don't detect this", "# perfectly: we just don't complain if the last non-whitespace character on", "# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the", "# previous line starts a preprocessor block. We also allow a brace on the", "# following line if it is part of an array initialization and would not fit", "# within the 80 character limit of the preceding line.", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "(", "not", "Search", "(", "r'[,;:}{(]\\s*$'", ",", "prevline", ")", "and", "not", "Match", "(", "r'\\s*#'", ",", "prevline", ")", "and", "not", "(", "GetLineWidth", "(", "prevline", ")", ">", "_line_length", "-", "2", "and", "'[]'", "in", "prevline", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "4", ",", "'{ should almost always be at the end of the previous line'", ")", "# An else clause should be on the same line as the preceding closing brace.", "if", "Match", "(", "r'\\s*else\\b\\s*(?:if\\b|\\{|$)'", ",", "line", ")", ":", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "Match", "(", "r'\\s*}\\s*$'", ",", "prevline", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'An else should appear on the same line as the preceding }'", ")", "# If braces come on one side of an else, they should be on both.", "# However, we have to worry about \"else if\" that spans multiple lines!", "if", "Search", "(", "r'else if\\s*\\('", ",", "line", ")", ":", "# could be multi-line if", "brace_on_left", "=", "bool", "(", "Search", "(", "r'}\\s*else if\\s*\\('", ",", "line", ")", ")", "# find the ( after the if", "pos", "=", "line", ".", "find", "(", "'else if'", ")", "pos", "=", "line", ".", "find", "(", "'('", ",", "pos", ")", "if", "pos", ">", "0", ":", "(", "endline", ",", "_", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", "brace_on_right", "=", "endline", "[", "endpos", ":", "]", ".", "find", "(", "'{'", ")", "!=", "-", "1", "if", "brace_on_left", "!=", "brace_on_right", ":", "# must be brace after if", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "elif", "Search", "(", "r'}\\s*else[^{]*$'", ",", "line", ")", "or", "Match", "(", "r'[^}]*else\\s*{'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "# Likewise, an else should never have the else clause on the same line", "if", "Search", "(", "r'\\belse [^\\s{]'", ",", "line", ")", "and", "not", "Search", "(", "r'\\belse if\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'Else clause should never be on same line as else (use 2 lines)'", ")", "# In the same way, a do/while should never be on one line", "if", "Match", "(", "r'\\s*do [^\\s{]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'do/while clauses should not be on a single line'", ")", "# Check single-line if/else bodies. The style guide says 'curly braces are not", "# required for single-line statements'. We additionally allow multi-line,", "# single statements, but we reject anything with more than one semicolon in", "# it. This means that the first semicolon after the if should be at the end of", "# its line, and the line after that should have an indent level equal to or", "# lower than the if. We also check for ambiguous if/else nesting without", "# braces.", "if_else_match", "=", "Search", "(", "r'\\b(if\\s*\\(|else\\b)'", ",", "line", ")", "if", "if_else_match", "and", "not", "Match", "(", "r'\\s*#'", ",", "line", ")", ":", "if_indent", "=", "GetIndentLevel", "(", "line", ")", "endline", ",", "endlinenum", ",", "endpos", "=", "line", ",", "linenum", ",", "if_else_match", ".", "end", "(", ")", "if_match", "=", "Search", "(", "r'\\bif\\s*\\('", ",", "line", ")", "if", "if_match", ":", "# This could be a multiline if condition, so find the end first.", "pos", "=", "if_match", ".", "end", "(", ")", "-", "1", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", "# Check for an opening brace, either directly after the if or on the next", "# line. If found, this isn't a single-statement conditional.", "if", "(", "not", "Match", "(", "r'\\s*{'", ",", "endline", "[", "endpos", ":", "]", ")", "and", "not", "(", "Match", "(", "r'\\s*$'", ",", "endline", "[", "endpos", ":", "]", ")", "and", "endlinenum", "<", "(", "len", "(", "clean_lines", ".", "elided", ")", "-", "1", ")", "and", "Match", "(", "r'\\s*{'", ",", "clean_lines", ".", "elided", "[", "endlinenum", "+", "1", "]", ")", ")", ")", ":", "while", "(", "endlinenum", "<", "len", "(", "clean_lines", ".", "elided", ")", "and", "';'", "not", "in", "clean_lines", ".", "elided", "[", "endlinenum", "]", "[", "endpos", ":", "]", ")", ":", "endlinenum", "+=", "1", "endpos", "=", "0", "if", "endlinenum", "<", "len", "(", "clean_lines", ".", "elided", ")", ":", "endline", "=", "clean_lines", ".", "elided", "[", "endlinenum", "]", "# We allow a mix of whitespace and closing braces (e.g. for one-liner", "# methods) and a single \\ after the semicolon (for macros)", "endpos", "=", "endline", ".", "find", "(", "';'", ")", "if", "not", "Match", "(", "r';[\\s}]*(\\\\?)$'", ",", "endline", "[", "endpos", ":", "]", ")", ":", "# Semicolon isn't the last character, there's something trailing.", "# Output a warning if the semicolon is not contained inside", "# a lambda expression.", "if", "not", "Match", "(", "r'^[^{};]*\\[[^\\[\\]]*\\][^{}]*\\{[^{}]*\\}\\s*\\)*[;,]\\s*$'", ",", "endline", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "4", ",", "'If/else bodies with multiple statements require braces'", ")", "elif", "endlinenum", "<", "len", "(", "clean_lines", ".", "elided", ")", "-", "1", ":", "# Make sure the next line is dedented", "next_line", "=", "clean_lines", ".", "elided", "[", "endlinenum", "+", "1", "]", "next_indent", "=", "GetIndentLevel", "(", "next_line", ")", "# With ambiguous nested if statements, this will error out on the", "# if that *doesn't* match the else, regardless of whether it's the", "# inner one or outer one.", "if", "(", "if_match", "and", "Match", "(", "r'\\s*else\\b'", ",", "next_line", ")", "and", "next_indent", "!=", "if_indent", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "4", ",", "'Else clause should be indented at the same level as if. '", "'Ambiguous nested if/else chains require braces.'", ")", "elif", "next_indent", ">", "if_indent", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "4", ",", "'If/else bodies with multiple statements require braces'", ")" ]
https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L3670-L3786
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/agents/baseline_controller/locomotion_controller_in_scenario_set_example.py
python
_generate_linear_angular_speed
(t, time_points, speed_points)
return speed[0:3], speed[3]
Creates an example speed profile based on time for demo purpose.
Creates an example speed profile based on time for demo purpose.
[ "Creates", "an", "example", "speed", "profile", "based", "on", "time", "for", "demo", "purpose", "." ]
def _generate_linear_angular_speed(t, time_points, speed_points): """Creates an example speed profile based on time for demo purpose.""" speed = scipy.interpolate.interp1d( time_points, speed_points, kind="previous", fill_value="extrapolate", axis=0)( t) return speed[0:3], speed[3]
[ "def", "_generate_linear_angular_speed", "(", "t", ",", "time_points", ",", "speed_points", ")", ":", "speed", "=", "scipy", ".", "interpolate", ".", "interp1d", "(", "time_points", ",", "speed_points", ",", "kind", "=", "\"previous\"", ",", "fill_value", "=", "\"extrapolate\"", ",", "axis", "=", "0", ")", "(", "t", ")", "return", "speed", "[", "0", ":", "3", "]", ",", "speed", "[", "3", "]" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/agents/baseline_controller/locomotion_controller_in_scenario_set_example.py#L69-L80
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py
python
TixWidget.subwidget
(self, name)
return self._nametowidget(n)
Return the named subwidget (which must have been created by the sub-class).
Return the named subwidget (which must have been created by the sub-class).
[ "Return", "the", "named", "subwidget", "(", "which", "must", "have", "been", "created", "by", "the", "sub", "-", "class", ")", "." ]
def subwidget(self, name): """Return the named subwidget (which must have been created by the sub-class).""" n = self._subwidget_name(name) if not n: raise TclError("Subwidget " + name + " not child of " + self._name) # Remove header of name and leading dot n = n[len(self._w)+1:] return self._nametowidget(n)
[ "def", "subwidget", "(", "self", ",", "name", ")", ":", "n", "=", "self", ".", "_subwidget_name", "(", "name", ")", "if", "not", "n", ":", "raise", "TclError", "(", "\"Subwidget \"", "+", "name", "+", "\" not child of \"", "+", "self", ".", "_name", ")", "# Remove header of name and leading dot", "n", "=", "n", "[", "len", "(", "self", ".", "_w", ")", "+", "1", ":", "]", "return", "self", ".", "_nametowidget", "(", "n", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py#L336-L344
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nntplib.py
python
_NNTPBase.group
(self, name)
return resp, int(count), int(first), int(last), name
Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles - first: first article number - last: last article number - name: the group name
Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles - first: first article number - last: last article number - name: the group name
[ "Process", "a", "GROUP", "command", ".", "Argument", ":", "-", "group", ":", "the", "group", "name", "Returns", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "count", ":", "number", "of", "articles", "-", "first", ":", "first", "article", "number", "-", "last", ":", "last", "article", "number", "-", "name", ":", "the", "group", "name" ]
def group(self, name): """Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles - first: first article number - last: last article number - name: the group name """ resp = self._shortcmd('GROUP ' + name) if not resp.startswith('211'): raise NNTPReplyError(resp) words = resp.split() count = first = last = 0 n = len(words) if n > 1: count = words[1] if n > 2: first = words[2] if n > 3: last = words[3] if n > 4: name = words[4].lower() return resp, int(count), int(first), int(last), name
[ "def", "group", "(", "self", ",", "name", ")", ":", "resp", "=", "self", ".", "_shortcmd", "(", "'GROUP '", "+", "name", ")", "if", "not", "resp", ".", "startswith", "(", "'211'", ")", ":", "raise", "NNTPReplyError", "(", "resp", ")", "words", "=", "resp", ".", "split", "(", ")", "count", "=", "first", "=", "last", "=", "0", "n", "=", "len", "(", "words", ")", "if", "n", ">", "1", ":", "count", "=", "words", "[", "1", "]", "if", "n", ">", "2", ":", "first", "=", "words", "[", "2", "]", "if", "n", ">", "3", ":", "last", "=", "words", "[", "3", "]", "if", "n", ">", "4", ":", "name", "=", "words", "[", "4", "]", ".", "lower", "(", ")", "return", "resp", ",", "int", "(", "count", ")", ",", "int", "(", "first", ")", ",", "int", "(", "last", ")", ",", "name" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nntplib.py#L651-L675
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
tools/stats/scribe.py
python
schema_from_sample
(data: Dict[str, Any])
return schema
Extract a schema compatible with 'register_rds_schema' from data.
Extract a schema compatible with 'register_rds_schema' from data.
[ "Extract", "a", "schema", "compatible", "with", "register_rds_schema", "from", "data", "." ]
def schema_from_sample(data: Dict[str, Any]) -> Dict[str, str]: """ Extract a schema compatible with 'register_rds_schema' from data. """ schema = {} for key, value in data.items(): if isinstance(value, str): schema[key] = "string" elif isinstance(value, int): schema[key] = "int" elif isinstance(value, float): schema[key] = "float" else: raise RuntimeError(f"Unsupported value type: {key}: {value}") return schema
[ "def", "schema_from_sample", "(", "data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "schema", "=", "{", "}", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "schema", "[", "key", "]", "=", "\"string\"", "elif", "isinstance", "(", "value", ",", "int", ")", ":", "schema", "[", "key", "]", "=", "\"int\"", "elif", "isinstance", "(", "value", ",", "float", ")", ":", "schema", "[", "key", "]", "=", "\"float\"", "else", ":", "raise", "RuntimeError", "(", "f\"Unsupported value type: {key}: {value}\"", ")", "return", "schema" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/stats/scribe.py#L97-L111
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/build/virtual_target.py
python
Action.actualize_sources
(self, sources, prop_set)
Creates actual jam targets for sources. Initializes two member variables: 'self.actual_sources_' -- sources which are passed to updating action 'self.dependency_only_sources_' -- sources which are made dependencies, but are not used otherwise. New values will be *appended* to the variables. They may be non-empty, if caller wants it.
Creates actual jam targets for sources. Initializes two member variables: 'self.actual_sources_' -- sources which are passed to updating action 'self.dependency_only_sources_' -- sources which are made dependencies, but are not used otherwise.
[ "Creates", "actual", "jam", "targets", "for", "sources", ".", "Initializes", "two", "member", "variables", ":", "self", ".", "actual_sources_", "--", "sources", "which", "are", "passed", "to", "updating", "action", "self", ".", "dependency_only_sources_", "--", "sources", "which", "are", "made", "dependencies", "but", "are", "not", "used", "otherwise", "." ]
def actualize_sources (self, sources, prop_set): """ Creates actual jam targets for sources. Initializes two member variables: 'self.actual_sources_' -- sources which are passed to updating action 'self.dependency_only_sources_' -- sources which are made dependencies, but are not used otherwise. New values will be *appended* to the variables. They may be non-empty, if caller wants it. """ assert is_iterable_typed(sources, VirtualTarget) assert isinstance(prop_set, property_set.PropertySet) dependencies = self.properties_.get ('<dependency>') self.dependency_only_sources_ += self.actualize_source_type (dependencies, prop_set) self.actual_sources_ += self.actualize_source_type (sources, prop_set) # This is used to help bjam find dependencies in generated headers # in other main targets. # Say: # # make a.h : ....... ; # exe hello : hello.cpp : <implicit-dependency>a.h ; # # However, for bjam to find the dependency the generated target must # be actualized (i.e. have the jam target). In the above case, # if we're building just hello ("bjam hello"), 'a.h' won't be # actualized unless we do it here. implicit = self.properties_.get("<implicit-dependency>") for i in implicit: i.actualize()
[ "def", "actualize_sources", "(", "self", ",", "sources", ",", "prop_set", ")", ":", "assert", "is_iterable_typed", "(", "sources", ",", "VirtualTarget", ")", "assert", "isinstance", "(", "prop_set", ",", "property_set", ".", "PropertySet", ")", "dependencies", "=", "self", ".", "properties_", ".", "get", "(", "'<dependency>'", ")", "self", ".", "dependency_only_sources_", "+=", "self", ".", "actualize_source_type", "(", "dependencies", ",", "prop_set", ")", "self", ".", "actual_sources_", "+=", "self", ".", "actualize_source_type", "(", "sources", ",", "prop_set", ")", "# This is used to help bjam find dependencies in generated headers", "# in other main targets.", "# Say:", "#", "# make a.h : ....... ;", "# exe hello : hello.cpp : <implicit-dependency>a.h ;", "#", "# However, for bjam to find the dependency the generated target must", "# be actualized (i.e. have the jam target). In the above case,", "# if we're building just hello (\"bjam hello\"), 'a.h' won't be", "# actualized unless we do it here.", "implicit", "=", "self", ".", "properties_", ".", "get", "(", "\"<implicit-dependency>\"", ")", "for", "i", "in", "implicit", ":", "i", ".", "actualize", "(", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/virtual_target.py#L886-L917
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
mlir/utils/spirv/gen_spirv_dialect.py
python
get_string_between_nested
(base, start, end)
return '', split[0]
Extracts a substring with a nested start and end from a string. Arguments: - base: string to extract from. - start: string to use as the start of the substring. - end: string to use as the end of the substring. Returns: - The substring if found - The part of the base after end of the substring. Is the base string itself if the substring wasn't found.
Extracts a substring with a nested start and end from a string.
[ "Extracts", "a", "substring", "with", "a", "nested", "start", "and", "end", "from", "a", "string", "." ]
def get_string_between_nested(base, start, end): """Extracts a substring with a nested start and end from a string. Arguments: - base: string to extract from. - start: string to use as the start of the substring. - end: string to use as the end of the substring. Returns: - The substring if found - The part of the base after end of the substring. Is the base string itself if the substring wasn't found. """ split = base.split(start, 1) if len(split) == 2: # Handle nesting delimiters rest = split[1] unmatched_start = 1 index = 0 while unmatched_start > 0 and index < len(rest): if rest[index:].startswith(end): unmatched_start -= 1 if unmatched_start == 0: break index += len(end) elif rest[index:].startswith(start): unmatched_start += 1 index += len(start) else: index += 1 assert index < len(rest), \ 'cannot find end "{end}" while extracting substring '\ 'starting with "{start}"'.format(start=start, end=end) return rest[:index], rest[index + len(end):] return '', split[0]
[ "def", "get_string_between_nested", "(", "base", ",", "start", ",", "end", ")", ":", "split", "=", "base", ".", "split", "(", "start", ",", "1", ")", "if", "len", "(", "split", ")", "==", "2", ":", "# Handle nesting delimiters", "rest", "=", "split", "[", "1", "]", "unmatched_start", "=", "1", "index", "=", "0", "while", "unmatched_start", ">", "0", "and", "index", "<", "len", "(", "rest", ")", ":", "if", "rest", "[", "index", ":", "]", ".", "startswith", "(", "end", ")", ":", "unmatched_start", "-=", "1", "if", "unmatched_start", "==", "0", ":", "break", "index", "+=", "len", "(", "end", ")", "elif", "rest", "[", "index", ":", "]", ".", "startswith", "(", "start", ")", ":", "unmatched_start", "+=", "1", "index", "+=", "len", "(", "start", ")", "else", ":", "index", "+=", "1", "assert", "index", "<", "len", "(", "rest", ")", ",", "'cannot find end \"{end}\" while extracting substring '", "'starting with \"{start}\"'", ".", "format", "(", "start", "=", "start", ",", "end", "=", "end", ")", "return", "rest", "[", ":", "index", "]", ",", "rest", "[", "index", "+", "len", "(", "end", ")", ":", "]", "return", "''", ",", "split", "[", "0", "]" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/mlir/utils/spirv/gen_spirv_dialect.py#L801-L836
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/_iotools.py
python
easy_dtype
(ndtype, names=None, defaultfmt="f%i", **validationargs)
return ndtype
Convenience function to create a `np.dtype` object. The function processes the input `dtype` and matches it with the given names. Parameters ---------- ndtype : var Definition of the dtype. Can be any string or dictionary recognized by the `np.dtype` function, or a sequence of types. names : str or sequence, optional Sequence of strings to use as field names for a structured dtype. For convenience, `names` can be a string of a comma-separated list of names. defaultfmt : str, optional Format string used to define missing names, such as ``"f%i"`` (default) or ``"fields_%02i"``. validationargs : optional A series of optional arguments used to initialize a `NameValidator`. Examples -------- >>> np.lib._iotools.easy_dtype(float) dtype('float64') >>> np.lib._iotools.easy_dtype("i4, f8") dtype([('f0', '<i4'), ('f1', '<f8')]) >>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i") dtype([('field_000', '<i4'), ('field_001', '<f8')]) >>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c") dtype([('a', '<i8'), ('b', '<f8'), ('c', '<f8')]) >>> np.lib._iotools.easy_dtype(float, names="a,b,c") dtype([('a', '<f8'), ('b', '<f8'), ('c', '<f8')])
Convenience function to create a `np.dtype` object.
[ "Convenience", "function", "to", "create", "a", "np", ".", "dtype", "object", "." ]
def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): """ Convenience function to create a `np.dtype` object. The function processes the input `dtype` and matches it with the given names. Parameters ---------- ndtype : var Definition of the dtype. Can be any string or dictionary recognized by the `np.dtype` function, or a sequence of types. names : str or sequence, optional Sequence of strings to use as field names for a structured dtype. For convenience, `names` can be a string of a comma-separated list of names. defaultfmt : str, optional Format string used to define missing names, such as ``"f%i"`` (default) or ``"fields_%02i"``. validationargs : optional A series of optional arguments used to initialize a `NameValidator`. Examples -------- >>> np.lib._iotools.easy_dtype(float) dtype('float64') >>> np.lib._iotools.easy_dtype("i4, f8") dtype([('f0', '<i4'), ('f1', '<f8')]) >>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i") dtype([('field_000', '<i4'), ('field_001', '<f8')]) >>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c") dtype([('a', '<i8'), ('b', '<f8'), ('c', '<f8')]) >>> np.lib._iotools.easy_dtype(float, names="a,b,c") dtype([('a', '<f8'), ('b', '<f8'), ('c', '<f8')]) """ try: ndtype = np.dtype(ndtype) except TypeError: validate = NameValidator(**validationargs) nbfields = len(ndtype) if names is None: names = [''] * len(ndtype) elif isinstance(names, basestring): names = names.split(",") names = validate(names, nbfields=nbfields, defaultfmt=defaultfmt) ndtype = np.dtype(dict(formats=ndtype, names=names)) else: nbtypes = len(ndtype) # Explicit names if names is not None: validate = NameValidator(**validationargs) if isinstance(names, basestring): names = names.split(",") # Simple dtype: repeat to match the nb of names if nbtypes == 0: formats = tuple([ndtype.type] * len(names)) names = validate(names, defaultfmt=defaultfmt) ndtype = np.dtype(list(zip(names, formats))) # Structured dtype: just validate the names as needed else: ndtype.names = validate(names, nbfields=nbtypes, defaultfmt=defaultfmt) # No implicit names elif (nbtypes > 0): validate = NameValidator(**validationargs) # Default initial names : should we change the format ? if (ndtype.names == tuple("f%i" % i for i in range(nbtypes))) and \ (defaultfmt != "f%i"): ndtype.names = validate([''] * nbtypes, defaultfmt=defaultfmt) # Explicit initial names : just validate else: ndtype.names = validate(ndtype.names, defaultfmt=defaultfmt) return ndtype
[ "def", "easy_dtype", "(", "ndtype", ",", "names", "=", "None", ",", "defaultfmt", "=", "\"f%i\"", ",", "*", "*", "validationargs", ")", ":", "try", ":", "ndtype", "=", "np", ".", "dtype", "(", "ndtype", ")", "except", "TypeError", ":", "validate", "=", "NameValidator", "(", "*", "*", "validationargs", ")", "nbfields", "=", "len", "(", "ndtype", ")", "if", "names", "is", "None", ":", "names", "=", "[", "''", "]", "*", "len", "(", "ndtype", ")", "elif", "isinstance", "(", "names", ",", "basestring", ")", ":", "names", "=", "names", ".", "split", "(", "\",\"", ")", "names", "=", "validate", "(", "names", ",", "nbfields", "=", "nbfields", ",", "defaultfmt", "=", "defaultfmt", ")", "ndtype", "=", "np", ".", "dtype", "(", "dict", "(", "formats", "=", "ndtype", ",", "names", "=", "names", ")", ")", "else", ":", "nbtypes", "=", "len", "(", "ndtype", ")", "# Explicit names", "if", "names", "is", "not", "None", ":", "validate", "=", "NameValidator", "(", "*", "*", "validationargs", ")", "if", "isinstance", "(", "names", ",", "basestring", ")", ":", "names", "=", "names", ".", "split", "(", "\",\"", ")", "# Simple dtype: repeat to match the nb of names", "if", "nbtypes", "==", "0", ":", "formats", "=", "tuple", "(", "[", "ndtype", ".", "type", "]", "*", "len", "(", "names", ")", ")", "names", "=", "validate", "(", "names", ",", "defaultfmt", "=", "defaultfmt", ")", "ndtype", "=", "np", ".", "dtype", "(", "list", "(", "zip", "(", "names", ",", "formats", ")", ")", ")", "# Structured dtype: just validate the names as needed", "else", ":", "ndtype", ".", "names", "=", "validate", "(", "names", ",", "nbfields", "=", "nbtypes", ",", "defaultfmt", "=", "defaultfmt", ")", "# No implicit names", "elif", "(", "nbtypes", ">", "0", ")", ":", "validate", "=", "NameValidator", "(", "*", "*", "validationargs", ")", "# Default initial names : should we change the format ?", "if", "(", "ndtype", ".", "names", "==", "tuple", "(", "\"f%i\"", "%", "i", "for", "i", "in", "range", "(", "nbtypes", ")", ")", ")", "and", "(", "defaultfmt", "!=", "\"f%i\"", ")", ":", "ndtype", ".", "names", "=", "validate", "(", "[", "''", "]", "*", "nbtypes", ",", "defaultfmt", "=", "defaultfmt", ")", "# Explicit initial names : just validate", "else", ":", "ndtype", ".", "names", "=", "validate", "(", "ndtype", ".", "names", ",", "defaultfmt", "=", "defaultfmt", ")", "return", "ndtype" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/_iotools.py#L800-L874
milvus-io/milvus
3b1030de2b6c39e3512833e97f6044d63eb24237
internal/core/build-support/cpplint.py
python
_RestoreFilters
()
Restores filters previously backed up.
Restores filters previously backed up.
[ "Restores", "filters", "previously", "backed", "up", "." ]
def _RestoreFilters(): """ Restores filters previously backed up.""" _cpplint_state.RestoreFilters()
[ "def", "_RestoreFilters", "(", ")", ":", "_cpplint_state", ".", "RestoreFilters", "(", ")" ]
https://github.com/milvus-io/milvus/blob/3b1030de2b6c39e3512833e97f6044d63eb24237/internal/core/build-support/cpplint.py#L1482-L1484
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py
python
maximum_fill_value
(obj)
return _extremum_fill_value(obj, max_filler, "maximum")
Return the minimum value that can be represented by the dtype of an object. This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Parameters ---------- obj : ndarray, dtype or scalar An object that can be queried for it's numeric type. Returns ------- val : scalar The minimum representable value. Raises ------ TypeError If `obj` isn't a suitable numeric type. See Also -------- minimum_fill_value : The inverse function. set_fill_value : Set the filling value of a masked array. MaskedArray.fill_value : Return current fill value. Examples -------- >>> import numpy.ma as ma >>> a = np.int8() >>> ma.maximum_fill_value(a) -128 >>> a = np.int32() >>> ma.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. >>> a = np.array([1, 2, 3], dtype=np.int8) >>> ma.maximum_fill_value(a) -128 >>> a = np.array([1, 2, 3], dtype=np.float32) >>> ma.maximum_fill_value(a) -inf
Return the minimum value that can be represented by the dtype of an object.
[ "Return", "the", "minimum", "value", "that", "can", "be", "represented", "by", "the", "dtype", "of", "an", "object", "." ]
def maximum_fill_value(obj): """ Return the minimum value that can be represented by the dtype of an object. This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Parameters ---------- obj : ndarray, dtype or scalar An object that can be queried for it's numeric type. Returns ------- val : scalar The minimum representable value. Raises ------ TypeError If `obj` isn't a suitable numeric type. See Also -------- minimum_fill_value : The inverse function. set_fill_value : Set the filling value of a masked array. MaskedArray.fill_value : Return current fill value. Examples -------- >>> import numpy.ma as ma >>> a = np.int8() >>> ma.maximum_fill_value(a) -128 >>> a = np.int32() >>> ma.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. >>> a = np.array([1, 2, 3], dtype=np.int8) >>> ma.maximum_fill_value(a) -128 >>> a = np.array([1, 2, 3], dtype=np.float32) >>> ma.maximum_fill_value(a) -inf """ return _extremum_fill_value(obj, max_filler, "maximum")
[ "def", "maximum_fill_value", "(", "obj", ")", ":", "return", "_extremum_fill_value", "(", "obj", ",", "max_filler", ",", "\"maximum\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L356-L404
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/packers.py
python
dtype_for
(t)
return np.typeDict.get(t, t)
return my dtype mapping, whether number or name
return my dtype mapping, whether number or name
[ "return", "my", "dtype", "mapping", "whether", "number", "or", "name" ]
def dtype_for(t): """ return my dtype mapping, whether number or name """ if t in dtype_dict: return dtype_dict[t] return np.typeDict.get(t, t)
[ "def", "dtype_for", "(", "t", ")", ":", "if", "t", "in", "dtype_dict", ":", "return", "dtype_dict", "[", "t", "]", "return", "np", ".", "typeDict", ".", "get", "(", "t", ",", "t", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/packers.py#L243-L247
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/ops.py
python
_get_graph_from_inputs
(op_input_list, graph=None)
return graph or get_default_graph()
Returns the appropriate graph to use for the given inputs. This library method provides a consistent algorithm for choosing the graph in which an Operation should be constructed: 1. If the "graph" is specified explicitly, we validate that all of the inputs in "op_input_list" are compatible with that graph. 2. Otherwise, we attempt to select a graph from the first Operation- or Tensor-valued input in "op_input_list", and validate that all other such inputs are in the same graph. 3. If the graph was not specified and it could not be inferred from "op_input_list", we attempt to use the default graph. Args: op_input_list: A list of inputs to an operation, which may include `Tensor`, `Operation`, and other objects that may be converted to a graph element. graph: (Optional) The explicit graph to use. Raises: TypeError: If op_input_list is not a list or tuple, or if graph is not a Graph. ValueError: If a graph is explicitly passed and not all inputs are from it, or if the inputs are from multiple graphs, or we could not find a graph and there was no default graph. Returns: The appropriate graph to use for the given inputs.
Returns the appropriate graph to use for the given inputs.
[ "Returns", "the", "appropriate", "graph", "to", "use", "for", "the", "given", "inputs", "." ]
def _get_graph_from_inputs(op_input_list, graph=None): """Returns the appropriate graph to use for the given inputs. This library method provides a consistent algorithm for choosing the graph in which an Operation should be constructed: 1. If the "graph" is specified explicitly, we validate that all of the inputs in "op_input_list" are compatible with that graph. 2. Otherwise, we attempt to select a graph from the first Operation- or Tensor-valued input in "op_input_list", and validate that all other such inputs are in the same graph. 3. If the graph was not specified and it could not be inferred from "op_input_list", we attempt to use the default graph. Args: op_input_list: A list of inputs to an operation, which may include `Tensor`, `Operation`, and other objects that may be converted to a graph element. graph: (Optional) The explicit graph to use. Raises: TypeError: If op_input_list is not a list or tuple, or if graph is not a Graph. ValueError: If a graph is explicitly passed and not all inputs are from it, or if the inputs are from multiple graphs, or we could not find a graph and there was no default graph. Returns: The appropriate graph to use for the given inputs. """ op_input_list = tuple(op_input_list) # Handle generators correctly if graph and not isinstance(graph, Graph): raise TypeError("Input graph needs to be a Graph: %s" % graph) # 1. We validate that all of the inputs are from the same graph. This is # either the supplied graph parameter, or the first one selected from one # the graph-element-valued inputs. In the latter case, we hold onto # that input in original_graph_element so we can provide a more # informative error if a mismatch is found. original_graph_element = None for op_input in op_input_list: # Determine if this is a valid graph_element. graph_element = None if isinstance(op_input, (Operation, Tensor, SparseTensor, IndexedSlices)): graph_element = op_input else: graph_element = _as_graph_element(op_input) if graph_element is not None: if not graph: original_graph_element = graph_element graph = graph_element.graph elif original_graph_element is not None: _assert_same_graph(original_graph_element, graph_element) elif graph_element.graph is not graph: raise ValueError( "%s is not from the passed-in graph." % graph_element) # 2. If all else fails, we use the default graph, which is always there. return graph or get_default_graph()
[ "def", "_get_graph_from_inputs", "(", "op_input_list", ",", "graph", "=", "None", ")", ":", "op_input_list", "=", "tuple", "(", "op_input_list", ")", "# Handle generators correctly", "if", "graph", "and", "not", "isinstance", "(", "graph", ",", "Graph", ")", ":", "raise", "TypeError", "(", "\"Input graph needs to be a Graph: %s\"", "%", "graph", ")", "# 1. We validate that all of the inputs are from the same graph. This is", "# either the supplied graph parameter, or the first one selected from one", "# the graph-element-valued inputs. In the latter case, we hold onto", "# that input in original_graph_element so we can provide a more", "# informative error if a mismatch is found.", "original_graph_element", "=", "None", "for", "op_input", "in", "op_input_list", ":", "# Determine if this is a valid graph_element.", "graph_element", "=", "None", "if", "isinstance", "(", "op_input", ",", "(", "Operation", ",", "Tensor", ",", "SparseTensor", ",", "IndexedSlices", ")", ")", ":", "graph_element", "=", "op_input", "else", ":", "graph_element", "=", "_as_graph_element", "(", "op_input", ")", "if", "graph_element", "is", "not", "None", ":", "if", "not", "graph", ":", "original_graph_element", "=", "graph_element", "graph", "=", "graph_element", ".", "graph", "elif", "original_graph_element", "is", "not", "None", ":", "_assert_same_graph", "(", "original_graph_element", ",", "graph_element", ")", "elif", "graph_element", ".", "graph", "is", "not", "graph", ":", "raise", "ValueError", "(", "\"%s is not from the passed-in graph.\"", "%", "graph_element", ")", "# 2. If all else fails, we use the default graph, which is always there.", "return", "graph", "or", "get_default_graph", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L3769-L3827
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/mailbox.py
python
Mailbox.get_string
(self, key)
return email.message_from_bytes(self.get_bytes(key)).as_string()
Return a string representation or raise a KeyError. Uses email.message.Message to create a 7bit clean string representation of the message.
Return a string representation or raise a KeyError.
[ "Return", "a", "string", "representation", "or", "raise", "a", "KeyError", "." ]
def get_string(self, key): """Return a string representation or raise a KeyError. Uses email.message.Message to create a 7bit clean string representation of the message.""" return email.message_from_bytes(self.get_bytes(key)).as_string()
[ "def", "get_string", "(", "self", ",", "key", ")", ":", "return", "email", ".", "message_from_bytes", "(", "self", ".", "get_bytes", "(", "key", ")", ")", ".", "as_string", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mailbox.py#L82-L87
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/converters/lists.py
python
ListTransformer._postprocess_statement
(self, node)
return node, None
Inserts any separate pop() calls that node may use.
Inserts any separate pop() calls that node may use.
[ "Inserts", "any", "separate", "pop", "()", "calls", "that", "node", "may", "use", "." ]
def _postprocess_statement(self, node): """Inserts any separate pop() calls that node may use.""" pop_uses = self.get_local(POP_USES, None) if pop_uses: replacements = [] for original_call_node, pop_var_name in pop_uses: replacements.extend( self._generate_pop_operation(original_call_node, pop_var_name)) replacements.append(node) node = replacements self.exit_local_scope() return node, None
[ "def", "_postprocess_statement", "(", "self", ",", "node", ")", ":", "pop_uses", "=", "self", ".", "get_local", "(", "POP_USES", ",", "None", ")", "if", "pop_uses", ":", "replacements", "=", "[", "]", "for", "original_call_node", ",", "pop_var_name", "in", "pop_uses", ":", "replacements", ".", "extend", "(", "self", ".", "_generate_pop_operation", "(", "original_call_node", ",", "pop_var_name", ")", ")", "replacements", ".", "append", "(", "node", ")", "node", "=", "replacements", "self", ".", "exit_local_scope", "(", ")", "return", "node", ",", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/converters/lists.py#L185-L196
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/common.py
python
EncodePOSIXShellList
(list)
return ' '.join(encoded_arguments)
Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator.
Encodes |list| suitably for consumption by POSIX shells.
[ "Encodes", "|list|", "suitably", "for", "consumption", "by", "POSIX", "shells", "." ]
def EncodePOSIXShellList(list): """Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator. """ encoded_arguments = [] for argument in list: encoded_arguments.append(EncodePOSIXShellArgument(argument)) return ' '.join(encoded_arguments)
[ "def", "EncodePOSIXShellList", "(", "list", ")", ":", "encoded_arguments", "=", "[", "]", "for", "argument", "in", "list", ":", "encoded_arguments", ".", "append", "(", "EncodePOSIXShellArgument", "(", "argument", ")", ")", "return", "' '", ".", "join", "(", "encoded_arguments", ")" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/common.py#L276-L286
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
libcxx/utils/gdb/libcxx/printers.py
python
RBTreeUtils.parent
(self, node)
return parent
Return the parent of node, if it exists.
Return the parent of node, if it exists.
[ "Return", "the", "parent", "of", "node", "if", "it", "exists", "." ]
def parent(self, node): """Return the parent of node, if it exists.""" # If this is the root, then from the algorithm's point of view, it has no # parent. if node == self.root: return None # We don't have enough information to tell if this is the end_node (which # doesn't have a __parent_ field), or the root (which doesn't have a parent # from the algorithm's point of view), so cast_type may not be correct for # this particular node. Use heuristics. # The end_node's left child is the root. Note that when printing interators # in isolation, the root is unknown. if self.left_child(node) == self.root: return None parent = node.cast(self.cast_type).dereference()["__parent_"] # If the value at the offset of __parent_ doesn't look like a valid pointer, # then assume that node is the end_node (and therefore has no parent). # End_node type has a pointer embedded, so should have pointer alignment. if addr_as_long(parent) % _void_pointer_type.alignof: return None # This is ugly, but the only other option is to dereference an invalid # pointer. 0x8000 is fairly arbitrary, but has had good results in # practice. If there was a way to tell if a pointer is invalid without # actually dereferencing it and spewing error messages, that would be ideal. if parent < 0x8000: return None return parent
[ "def", "parent", "(", "self", ",", "node", ")", ":", "# If this is the root, then from the algorithm's point of view, it has no", "# parent.", "if", "node", "==", "self", ".", "root", ":", "return", "None", "# We don't have enough information to tell if this is the end_node (which", "# doesn't have a __parent_ field), or the root (which doesn't have a parent", "# from the algorithm's point of view), so cast_type may not be correct for", "# this particular node. Use heuristics.", "# The end_node's left child is the root. Note that when printing interators", "# in isolation, the root is unknown.", "if", "self", ".", "left_child", "(", "node", ")", "==", "self", ".", "root", ":", "return", "None", "parent", "=", "node", ".", "cast", "(", "self", ".", "cast_type", ")", ".", "dereference", "(", ")", "[", "\"__parent_\"", "]", "# If the value at the offset of __parent_ doesn't look like a valid pointer,", "# then assume that node is the end_node (and therefore has no parent).", "# End_node type has a pointer embedded, so should have pointer alignment.", "if", "addr_as_long", "(", "parent", ")", "%", "_void_pointer_type", ".", "alignof", ":", "return", "None", "# This is ugly, but the only other option is to dereference an invalid", "# pointer. 0x8000 is fairly arbitrary, but has had good results in", "# practice. If there was a way to tell if a pointer is invalid without", "# actually dereferencing it and spewing error messages, that would be ideal.", "if", "parent", "<", "0x8000", ":", "return", "None", "return", "parent" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/libcxx/utils/gdb/libcxx/printers.py#L584-L613
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
BucketFunction.WriteHandlerImplementation
(self, file)
Overridden from Function
Overridden from Function
[ "Overridden", "from", "Function" ]
def WriteHandlerImplementation(self, file): """Overridden from Function""" self.type_handler.WriteBucketHandlerImplementation(self, file)
[ "def", "WriteHandlerImplementation", "(", "self", ",", "file", ")", ":", "self", ".", "type_handler", ".", "WriteBucketHandlerImplementation", "(", "self", ",", "file", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5518-L5520
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/scope.py
python
Scope.full_scope
(self)
return DeepChainMap(*maps)
Return the full scope for use with passing to engines transparently as a mapping. Returns ------- vars : DeepChainMap All variables in this scope.
Return the full scope for use with passing to engines transparently as a mapping.
[ "Return", "the", "full", "scope", "for", "use", "with", "passing", "to", "engines", "transparently", "as", "a", "mapping", "." ]
def full_scope(self): """ Return the full scope for use with passing to engines transparently as a mapping. Returns ------- vars : DeepChainMap All variables in this scope. """ maps = [self.temps] + self.resolvers.maps + self.scope.maps return DeepChainMap(*maps)
[ "def", "full_scope", "(", "self", ")", ":", "maps", "=", "[", "self", ".", "temps", "]", "+", "self", ".", "resolvers", ".", "maps", "+", "self", ".", "scope", ".", "maps", "return", "DeepChainMap", "(", "*", "maps", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/scope.py#L303-L314
microsoft/AirSim
8057725712c0cd46979135396381784075ffc0f3
PythonClient/airsim/client.py
python
VehicleClient.simGetObjectPose
(self, object_name)
return Pose.from_msgpack(pose)
The position inside the returned Pose is in the world frame Args: object_name (str): Object to get the Pose of Returns: Pose:
The position inside the returned Pose is in the world frame
[ "The", "position", "inside", "the", "returned", "Pose", "is", "in", "the", "world", "frame" ]
def simGetObjectPose(self, object_name): """ The position inside the returned Pose is in the world frame Args: object_name (str): Object to get the Pose of Returns: Pose: """ pose = self.client.call('simGetObjectPose', object_name) return Pose.from_msgpack(pose)
[ "def", "simGetObjectPose", "(", "self", ",", "object_name", ")", ":", "pose", "=", "self", ".", "client", ".", "call", "(", "'simGetObjectPose'", ",", "object_name", ")", "return", "Pose", ".", "from_msgpack", "(", "pose", ")" ]
https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/client.py#L486-L497
logcabin/logcabin
ee6c55ae9744b82b451becd9707d26c7c1b6bbfb
scripts/cpplint.py
python
FileInfo.RepositoryName
(self)
return fullname
FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors.
FullName after removing the local path to the repository.
[ "FullName", "after", "removing", "the", "local", "path", "to", "the", "repository", "." ]
def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN? Try to find a git top level directory by searching up from the # current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and not os.path.exists(os.path.join(root_dir, ".git"))): root_dir = os.path.dirname(root_dir) if os.path.exists(os.path.join(root_dir, ".git")): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname
[ "def", "RepositoryName", "(", "self", ")", ":", "fullname", "=", "self", ".", "FullName", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "fullname", ")", ":", "project_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "project_dir", ",", "\".svn\"", ")", ")", ":", "# If there's a .svn file in the current directory, we recursively look", "# up the directory tree for the top of the SVN checkout", "root_dir", "=", "project_dir", "one_up_dir", "=", "os", ".", "path", ".", "dirname", "(", "root_dir", ")", "while", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "one_up_dir", ",", "\".svn\"", ")", ")", ":", "root_dir", "=", "os", ".", "path", ".", "dirname", "(", "root_dir", ")", "one_up_dir", "=", "os", ".", "path", ".", "dirname", "(", "one_up_dir", ")", "prefix", "=", "os", ".", "path", ".", "commonprefix", "(", "[", "root_dir", ",", "project_dir", "]", ")", "return", "fullname", "[", "len", "(", "prefix", ")", "+", "1", ":", "]", "# Not SVN? Try to find a git top level directory by searching up from the", "# current path.", "root_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "while", "(", "root_dir", "!=", "os", ".", "path", ".", "dirname", "(", "root_dir", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "\".git\"", ")", ")", ")", ":", "root_dir", "=", "os", ".", "path", ".", "dirname", "(", "root_dir", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "\".git\"", ")", ")", ":", "prefix", "=", "os", ".", "path", ".", "commonprefix", "(", "[", "root_dir", ",", "project_dir", "]", ")", "return", "fullname", "[", "len", "(", "prefix", ")", "+", "1", ":", "]", "# Don't know what to do; header guard warnings may be wrong...", "return", "fullname" ]
https://github.com/logcabin/logcabin/blob/ee6c55ae9744b82b451becd9707d26c7c1b6bbfb/scripts/cpplint.py#L648-L686
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
fpNeg
(a, ctx=None)
return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> fpNeg(x) -x >>> fpNeg(x).sort() FPSort(8, 24)
Create a Z3 floating-point addition expression.
[ "Create", "a", "Z3", "floating", "-", "point", "addition", "expression", "." ]
def fpNeg(a, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> fpNeg(x) -x >>> fpNeg(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
[ "def", "fpNeg", "(", "a", ",", "ctx", "=", "None", ")", ":", "ctx", "=", "_get_ctx", "(", "ctx", ")", "[", "a", "]", "=", "_coerce_fp_expr_list", "(", "[", "a", "]", ",", "ctx", ")", "return", "FPRef", "(", "Z3_mk_fpa_neg", "(", "ctx", ".", "ref", "(", ")", ",", "a", ".", "as_ast", "(", ")", ")", ",", "ctx", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L10008-L10021
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/array_ops.py
python
UniqueWithPad.__init__
(self)
init UniqueWithPad
init UniqueWithPad
[ "init", "UniqueWithPad" ]
def __init__(self): """init UniqueWithPad"""
[ "def", "__init__", "(", "self", ")", ":" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/array_ops.py#L1048-L1049
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchMaterial.py
python
_ArchMaterialTaskPanel.getFields
(self)
sets self.material from the contents of the task box
sets self.material from the contents of the task box
[ "sets", "self", ".", "material", "from", "the", "contents", "of", "the", "task", "box" ]
def getFields(self): "sets self.material from the contents of the task box" self.material['Name'] = self.form.FieldName.text() self.material['Description'] = self.form.FieldDescription.text() self.material['DiffuseColor'] = self.getColorFromIcon(self.form.ButtonColor.icon()) self.material['ViewColor'] = self.material['DiffuseColor'] self.material['Color'] = self.material['DiffuseColor'] self.material['SectionColor'] = self.getColorFromIcon(self.form.ButtonSectionColor.icon()) self.material['StandardCode'] = self.form.FieldCode.text() self.material['ProductURL'] = self.form.FieldUrl.text() self.material['Transparency'] = str(self.form.SpinBox_Transparency.value())
[ "def", "getFields", "(", "self", ")", ":", "self", ".", "material", "[", "'Name'", "]", "=", "self", ".", "form", ".", "FieldName", ".", "text", "(", ")", "self", ".", "material", "[", "'Description'", "]", "=", "self", ".", "form", ".", "FieldDescription", ".", "text", "(", ")", "self", ".", "material", "[", "'DiffuseColor'", "]", "=", "self", ".", "getColorFromIcon", "(", "self", ".", "form", ".", "ButtonColor", ".", "icon", "(", ")", ")", "self", ".", "material", "[", "'ViewColor'", "]", "=", "self", ".", "material", "[", "'DiffuseColor'", "]", "self", ".", "material", "[", "'Color'", "]", "=", "self", ".", "material", "[", "'DiffuseColor'", "]", "self", ".", "material", "[", "'SectionColor'", "]", "=", "self", ".", "getColorFromIcon", "(", "self", ".", "form", ".", "ButtonSectionColor", ".", "icon", "(", ")", ")", "self", ".", "material", "[", "'StandardCode'", "]", "=", "self", ".", "form", ".", "FieldCode", ".", "text", "(", ")", "self", ".", "material", "[", "'ProductURL'", "]", "=", "self", ".", "form", ".", "FieldUrl", ".", "text", "(", ")", "self", ".", "material", "[", "'Transparency'", "]", "=", "str", "(", "self", ".", "form", ".", "SpinBox_Transparency", ".", "value", "(", ")", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchMaterial.py#L598-L608
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py
python
Cursor.linkage
(self)
return LinkageKind.from_id(self._linkage)
Return the linkage of this cursor.
Return the linkage of this cursor.
[ "Return", "the", "linkage", "of", "this", "cursor", "." ]
def linkage(self): """Return the linkage of this cursor.""" if not hasattr(self, '_linkage'): self._linkage = conf.lib.clang_getCursorLinkage(self) return LinkageKind.from_id(self._linkage)
[ "def", "linkage", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_linkage'", ")", ":", "self", ".", "_linkage", "=", "conf", ".", "lib", ".", "clang_getCursorLinkage", "(", "self", ")", "return", "LinkageKind", ".", "from_id", "(", "self", ".", "_linkage", ")" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py#L1585-L1590
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/serverui/sdhashsrv/sdhashsrv.py
python
Iface.displayResultStatus
(self, resultID)
Parameters: - resultID
Parameters: - resultID
[ "Parameters", ":", "-", "resultID" ]
def displayResultStatus(self, resultID): """ Parameters: - resultID """ pass
[ "def", "displayResultStatus", "(", "self", ",", "resultID", ")", ":", "pass" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/serverui/sdhashsrv/sdhashsrv.py#L130-L135
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/python/cp_model.py
python
CpModel.AddAbsEquality
(self, target, expr)
return ct
Adds `target == Abs(var)`.
Adds `target == Abs(var)`.
[ "Adds", "target", "==", "Abs", "(", "var", ")", "." ]
def AddAbsEquality(self, target, expr): """Adds `target == Abs(var)`.""" ct = Constraint(self.__model.constraints) model_ct = self.__model.constraints[ct.Index()] model_ct.lin_max.exprs.append(self.ParseLinearExpression(expr)) model_ct.lin_max.exprs.append(self.ParseLinearExpression(expr, True)) model_ct.lin_max.target.CopyFrom(self.ParseLinearExpression(target)) return ct
[ "def", "AddAbsEquality", "(", "self", ",", "target", ",", "expr", ")", ":", "ct", "=", "Constraint", "(", "self", ".", "__model", ".", "constraints", ")", "model_ct", "=", "self", ".", "__model", ".", "constraints", "[", "ct", ".", "Index", "(", ")", "]", "model_ct", ".", "lin_max", ".", "exprs", ".", "append", "(", "self", ".", "ParseLinearExpression", "(", "expr", ")", ")", "model_ct", ".", "lin_max", ".", "exprs", ".", "append", "(", "self", ".", "ParseLinearExpression", "(", "expr", ",", "True", ")", ")", "model_ct", ".", "lin_max", ".", "target", ".", "CopyFrom", "(", "self", ".", "ParseLinearExpression", "(", "target", ")", ")", "return", "ct" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1523-L1530
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookies.py
python
_quote
(str)
r"""Quote a string for use in a cookie header. If the string does not need to be double-quoted, then just return the string. Otherwise, surround the string in doublequotes and quote (with a \) special characters.
r"""Quote a string for use in a cookie header.
[ "r", "Quote", "a", "string", "for", "use", "in", "a", "cookie", "header", "." ]
def _quote(str): r"""Quote a string for use in a cookie header. If the string does not need to be double-quoted, then just return the string. Otherwise, surround the string in doublequotes and quote (with a \) special characters. """ if str is None or _is_legal_key(str): return str else: return '"' + str.translate(_Translator) + '"'
[ "def", "_quote", "(", "str", ")", ":", "if", "str", "is", "None", "or", "_is_legal_key", "(", "str", ")", ":", "return", "str", "else", ":", "return", "'\"'", "+", "str", ".", "translate", "(", "_Translator", ")", "+", "'\"'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookies.py#L173-L183
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/scripts/cpp_lint.py
python
CheckForHeaderGuard
(filename, lines, error)
Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Checks that the file contains a header guard.
[ "Checks", "that", "the", "file", "contains", "a", "header", "guard", "." ]
def CheckForHeaderGuard(filename, lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ cppvar = GetHeaderGuardCPPVariable(filename) ifndef = None ifndef_linenum = 0 define = None endif = None endif_linenum = 0 for linenum, line in enumerate(lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return if not define: error(filename, 0, 'build/header_guard', 5, 'No #define header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) if define != ifndef: error(filename, 0, 'build/header_guard', 5, '#ifndef and #define don\'t match, suggested CPP variable is: %s' % cppvar) return if endif != ('#endif // %s' % cppvar): error_level = 0 if endif != ('#endif // %s' % (cppvar + '_')): error_level = 5 ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, error) error(filename, endif_linenum, 'build/header_guard', error_level, '#endif line should be "#endif // %s"' % cppvar)
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "lines", ",", "error", ")", ":", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "ifndef", "=", "None", "ifndef_linenum", "=", "0", "define", "=", "None", "endif", "=", "None", "endif_linenum", "=", "0", "for", "linenum", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "linesplit", "=", "line", ".", "split", "(", ")", "if", "len", "(", "linesplit", ")", ">=", "2", ":", "# find the first occurrence of #ifndef and #define, save arg", "if", "not", "ifndef", "and", "linesplit", "[", "0", "]", "==", "'#ifndef'", ":", "# set ifndef to the header guard presented on the #ifndef line.", "ifndef", "=", "linesplit", "[", "1", "]", "ifndef_linenum", "=", "linenum", "if", "not", "define", "and", "linesplit", "[", "0", "]", "==", "'#define'", ":", "define", "=", "linesplit", "[", "1", "]", "# find the last occurrence of #endif, save entire line", "if", "line", ".", "startswith", "(", "'#endif'", ")", ":", "endif", "=", "line", "endif_linenum", "=", "linenum", "if", "not", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #ifndef header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "not", "define", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #define header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__", "# for backward compatibility.", "if", "ifndef", "!=", "cppvar", ":", "error_level", "=", "0", "if", "ifndef", "!=", "cppvar", "+", "'_'", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "ifndef_linenum", "]", ",", "ifndef_linenum", ",", "error", ")", "error", "(", "filename", ",", "ifndef_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#ifndef header guard has wrong style, please use: %s'", "%", "cppvar", ")", "if", "define", "!=", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'#ifndef and #define don\\'t match, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "endif", "!=", "(", "'#endif // %s'", "%", "cppvar", ")", ":", "error_level", "=", "0", "if", "endif", "!=", "(", "'#endif // %s'", "%", "(", "cppvar", "+", "'_'", ")", ")", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "endif_linenum", "]", ",", "endif_linenum", ",", "error", ")", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/scripts/cpp_lint.py#L1408-L1480
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/quoprimime.py
python
unquote
(s)
return chr(int(s[1:3], 16))
Turn a string in the form =AB to the ASCII character with value 0xab
Turn a string in the form =AB to the ASCII character with value 0xab
[ "Turn", "a", "string", "in", "the", "form", "=", "AB", "to", "the", "ASCII", "character", "with", "value", "0xab" ]
def unquote(s): """Turn a string in the form =AB to the ASCII character with value 0xab""" return chr(int(s[1:3], 16))
[ "def", "unquote", "(", "s", ")", ":", "return", "chr", "(", "int", "(", "s", "[", "1", ":", "3", "]", ",", "16", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/quoprimime.py#L118-L120
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/datetimelike.py
python
DatetimeLikeArrayMixin._add_delta_tdi
(self, other)
return new_values.view("i8")
Add a delta of a TimedeltaIndex return the i8 result view
Add a delta of a TimedeltaIndex return the i8 result view
[ "Add", "a", "delta", "of", "a", "TimedeltaIndex", "return", "the", "i8", "result", "view" ]
def _add_delta_tdi(self, other): """ Add a delta of a TimedeltaIndex return the i8 result view """ if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isinstance(other, np.ndarray): # ndarray[timedelta64]; wrap in TimedeltaIndex for op from pandas.core.arrays import TimedeltaArray other = TimedeltaArray._from_sequence(other) self_i8 = self.asi8 other_i8 = other.asi8 new_values = checked_add_with_arr( self_i8, other_i8, arr_mask=self._isnan, b_mask=other._isnan ) if self._hasnans or other._hasnans: mask = (self._isnan) | (other._isnan) new_values[mask] = iNaT return new_values.view("i8")
[ "def", "_add_delta_tdi", "(", "self", ",", "other", ")", ":", "if", "len", "(", "self", ")", "!=", "len", "(", "other", ")", ":", "raise", "ValueError", "(", "\"cannot add indices of unequal length\"", ")", "if", "isinstance", "(", "other", ",", "np", ".", "ndarray", ")", ":", "# ndarray[timedelta64]; wrap in TimedeltaIndex for op", "from", "pandas", ".", "core", ".", "arrays", "import", "TimedeltaArray", "other", "=", "TimedeltaArray", ".", "_from_sequence", "(", "other", ")", "self_i8", "=", "self", ".", "asi8", "other_i8", "=", "other", ".", "asi8", "new_values", "=", "checked_add_with_arr", "(", "self_i8", ",", "other_i8", ",", "arr_mask", "=", "self", ".", "_isnan", ",", "b_mask", "=", "other", ".", "_isnan", ")", "if", "self", ".", "_hasnans", "or", "other", ".", "_hasnans", ":", "mask", "=", "(", "self", ".", "_isnan", ")", "|", "(", "other", ".", "_isnan", ")", "new_values", "[", "mask", "]", "=", "iNaT", "return", "new_values", ".", "view", "(", "\"i8\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/datetimelike.py#L1159-L1181
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
MenuBar.GetMenu
(*args, **kwargs)
return _core_.MenuBar_GetMenu(*args, **kwargs)
GetMenu(self, size_t pos) -> Menu
GetMenu(self, size_t pos) -> Menu
[ "GetMenu", "(", "self", "size_t", "pos", ")", "-", ">", "Menu" ]
def GetMenu(*args, **kwargs): """GetMenu(self, size_t pos) -> Menu""" return _core_.MenuBar_GetMenu(*args, **kwargs)
[ "def", "GetMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuBar_GetMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12280-L12282
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
ppapi/generators/idl_parser.py
python
IDLParser.p_ext_attr_list
(self, p)
ext_attr_list : SYMBOL '=' SYMBOL ext_attr_cont | SYMBOL '=' value ext_attr_cont | SYMBOL '=' SYMBOL param_list ext_attr_cont | SYMBOL ext_attr_cont
ext_attr_list : SYMBOL '=' SYMBOL ext_attr_cont | SYMBOL '=' value ext_attr_cont | SYMBOL '=' SYMBOL param_list ext_attr_cont | SYMBOL ext_attr_cont
[ "ext_attr_list", ":", "SYMBOL", "=", "SYMBOL", "ext_attr_cont", "|", "SYMBOL", "=", "value", "ext_attr_cont", "|", "SYMBOL", "=", "SYMBOL", "param_list", "ext_attr_cont", "|", "SYMBOL", "ext_attr_cont" ]
def p_ext_attr_list(self, p): """ext_attr_list : SYMBOL '=' SYMBOL ext_attr_cont | SYMBOL '=' value ext_attr_cont | SYMBOL '=' SYMBOL param_list ext_attr_cont | SYMBOL ext_attr_cont""" # If there are 4 tokens plus a return slot, this must be in the form # SYMBOL = SYMBOL|value ext_attr_cont if len(p) == 5: p[0] = ListFromConcat(self.BuildAttribute(p[1], p[3]), p[4]) # If there are 5 tokens plus a return slot, this must be in the form # SYMBOL = SYMBOL (param_list) ext_attr_cont elif len(p) == 6: member = self.BuildNamed('Member', p, 3, [p[4]]) p[0] = ListFromConcat(self.BuildAttribute(p[1], member), p[5]) # Otherwise, this must be: SYMBOL ext_attr_cont else: p[0] = ListFromConcat(self.BuildAttribute(p[1], 'True'), p[2]) if self.parse_debug: DumpReduction('ext_attribute_list', p)
[ "def", "p_ext_attr_list", "(", "self", ",", "p", ")", ":", "# If there are 4 tokens plus a return slot, this must be in the form", "# SYMBOL = SYMBOL|value ext_attr_cont", "if", "len", "(", "p", ")", "==", "5", ":", "p", "[", "0", "]", "=", "ListFromConcat", "(", "self", ".", "BuildAttribute", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", ",", "p", "[", "4", "]", ")", "# If there are 5 tokens plus a return slot, this must be in the form", "# SYMBOL = SYMBOL (param_list) ext_attr_cont", "elif", "len", "(", "p", ")", "==", "6", ":", "member", "=", "self", ".", "BuildNamed", "(", "'Member'", ",", "p", ",", "3", ",", "[", "p", "[", "4", "]", "]", ")", "p", "[", "0", "]", "=", "ListFromConcat", "(", "self", ".", "BuildAttribute", "(", "p", "[", "1", "]", ",", "member", ")", ",", "p", "[", "5", "]", ")", "# Otherwise, this must be: SYMBOL ext_attr_cont", "else", ":", "p", "[", "0", "]", "=", "ListFromConcat", "(", "self", ".", "BuildAttribute", "(", "p", "[", "1", "]", ",", "'True'", ")", ",", "p", "[", "2", "]", ")", "if", "self", ".", "parse_debug", ":", "DumpReduction", "(", "'ext_attribute_list'", ",", "p", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/ppapi/generators/idl_parser.py#L377-L394
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/build/property.py
python
PropertyMap.insert
(self, properties, value)
Associate value with properties.
Associate value with properties.
[ "Associate", "value", "with", "properties", "." ]
def insert (self, properties, value): """ Associate value with properties. """ assert is_iterable_typed(properties, basestring) assert isinstance(value, basestring) self.__properties.append(properties) self.__values.append(value)
[ "def", "insert", "(", "self", ",", "properties", ",", "value", ")", ":", "assert", "is_iterable_typed", "(", "properties", ",", "basestring", ")", "assert", "isinstance", "(", "value", ",", "basestring", ")", "self", ".", "__properties", ".", "append", "(", "properties", ")", "self", ".", "__values", ".", "append", "(", "value", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/property.py#L590-L596
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/sparse.py
python
SparseArray.npoints
(self)
return self.sp_index.npoints
The number of non- ``fill_value`` points. Examples -------- >>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0) >>> s.npoints 3
The number of non- ``fill_value`` points.
[ "The", "number", "of", "non", "-", "fill_value", "points", "." ]
def npoints(self): """ The number of non- ``fill_value`` points. Examples -------- >>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0) >>> s.npoints 3 """ return self.sp_index.npoints
[ "def", "npoints", "(", "self", ")", ":", "return", "self", ".", "sp_index", ".", "npoints" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/sparse.py#L810-L820
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/install_egg_info.py
python
to_filename
(name)
return name.replace('-','_')
Convert a project or version name to its filename-escaped form Any '-' characters are currently replaced with '_'.
Convert a project or version name to its filename-escaped form
[ "Convert", "a", "project", "or", "version", "name", "to", "its", "filename", "-", "escaped", "form" ]
def to_filename(name): """Convert a project or version name to its filename-escaped form Any '-' characters are currently replaced with '_'. """ return name.replace('-','_')
[ "def", "to_filename", "(", "name", ")", ":", "return", "name", ".", "replace", "(", "'-'", ",", "'_'", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/install_egg_info.py#L73-L78
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dispatcher.py
python
_DispatcherBase.typeof_pyval
(self, val)
return tp
Resolve the Numba type of Python value *val*. This is called from numba._dispatcher as a fallback if the native code cannot decide the type.
Resolve the Numba type of Python value *val*. This is called from numba._dispatcher as a fallback if the native code cannot decide the type.
[ "Resolve", "the", "Numba", "type", "of", "Python", "value", "*", "val", "*", ".", "This", "is", "called", "from", "numba", ".", "_dispatcher", "as", "a", "fallback", "if", "the", "native", "code", "cannot", "decide", "the", "type", "." ]
def typeof_pyval(self, val): """ Resolve the Numba type of Python value *val*. This is called from numba._dispatcher as a fallback if the native code cannot decide the type. """ # Not going through the resolve_argument_type() indirection # can save a couple µs. try: tp = typeof(val, Purpose.argument) except ValueError: tp = types.pyobject else: if tp is None: tp = types.pyobject return tp
[ "def", "typeof_pyval", "(", "self", ",", "val", ")", ":", "# Not going through the resolve_argument_type() indirection", "# can save a couple µs.", "try", ":", "tp", "=", "typeof", "(", "val", ",", "Purpose", ".", "argument", ")", "except", "ValueError", ":", "tp", "=", "types", ".", "pyobject", "else", ":", "if", "tp", "is", "None", ":", "tp", "=", "types", ".", "pyobject", "return", "tp" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dispatcher.py#L595-L610
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_futures.py
python
_format_callbacks
(cb)
return f'cb=[{cb}]'
helper function for Future.__repr__
helper function for Future.__repr__
[ "helper", "function", "for", "Future", ".", "__repr__" ]
def _format_callbacks(cb): """helper function for Future.__repr__""" size = len(cb) if not size: cb = '' def format_cb(callback): return format_helpers._format_callback_source(callback, ()) if size == 1: cb = format_cb(cb[0][0]) elif size == 2: cb = '{}, {}'.format(format_cb(cb[0][0]), format_cb(cb[1][0])) elif size > 2: cb = '{}, <{} more>, {}'.format(format_cb(cb[0][0]), size - 2, format_cb(cb[-1][0])) return f'cb=[{cb}]'
[ "def", "_format_callbacks", "(", "cb", ")", ":", "size", "=", "len", "(", "cb", ")", "if", "not", "size", ":", "cb", "=", "''", "def", "format_cb", "(", "callback", ")", ":", "return", "format_helpers", ".", "_format_callback_source", "(", "callback", ",", "(", ")", ")", "if", "size", "==", "1", ":", "cb", "=", "format_cb", "(", "cb", "[", "0", "]", "[", "0", "]", ")", "elif", "size", "==", "2", ":", "cb", "=", "'{}, {}'", ".", "format", "(", "format_cb", "(", "cb", "[", "0", "]", "[", "0", "]", ")", ",", "format_cb", "(", "cb", "[", "1", "]", "[", "0", "]", ")", ")", "elif", "size", ">", "2", ":", "cb", "=", "'{}, <{} more>, {}'", ".", "format", "(", "format_cb", "(", "cb", "[", "0", "]", "[", "0", "]", ")", ",", "size", "-", "2", ",", "format_cb", "(", "cb", "[", "-", "1", "]", "[", "0", "]", ")", ")", "return", "f'cb=[{cb}]'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_futures.py#L34-L51
esphome/esphome
40e06c9819f17409615d4f4eec5cfe4dc9a3776d
esphome/cpp_generator.py
python
add_global
(expression: Union[SafeExpType, Statement])
Add an expression to the codegen global storage (above setup()).
Add an expression to the codegen global storage (above setup()).
[ "Add", "an", "expression", "to", "the", "codegen", "global", "storage", "(", "above", "setup", "()", ")", "." ]
def add_global(expression: Union[SafeExpType, Statement]): """Add an expression to the codegen global storage (above setup()).""" CORE.add_global(expression)
[ "def", "add_global", "(", "expression", ":", "Union", "[", "SafeExpType", ",", "Statement", "]", ")", ":", "CORE", ".", "add_global", "(", "expression", ")" ]
https://github.com/esphome/esphome/blob/40e06c9819f17409615d4f4eec5cfe4dc9a3776d/esphome/cpp_generator.py#L563-L565
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/common_shapes.py
python
is_broadcast_compatible
(shape_x, shape_y)
return _broadcast_shape_helper(shape_x, shape_y) is not None
Returns True if `shape_x` and `shape_y` are broadcast compatible. Args: shape_x: A `TensorShape` shape_y: A `TensorShape` Returns: True if a shape exists that both `shape_x` and `shape_y` can be broadcasted to. False otherwise.
Returns True if `shape_x` and `shape_y` are broadcast compatible.
[ "Returns", "True", "if", "shape_x", "and", "shape_y", "are", "broadcast", "compatible", "." ]
def is_broadcast_compatible(shape_x, shape_y): """Returns True if `shape_x` and `shape_y` are broadcast compatible. Args: shape_x: A `TensorShape` shape_y: A `TensorShape` Returns: True if a shape exists that both `shape_x` and `shape_y` can be broadcasted to. False otherwise. """ if shape_x.ndims is None or shape_y.ndims is None: return False return _broadcast_shape_helper(shape_x, shape_y) is not None
[ "def", "is_broadcast_compatible", "(", "shape_x", ",", "shape_y", ")", ":", "if", "shape_x", ".", "ndims", "is", "None", "or", "shape_y", ".", "ndims", "is", "None", ":", "return", "False", "return", "_broadcast_shape_helper", "(", "shape_x", ",", "shape_y", ")", "is", "not", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/common_shapes.py#L562-L575
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/ftplib.py
python
FTP.retrbinary
(self, cmd, callback, blocksize=8192, rest=None)
return self.voidresp()
Retrieve data in binary mode. A new port is created for you. Args: cmd: A RETR command. callback: A single parameter callable to be called on each block of data read. blocksize: The maximum number of bytes to read from the socket at one time. [default: 8192] rest: Passed to transfercmd(). [default: None] Returns: The response code.
Retrieve data in binary mode. A new port is created for you.
[ "Retrieve", "data", "in", "binary", "mode", ".", "A", "new", "port", "is", "created", "for", "you", "." ]
def retrbinary(self, cmd, callback, blocksize=8192, rest=None): """Retrieve data in binary mode. A new port is created for you. Args: cmd: A RETR command. callback: A single parameter callable to be called on each block of data read. blocksize: The maximum number of bytes to read from the socket at one time. [default: 8192] rest: Passed to transfercmd(). [default: None] Returns: The response code. """ self.voidcmd('TYPE I') conn = self.transfercmd(cmd, rest) while 1: data = conn.recv(blocksize) if not data: break callback(data) conn.close() return self.voidresp()
[ "def", "retrbinary", "(", "self", ",", "cmd", ",", "callback", ",", "blocksize", "=", "8192", ",", "rest", "=", "None", ")", ":", "self", ".", "voidcmd", "(", "'TYPE I'", ")", "conn", "=", "self", ".", "transfercmd", "(", "cmd", ",", "rest", ")", "while", "1", ":", "data", "=", "conn", ".", "recv", "(", "blocksize", ")", "if", "not", "data", ":", "break", "callback", "(", "data", ")", "conn", ".", "close", "(", ")", "return", "self", ".", "voidresp", "(", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ftplib.py#L379-L401
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py
python
Filterer.removeFilter
(self, filter)
Remove the specified filter from this handler.
Remove the specified filter from this handler.
[ "Remove", "the", "specified", "filter", "from", "this", "handler", "." ]
def removeFilter(self, filter): """ Remove the specified filter from this handler. """ if filter in self.filters: self.filters.remove(filter)
[ "def", "removeFilter", "(", "self", ",", "filter", ")", ":", "if", "filter", "in", "self", ".", "filters", ":", "self", ".", "filters", ".", "remove", "(", "filter", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py#L729-L734
Constellation/iv
64c3a9c7c517063f29d90d449180ea8f6f4d946f
tools/cpplint.py
python
CheckForCopyright
(filename, lines, error)
Logs an error if no Copyright message appears at the top of the file.
Logs an error if no Copyright message appears at the top of the file.
[ "Logs", "an", "error", "if", "no", "Copyright", "message", "appears", "at", "the", "top", "of", "the", "file", "." ]
def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in xrange(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): break else: # means no copyright line was found error(filename, 0, 'legal/copyright', 5, 'No copyright message found. ' 'You should have a line: "Copyright [year] <Copyright Owner>"')
[ "def", "CheckForCopyright", "(", "filename", ",", "lines", ",", "error", ")", ":", "# We'll say it should occur by line 10. Don't forget there's a", "# dummy line at the front.", "for", "line", "in", "xrange", "(", "1", ",", "min", "(", "len", "(", "lines", ")", ",", "11", ")", ")", ":", "if", "re", ".", "search", "(", "r'Copyright'", ",", "lines", "[", "line", "]", ",", "re", ".", "I", ")", ":", "break", "else", ":", "# means no copyright line was found", "error", "(", "filename", ",", "0", ",", "'legal/copyright'", ",", "5", ",", "'No copyright message found. '", "'You should have a line: \"Copyright [year] <Copyright Owner>\"'", ")" ]
https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L1360-L1370