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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/eslint.py | python | get_eslint_from_cache | (dest_file, platform, arch) | Get ESLint binary from mongodb's cache. | Get ESLint binary from mongodb's cache. | [
"Get",
"ESLint",
"binary",
"from",
"mongodb",
"s",
"cache",
"."
] | def get_eslint_from_cache(dest_file, platform, arch):
"""Get ESLint binary from mongodb's cache."""
# Get URL
if platform == "Linux":
url = ESLINT_HTTP_LINUX_CACHE
elif platform == "Darwin":
url = ESLINT_HTTP_DARWIN_CACHE
else:
raise ValueError('ESLint is not available as a binary for ' + platform)
dest_dir = tempfile.gettempdir()
temp_tar_file = os.path.join(dest_dir, "temp.tar.gz")
# Download the file
print("Downloading ESLint %s from %s, saving to %s" % (ESLINT_VERSION, url, temp_tar_file))
urllib.request.urlretrieve(url, temp_tar_file)
# pylint: disable=too-many-function-args
print("Extracting ESLint %s to %s" % (ESLINT_VERSION, dest_file))
eslint_distfile = ESLINT_SOURCE_TAR_BASE.substitute(platform=platform, arch=arch)
extract_eslint(temp_tar_file, eslint_distfile)
shutil.move(eslint_distfile, dest_file) | [
"def",
"get_eslint_from_cache",
"(",
"dest_file",
",",
"platform",
",",
"arch",
")",
":",
"# Get URL",
"if",
"platform",
"==",
"\"Linux\"",
":",
"url",
"=",
"ESLINT_HTTP_LINUX_CACHE",
"elif",
"platform",
"==",
"\"Darwin\"",
":",
"url",
"=",
"ESLINT_HTTP_DARWIN_CACHE",
"else",
":",
"raise",
"ValueError",
"(",
"'ESLint is not available as a binary for '",
"+",
"platform",
")",
"dest_dir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"temp_tar_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"\"temp.tar.gz\"",
")",
"# Download the file",
"print",
"(",
"\"Downloading ESLint %s from %s, saving to %s\"",
"%",
"(",
"ESLINT_VERSION",
",",
"url",
",",
"temp_tar_file",
")",
")",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"url",
",",
"temp_tar_file",
")",
"# pylint: disable=too-many-function-args",
"print",
"(",
"\"Extracting ESLint %s to %s\"",
"%",
"(",
"ESLINT_VERSION",
",",
"dest_file",
")",
")",
"eslint_distfile",
"=",
"ESLINT_SOURCE_TAR_BASE",
".",
"substitute",
"(",
"platform",
"=",
"platform",
",",
"arch",
"=",
"arch",
")",
"extract_eslint",
"(",
"temp_tar_file",
",",
"eslint_distfile",
")",
"shutil",
".",
"move",
"(",
"eslint_distfile",
",",
"dest_file",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/eslint.py#L79-L100 | ||
vtraag/leidenalg | b53366829360e10922a2dbf57eb405a516c23bc9 | setup.py | python | BuildConfiguration.print_build_info | (self) | Prints the include and library path being used for debugging purposes. | Prints the include and library path being used for debugging purposes. | [
"Prints",
"the",
"include",
"and",
"library",
"path",
"being",
"used",
"for",
"debugging",
"purposes",
"."
] | def print_build_info(self):
"""Prints the include and library path being used for debugging purposes."""
if self.static_extension == "only_igraph":
build_type = "dynamic extension with vendored igraph source"
elif self.static_extension:
build_type = "static extension"
else:
build_type = "dynamic extension"
print("Build type: %s" % build_type)
print("Include path: %s" % " ".join(self.include_dirs))
if self.excluded_include_dirs:
print(" - excluding: %s" % " ".join(self.excluded_include_dirs))
print("Library path: %s" % " ".join(self.library_dirs))
if self.excluded_library_dirs:
print(" - excluding: %s" % " ".join(self.excluded_library_dirs))
print("Runtime library path: %s" % " ".join(self.runtime_library_dirs))
print("Linked dynamic libraries: %s" % " ".join(self.libraries))
print("Linked static libraries: %s" % " ".join(self.extra_objects))
print("Extra compiler options: %s" % " ".join(self.extra_compile_args))
print("Extra linker options: %s" % " ".join(self.extra_link_args)) | [
"def",
"print_build_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"static_extension",
"==",
"\"only_igraph\"",
":",
"build_type",
"=",
"\"dynamic extension with vendored igraph source\"",
"elif",
"self",
".",
"static_extension",
":",
"build_type",
"=",
"\"static extension\"",
"else",
":",
"build_type",
"=",
"\"dynamic extension\"",
"print",
"(",
"\"Build type: %s\"",
"%",
"build_type",
")",
"print",
"(",
"\"Include path: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"include_dirs",
")",
")",
"if",
"self",
".",
"excluded_include_dirs",
":",
"print",
"(",
"\" - excluding: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"excluded_include_dirs",
")",
")",
"print",
"(",
"\"Library path: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"library_dirs",
")",
")",
"if",
"self",
".",
"excluded_library_dirs",
":",
"print",
"(",
"\" - excluding: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"excluded_library_dirs",
")",
")",
"print",
"(",
"\"Runtime library path: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"runtime_library_dirs",
")",
")",
"print",
"(",
"\"Linked dynamic libraries: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"libraries",
")",
")",
"print",
"(",
"\"Linked static libraries: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"extra_objects",
")",
")",
"print",
"(",
"\"Extra compiler options: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"extra_compile_args",
")",
")",
"print",
"(",
"\"Extra linker options: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"self",
".",
"extra_link_args",
")",
")"
] | https://github.com/vtraag/leidenalg/blob/b53366829360e10922a2dbf57eb405a516c23bc9/setup.py#L618-L637 | ||
fasiondog/hikyuu | 842751aa25283f9fdafc6f560ea262f79e67a307 | hikyuu/fetcher/proxy/proxy.py | python | request_with_local | (url) | return requests.get(url).text | 通过本机ip直接获取请求,访问失败将抛出异常 | 通过本机ip直接获取请求,访问失败将抛出异常 | [
"通过本机ip直接获取请求,访问失败将抛出异常"
] | def request_with_local(url):
"""通过本机ip直接获取请求,访问失败将抛出异常"""
return requests.get(url).text | [
"def",
"request_with_local",
"(",
"url",
")",
":",
"return",
"requests",
".",
"get",
"(",
"url",
")",
".",
"text"
] | https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/fetcher/proxy/proxy.py#L34-L36 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/examples/image_retraining/retrain.py | python | get_random_cached_bottlenecks | (sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
bottleneck_tensor) | return bottlenecks, ground_truths | Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: Dictionary of training images for each label.
how_many: The number of bottleneck values to return.
category: Name string of which set to pull from - training, testing, or
validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
image_dir: Root folder string of the subfolders containing the training
images.
jpeg_data_tensor: The layer to feed jpeg image data into.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths. | Retrieves bottleneck values for cached images. | [
"Retrieves",
"bottleneck",
"values",
"for",
"cached",
"images",
"."
] | def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
bottleneck_tensor):
"""Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: Dictionary of training images for each label.
how_many: The number of bottleneck values to return.
category: Name string of which set to pull from - training, testing, or
validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
image_dir: Root folder string of the subfolders containing the training
images.
jpeg_data_tensor: The layer to feed jpeg image data into.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(65536)
bottleneck = get_or_create_bottleneck(sess, image_lists, label_name,
image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor,
bottleneck_tensor)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth)
return bottlenecks, ground_truths | [
"def",
"get_random_cached_bottlenecks",
"(",
"sess",
",",
"image_lists",
",",
"how_many",
",",
"category",
",",
"bottleneck_dir",
",",
"image_dir",
",",
"jpeg_data_tensor",
",",
"bottleneck_tensor",
")",
":",
"class_count",
"=",
"len",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"bottlenecks",
"=",
"[",
"]",
"ground_truths",
"=",
"[",
"]",
"for",
"unused_i",
"in",
"range",
"(",
"how_many",
")",
":",
"label_index",
"=",
"random",
".",
"randrange",
"(",
"class_count",
")",
"label_name",
"=",
"list",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"[",
"label_index",
"]",
"image_index",
"=",
"random",
".",
"randrange",
"(",
"65536",
")",
"bottleneck",
"=",
"get_or_create_bottleneck",
"(",
"sess",
",",
"image_lists",
",",
"label_name",
",",
"image_index",
",",
"image_dir",
",",
"category",
",",
"bottleneck_dir",
",",
"jpeg_data_tensor",
",",
"bottleneck_tensor",
")",
"ground_truth",
"=",
"np",
".",
"zeros",
"(",
"class_count",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"ground_truth",
"[",
"label_index",
"]",
"=",
"1.0",
"bottlenecks",
".",
"append",
"(",
"bottleneck",
")",
"ground_truths",
".",
"append",
"(",
"ground_truth",
")",
"return",
"bottlenecks",
",",
"ground_truths"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/examples/image_retraining/retrain.py#L462-L501 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/engine/training.py | python | Model.compile | (self,
optimizer,
loss,
metrics=None,
loss_weights=None,
sample_weight_mode=None,
**kwargs) | Configures the model for training.
Arguments:
optimizer: str (name of optimizer) or optimizer object.
See [optimizers](/optimizers).
loss: str (name of objective function) or objective function.
See [losses](/losses).
If the model has multiple outputs, you can use a different loss
on each output by passing a dictionary or a list of losses.
The loss value that will be minimized by the model
will then be the sum of all individual losses.
metrics: list of metrics to be evaluated by the model
during training and testing.
Typically you will use `metrics=['accuracy']`.
To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary,
such as `metrics={'output_a': 'accuracy'}`.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions
of different model outputs.
The loss value that will be minimized by the model
will then be the *weighted sum* of all individual losses,
weighted by the `loss_weights` coefficients.
If a list, it is expected to have a 1:1 mapping
to the model's outputs. If a tensor, it is expected to map
output names (strings) to scalar coefficients.
sample_weight_mode: if you need to do timestep-wise
sample weighting (2D weights), set this to `"temporal"`.
`None` defaults to sample-wise weights (1D).
If the model has multiple outputs, you can use a different
`sample_weight_mode` on each output by passing a
dictionary or a list of modes.
**kwargs: Additional arguments passed to `tf.Session.run`.
Raises:
ValueError: In case of invalid arguments for
`optimizer`, `loss`, `metrics` or `sample_weight_mode`.
RuntimeError: In case of ill-formulated optimization problem. | Configures the model for training. | [
"Configures",
"the",
"model",
"for",
"training",
"."
] | def compile(self,
optimizer,
loss,
metrics=None,
loss_weights=None,
sample_weight_mode=None,
**kwargs):
"""Configures the model for training.
Arguments:
optimizer: str (name of optimizer) or optimizer object.
See [optimizers](/optimizers).
loss: str (name of objective function) or objective function.
See [losses](/losses).
If the model has multiple outputs, you can use a different loss
on each output by passing a dictionary or a list of losses.
The loss value that will be minimized by the model
will then be the sum of all individual losses.
metrics: list of metrics to be evaluated by the model
during training and testing.
Typically you will use `metrics=['accuracy']`.
To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary,
such as `metrics={'output_a': 'accuracy'}`.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions
of different model outputs.
The loss value that will be minimized by the model
will then be the *weighted sum* of all individual losses,
weighted by the `loss_weights` coefficients.
If a list, it is expected to have a 1:1 mapping
to the model's outputs. If a tensor, it is expected to map
output names (strings) to scalar coefficients.
sample_weight_mode: if you need to do timestep-wise
sample weighting (2D weights), set this to `"temporal"`.
`None` defaults to sample-wise weights (1D).
If the model has multiple outputs, you can use a different
`sample_weight_mode` on each output by passing a
dictionary or a list of modes.
**kwargs: Additional arguments passed to `tf.Session.run`.
Raises:
ValueError: In case of invalid arguments for
`optimizer`, `loss`, `metrics` or `sample_weight_mode`.
RuntimeError: In case of ill-formulated optimization problem.
"""
loss = loss or {}
self.optimizer = optimizers.get(optimizer)
self.sample_weight_mode = sample_weight_mode
self.loss = loss
self.loss_weights = loss_weights
# Prepare loss functions.
if isinstance(loss, dict):
for name in loss:
if name not in self.output_names:
raise ValueError('Unknown entry in loss '
'dictionary: "' + name + '". '
'Only expected the following keys: ' +
str(self.output_names))
loss_functions = []
for name in self.output_names:
if name not in loss:
logging.warning(
'Output "' + name + '" missing from loss dictionary. '
'We assume this was done on purpose, '
'and we will not be expecting '
'any data to be passed to "' + name + '" during training.',
stacklevel=2)
loss_functions.append(losses.get(loss.get(name)))
elif isinstance(loss, list):
if len(loss) != len(self.outputs):
raise ValueError('When passing a list as loss, '
'it should have one entry per model outputs. '
'The model has ' + str(len(self.outputs)) +
' outputs, but you passed loss=' + str(loss))
loss_functions = [losses.get(l) for l in loss]
else:
loss_function = losses.get(loss)
loss_functions = [loss_function for _ in range(len(self.outputs))]
self.loss_functions = loss_functions
weighted_losses = [_weighted_masked_objective(fn) for fn in loss_functions]
skip_indices = []
self._feed_outputs = []
self._feed_output_names = []
self._feed_output_shapes = []
self._feed_loss_fns = []
for i in range(len(weighted_losses)):
if weighted_losses[i] is None:
skip_indices.append(i)
else:
self._feed_outputs.append(self.outputs[i])
self._feed_output_names.append(self.output_names[i])
self._feed_output_shapes.append(self.internal_output_shapes[i])
self._feed_loss_fns.append(self.loss_functions[i])
# Prepare output masks.
masks = self.compute_mask(self.inputs, mask=None)
if masks is None:
masks = [None for _ in self.outputs]
if not isinstance(masks, list):
masks = [masks]
# Prepare loss weights.
if loss_weights is None:
loss_weights_list = [1. for _ in range(len(self.outputs))]
elif isinstance(loss_weights, dict):
for name in loss_weights:
if name not in self.output_names:
raise ValueError('Unknown entry in loss_weights '
'dictionary: "' + name + '". '
'Only expected the following keys: ' +
str(self.output_names))
loss_weights_list = []
for name in self.output_names:
loss_weights_list.append(loss_weights.get(name, 1.))
elif isinstance(loss_weights, list):
if len(loss_weights) != len(self.outputs):
raise ValueError('When passing a list as loss_weights, '
'it should have one entry per model outputs. '
'The model has ' + str(len(self.outputs)) +
' outputs, but you passed loss_weights=' +
str(loss_weights))
loss_weights_list = loss_weights
else:
raise TypeError('Could not interpret loss_weights argument: ' +
str(loss_weights) + ' - expected a list of dicts.')
# Prepare sample weights.
sample_weights = []
sample_weight_modes = []
if isinstance(sample_weight_mode, dict):
for name in sample_weight_mode:
if name not in self.output_names:
raise ValueError('Unknown entry in '
'sample_weight_mode dictionary: "' + name + '". '
'Only expected the following keys: ' +
str(self.output_names))
for i, name in enumerate(self.output_names):
if i in skip_indices:
weight = None
sample_weight_modes.append(None)
else:
if name not in sample_weight_mode:
raise ValueError('Output "' + name +
'" missing from sample_weight_modes '
'dictionary')
if sample_weight_mode.get(name) == 'temporal':
weight = K.placeholder(ndim=2, name=name + '_sample_weights')
sample_weight_modes.append('temporal')
else:
weight = K.placeholder(ndim=1, name=name + '_sample_weights')
sample_weight_modes.append(None)
sample_weights.append(weight)
elif isinstance(sample_weight_mode, list):
if len(sample_weight_mode) != len(self.outputs):
raise ValueError('When passing a list as sample_weight_mode, '
'it should have one entry per model outputs. '
'The model has ' + str(len(self.outputs)) +
' outputs, but you passed '
'sample_weight_mode=' + str(sample_weight_mode))
for i in range(len(self.output_names)):
if i in skip_indices:
weight = None
sample_weight_modes.append(None)
else:
mode = sample_weight_mode[i]
name = self.output_names[i]
if mode == 'temporal':
weight = K.placeholder(ndim=2, name=name + '_sample_weights')
sample_weight_modes.append('temporal')
else:
weight = K.placeholder(ndim=1, name=name + '_sample_weights')
sample_weight_modes.append(None)
sample_weights.append(weight)
else:
for i, name in enumerate(self.output_names):
if i in skip_indices:
sample_weight_modes.append(None)
sample_weights.append(None)
else:
if sample_weight_mode == 'temporal':
sample_weights.append(
K.placeholder(ndim=2, name=name + '_sample_weights'))
sample_weight_modes.append('temporal')
else:
sample_weights.append(
K.placeholder(ndim=1, name=name + '_sample_weights'))
sample_weight_modes.append(None)
self.sample_weight_modes = sample_weight_modes
self._feed_sample_weight_modes = []
for i in range(len(self.outputs)):
if i not in skip_indices:
self._feed_sample_weight_modes.append(self.sample_weight_modes[i])
# Prepare targets of model.
self.targets = []
self._feed_targets = []
for i in range(len(self.outputs)):
if i in skip_indices:
self.targets.append(None)
else:
shape = self.internal_output_shapes[i]
name = self.output_names[i]
target = K.placeholder(
ndim=len(shape),
name=name + '_target',
sparse=K.is_sparse(self.outputs[i]),
dtype=K.dtype(self.outputs[i]))
self.targets.append(target)
self._feed_targets.append(target)
# Prepare metrics.
self.metrics = metrics
self.metrics_names = ['loss']
self.metrics_tensors = []
# Compute total loss.
total_loss = None
for i in range(len(self.outputs)):
if i in skip_indices:
continue
y_true = self.targets[i]
y_pred = self.outputs[i]
weighted_loss = weighted_losses[i]
sample_weight = sample_weights[i]
mask = masks[i]
loss_weight = loss_weights_list[i]
output_loss = weighted_loss(y_true, y_pred, sample_weight, mask)
if len(self.outputs) > 1:
self.metrics_tensors.append(output_loss)
self.metrics_names.append(self.output_names[i] + '_loss')
if total_loss is None:
total_loss = loss_weight * output_loss
else:
total_loss += loss_weight * output_loss
if total_loss is None:
if not self.losses:
raise RuntimeError('The model cannot be compiled '
'because it has no loss to optimize.')
else:
total_loss = 0.
# Add regularization penalties
# and other layer-specific losses.
for loss_tensor in self.losses:
total_loss += loss_tensor
# List of same size as output_names.
# contains tuples (metrics for output, names of metrics).
nested_metrics = _collect_metrics(metrics, self.output_names)
def append_metric(layer_num, metric_name, metric_tensor):
"""Helper function used in loop below."""
if len(self.output_names) > 1:
metric_name = self.output_layers[layer_num].name + '_' + metric_name
self.metrics_names.append(metric_name)
self.metrics_tensors.append(metric_tensor)
for i in range(len(self.outputs)):
if i in skip_indices:
continue
y_true = self.targets[i]
y_pred = self.outputs[i]
output_metrics = nested_metrics[i]
for metric in output_metrics:
if metric == 'accuracy' or metric == 'acc':
# custom handling of accuracy
# (because of class mode duality)
output_shape = self.internal_output_shapes[i]
acc_fn = None
if (output_shape[-1] == 1 or
self.loss_functions[i] == losses.binary_crossentropy):
# case: binary accuracy
acc_fn = metrics_module.binary_accuracy
elif self.loss_functions[i] == losses.sparse_categorical_crossentropy:
# case: categorical accuracy with sparse targets
acc_fn = metrics_module.sparse_categorical_accuracy
else:
acc_fn = metrics_module.categorical_accuracy
masked_fn = _masked_objective(acc_fn)
append_metric(i, 'acc', masked_fn(y_true, y_pred, mask=masks[i]))
else:
metric_fn = metrics_module.get(metric)
masked_metric_fn = _masked_objective(metric_fn)
metric_result = masked_metric_fn(y_true, y_pred, mask=masks[i])
metric_result = {metric_fn.__name__: metric_result}
for name, tensor in six.iteritems(metric_result):
append_metric(i, name, tensor)
# Prepare gradient updates and state updates.
self.total_loss = total_loss
self.sample_weights = sample_weights
self._feed_sample_weights = []
for i in range(len(self.sample_weights)):
if i not in skip_indices:
self._feed_sample_weights.append(sample_weights[i])
# Functions for train, test and predict will
# be compiled lazily when required.
# This saves time when the user is not using all functions.
self._function_kwargs = kwargs
self.train_function = None
self.test_function = None
self.predict_function = None
# Collected trainable weights, sorted in topological order.
trainable_weights = self.trainable_weights
self._collected_trainable_weights = trainable_weights | [
"def",
"compile",
"(",
"self",
",",
"optimizer",
",",
"loss",
",",
"metrics",
"=",
"None",
",",
"loss_weights",
"=",
"None",
",",
"sample_weight_mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"loss",
"=",
"loss",
"or",
"{",
"}",
"self",
".",
"optimizer",
"=",
"optimizers",
".",
"get",
"(",
"optimizer",
")",
"self",
".",
"sample_weight_mode",
"=",
"sample_weight_mode",
"self",
".",
"loss",
"=",
"loss",
"self",
".",
"loss_weights",
"=",
"loss_weights",
"# Prepare loss functions.",
"if",
"isinstance",
"(",
"loss",
",",
"dict",
")",
":",
"for",
"name",
"in",
"loss",
":",
"if",
"name",
"not",
"in",
"self",
".",
"output_names",
":",
"raise",
"ValueError",
"(",
"'Unknown entry in loss '",
"'dictionary: \"'",
"+",
"name",
"+",
"'\". '",
"'Only expected the following keys: '",
"+",
"str",
"(",
"self",
".",
"output_names",
")",
")",
"loss_functions",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"output_names",
":",
"if",
"name",
"not",
"in",
"loss",
":",
"logging",
".",
"warning",
"(",
"'Output \"'",
"+",
"name",
"+",
"'\" missing from loss dictionary. '",
"'We assume this was done on purpose, '",
"'and we will not be expecting '",
"'any data to be passed to \"'",
"+",
"name",
"+",
"'\" during training.'",
",",
"stacklevel",
"=",
"2",
")",
"loss_functions",
".",
"append",
"(",
"losses",
".",
"get",
"(",
"loss",
".",
"get",
"(",
"name",
")",
")",
")",
"elif",
"isinstance",
"(",
"loss",
",",
"list",
")",
":",
"if",
"len",
"(",
"loss",
")",
"!=",
"len",
"(",
"self",
".",
"outputs",
")",
":",
"raise",
"ValueError",
"(",
"'When passing a list as loss, '",
"'it should have one entry per model outputs. '",
"'The model has '",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
"+",
"' outputs, but you passed loss='",
"+",
"str",
"(",
"loss",
")",
")",
"loss_functions",
"=",
"[",
"losses",
".",
"get",
"(",
"l",
")",
"for",
"l",
"in",
"loss",
"]",
"else",
":",
"loss_function",
"=",
"losses",
".",
"get",
"(",
"loss",
")",
"loss_functions",
"=",
"[",
"loss_function",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
"]",
"self",
".",
"loss_functions",
"=",
"loss_functions",
"weighted_losses",
"=",
"[",
"_weighted_masked_objective",
"(",
"fn",
")",
"for",
"fn",
"in",
"loss_functions",
"]",
"skip_indices",
"=",
"[",
"]",
"self",
".",
"_feed_outputs",
"=",
"[",
"]",
"self",
".",
"_feed_output_names",
"=",
"[",
"]",
"self",
".",
"_feed_output_shapes",
"=",
"[",
"]",
"self",
".",
"_feed_loss_fns",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"weighted_losses",
")",
")",
":",
"if",
"weighted_losses",
"[",
"i",
"]",
"is",
"None",
":",
"skip_indices",
".",
"append",
"(",
"i",
")",
"else",
":",
"self",
".",
"_feed_outputs",
".",
"append",
"(",
"self",
".",
"outputs",
"[",
"i",
"]",
")",
"self",
".",
"_feed_output_names",
".",
"append",
"(",
"self",
".",
"output_names",
"[",
"i",
"]",
")",
"self",
".",
"_feed_output_shapes",
".",
"append",
"(",
"self",
".",
"internal_output_shapes",
"[",
"i",
"]",
")",
"self",
".",
"_feed_loss_fns",
".",
"append",
"(",
"self",
".",
"loss_functions",
"[",
"i",
"]",
")",
"# Prepare output masks.",
"masks",
"=",
"self",
".",
"compute_mask",
"(",
"self",
".",
"inputs",
",",
"mask",
"=",
"None",
")",
"if",
"masks",
"is",
"None",
":",
"masks",
"=",
"[",
"None",
"for",
"_",
"in",
"self",
".",
"outputs",
"]",
"if",
"not",
"isinstance",
"(",
"masks",
",",
"list",
")",
":",
"masks",
"=",
"[",
"masks",
"]",
"# Prepare loss weights.",
"if",
"loss_weights",
"is",
"None",
":",
"loss_weights_list",
"=",
"[",
"1.",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
"]",
"elif",
"isinstance",
"(",
"loss_weights",
",",
"dict",
")",
":",
"for",
"name",
"in",
"loss_weights",
":",
"if",
"name",
"not",
"in",
"self",
".",
"output_names",
":",
"raise",
"ValueError",
"(",
"'Unknown entry in loss_weights '",
"'dictionary: \"'",
"+",
"name",
"+",
"'\". '",
"'Only expected the following keys: '",
"+",
"str",
"(",
"self",
".",
"output_names",
")",
")",
"loss_weights_list",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"output_names",
":",
"loss_weights_list",
".",
"append",
"(",
"loss_weights",
".",
"get",
"(",
"name",
",",
"1.",
")",
")",
"elif",
"isinstance",
"(",
"loss_weights",
",",
"list",
")",
":",
"if",
"len",
"(",
"loss_weights",
")",
"!=",
"len",
"(",
"self",
".",
"outputs",
")",
":",
"raise",
"ValueError",
"(",
"'When passing a list as loss_weights, '",
"'it should have one entry per model outputs. '",
"'The model has '",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
"+",
"' outputs, but you passed loss_weights='",
"+",
"str",
"(",
"loss_weights",
")",
")",
"loss_weights_list",
"=",
"loss_weights",
"else",
":",
"raise",
"TypeError",
"(",
"'Could not interpret loss_weights argument: '",
"+",
"str",
"(",
"loss_weights",
")",
"+",
"' - expected a list of dicts.'",
")",
"# Prepare sample weights.",
"sample_weights",
"=",
"[",
"]",
"sample_weight_modes",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"sample_weight_mode",
",",
"dict",
")",
":",
"for",
"name",
"in",
"sample_weight_mode",
":",
"if",
"name",
"not",
"in",
"self",
".",
"output_names",
":",
"raise",
"ValueError",
"(",
"'Unknown entry in '",
"'sample_weight_mode dictionary: \"'",
"+",
"name",
"+",
"'\". '",
"'Only expected the following keys: '",
"+",
"str",
"(",
"self",
".",
"output_names",
")",
")",
"for",
"i",
",",
"name",
"in",
"enumerate",
"(",
"self",
".",
"output_names",
")",
":",
"if",
"i",
"in",
"skip_indices",
":",
"weight",
"=",
"None",
"sample_weight_modes",
".",
"append",
"(",
"None",
")",
"else",
":",
"if",
"name",
"not",
"in",
"sample_weight_mode",
":",
"raise",
"ValueError",
"(",
"'Output \"'",
"+",
"name",
"+",
"'\" missing from sample_weight_modes '",
"'dictionary'",
")",
"if",
"sample_weight_mode",
".",
"get",
"(",
"name",
")",
"==",
"'temporal'",
":",
"weight",
"=",
"K",
".",
"placeholder",
"(",
"ndim",
"=",
"2",
",",
"name",
"=",
"name",
"+",
"'_sample_weights'",
")",
"sample_weight_modes",
".",
"append",
"(",
"'temporal'",
")",
"else",
":",
"weight",
"=",
"K",
".",
"placeholder",
"(",
"ndim",
"=",
"1",
",",
"name",
"=",
"name",
"+",
"'_sample_weights'",
")",
"sample_weight_modes",
".",
"append",
"(",
"None",
")",
"sample_weights",
".",
"append",
"(",
"weight",
")",
"elif",
"isinstance",
"(",
"sample_weight_mode",
",",
"list",
")",
":",
"if",
"len",
"(",
"sample_weight_mode",
")",
"!=",
"len",
"(",
"self",
".",
"outputs",
")",
":",
"raise",
"ValueError",
"(",
"'When passing a list as sample_weight_mode, '",
"'it should have one entry per model outputs. '",
"'The model has '",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
"+",
"' outputs, but you passed '",
"'sample_weight_mode='",
"+",
"str",
"(",
"sample_weight_mode",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"output_names",
")",
")",
":",
"if",
"i",
"in",
"skip_indices",
":",
"weight",
"=",
"None",
"sample_weight_modes",
".",
"append",
"(",
"None",
")",
"else",
":",
"mode",
"=",
"sample_weight_mode",
"[",
"i",
"]",
"name",
"=",
"self",
".",
"output_names",
"[",
"i",
"]",
"if",
"mode",
"==",
"'temporal'",
":",
"weight",
"=",
"K",
".",
"placeholder",
"(",
"ndim",
"=",
"2",
",",
"name",
"=",
"name",
"+",
"'_sample_weights'",
")",
"sample_weight_modes",
".",
"append",
"(",
"'temporal'",
")",
"else",
":",
"weight",
"=",
"K",
".",
"placeholder",
"(",
"ndim",
"=",
"1",
",",
"name",
"=",
"name",
"+",
"'_sample_weights'",
")",
"sample_weight_modes",
".",
"append",
"(",
"None",
")",
"sample_weights",
".",
"append",
"(",
"weight",
")",
"else",
":",
"for",
"i",
",",
"name",
"in",
"enumerate",
"(",
"self",
".",
"output_names",
")",
":",
"if",
"i",
"in",
"skip_indices",
":",
"sample_weight_modes",
".",
"append",
"(",
"None",
")",
"sample_weights",
".",
"append",
"(",
"None",
")",
"else",
":",
"if",
"sample_weight_mode",
"==",
"'temporal'",
":",
"sample_weights",
".",
"append",
"(",
"K",
".",
"placeholder",
"(",
"ndim",
"=",
"2",
",",
"name",
"=",
"name",
"+",
"'_sample_weights'",
")",
")",
"sample_weight_modes",
".",
"append",
"(",
"'temporal'",
")",
"else",
":",
"sample_weights",
".",
"append",
"(",
"K",
".",
"placeholder",
"(",
"ndim",
"=",
"1",
",",
"name",
"=",
"name",
"+",
"'_sample_weights'",
")",
")",
"sample_weight_modes",
".",
"append",
"(",
"None",
")",
"self",
".",
"sample_weight_modes",
"=",
"sample_weight_modes",
"self",
".",
"_feed_sample_weight_modes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
":",
"if",
"i",
"not",
"in",
"skip_indices",
":",
"self",
".",
"_feed_sample_weight_modes",
".",
"append",
"(",
"self",
".",
"sample_weight_modes",
"[",
"i",
"]",
")",
"# Prepare targets of model.",
"self",
".",
"targets",
"=",
"[",
"]",
"self",
".",
"_feed_targets",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
":",
"if",
"i",
"in",
"skip_indices",
":",
"self",
".",
"targets",
".",
"append",
"(",
"None",
")",
"else",
":",
"shape",
"=",
"self",
".",
"internal_output_shapes",
"[",
"i",
"]",
"name",
"=",
"self",
".",
"output_names",
"[",
"i",
"]",
"target",
"=",
"K",
".",
"placeholder",
"(",
"ndim",
"=",
"len",
"(",
"shape",
")",
",",
"name",
"=",
"name",
"+",
"'_target'",
",",
"sparse",
"=",
"K",
".",
"is_sparse",
"(",
"self",
".",
"outputs",
"[",
"i",
"]",
")",
",",
"dtype",
"=",
"K",
".",
"dtype",
"(",
"self",
".",
"outputs",
"[",
"i",
"]",
")",
")",
"self",
".",
"targets",
".",
"append",
"(",
"target",
")",
"self",
".",
"_feed_targets",
".",
"append",
"(",
"target",
")",
"# Prepare metrics.",
"self",
".",
"metrics",
"=",
"metrics",
"self",
".",
"metrics_names",
"=",
"[",
"'loss'",
"]",
"self",
".",
"metrics_tensors",
"=",
"[",
"]",
"# Compute total loss.",
"total_loss",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
":",
"if",
"i",
"in",
"skip_indices",
":",
"continue",
"y_true",
"=",
"self",
".",
"targets",
"[",
"i",
"]",
"y_pred",
"=",
"self",
".",
"outputs",
"[",
"i",
"]",
"weighted_loss",
"=",
"weighted_losses",
"[",
"i",
"]",
"sample_weight",
"=",
"sample_weights",
"[",
"i",
"]",
"mask",
"=",
"masks",
"[",
"i",
"]",
"loss_weight",
"=",
"loss_weights_list",
"[",
"i",
"]",
"output_loss",
"=",
"weighted_loss",
"(",
"y_true",
",",
"y_pred",
",",
"sample_weight",
",",
"mask",
")",
"if",
"len",
"(",
"self",
".",
"outputs",
")",
">",
"1",
":",
"self",
".",
"metrics_tensors",
".",
"append",
"(",
"output_loss",
")",
"self",
".",
"metrics_names",
".",
"append",
"(",
"self",
".",
"output_names",
"[",
"i",
"]",
"+",
"'_loss'",
")",
"if",
"total_loss",
"is",
"None",
":",
"total_loss",
"=",
"loss_weight",
"*",
"output_loss",
"else",
":",
"total_loss",
"+=",
"loss_weight",
"*",
"output_loss",
"if",
"total_loss",
"is",
"None",
":",
"if",
"not",
"self",
".",
"losses",
":",
"raise",
"RuntimeError",
"(",
"'The model cannot be compiled '",
"'because it has no loss to optimize.'",
")",
"else",
":",
"total_loss",
"=",
"0.",
"# Add regularization penalties",
"# and other layer-specific losses.",
"for",
"loss_tensor",
"in",
"self",
".",
"losses",
":",
"total_loss",
"+=",
"loss_tensor",
"# List of same size as output_names.",
"# contains tuples (metrics for output, names of metrics).",
"nested_metrics",
"=",
"_collect_metrics",
"(",
"metrics",
",",
"self",
".",
"output_names",
")",
"def",
"append_metric",
"(",
"layer_num",
",",
"metric_name",
",",
"metric_tensor",
")",
":",
"\"\"\"Helper function used in loop below.\"\"\"",
"if",
"len",
"(",
"self",
".",
"output_names",
")",
">",
"1",
":",
"metric_name",
"=",
"self",
".",
"output_layers",
"[",
"layer_num",
"]",
".",
"name",
"+",
"'_'",
"+",
"metric_name",
"self",
".",
"metrics_names",
".",
"append",
"(",
"metric_name",
")",
"self",
".",
"metrics_tensors",
".",
"append",
"(",
"metric_tensor",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"outputs",
")",
")",
":",
"if",
"i",
"in",
"skip_indices",
":",
"continue",
"y_true",
"=",
"self",
".",
"targets",
"[",
"i",
"]",
"y_pred",
"=",
"self",
".",
"outputs",
"[",
"i",
"]",
"output_metrics",
"=",
"nested_metrics",
"[",
"i",
"]",
"for",
"metric",
"in",
"output_metrics",
":",
"if",
"metric",
"==",
"'accuracy'",
"or",
"metric",
"==",
"'acc'",
":",
"# custom handling of accuracy",
"# (because of class mode duality)",
"output_shape",
"=",
"self",
".",
"internal_output_shapes",
"[",
"i",
"]",
"acc_fn",
"=",
"None",
"if",
"(",
"output_shape",
"[",
"-",
"1",
"]",
"==",
"1",
"or",
"self",
".",
"loss_functions",
"[",
"i",
"]",
"==",
"losses",
".",
"binary_crossentropy",
")",
":",
"# case: binary accuracy",
"acc_fn",
"=",
"metrics_module",
".",
"binary_accuracy",
"elif",
"self",
".",
"loss_functions",
"[",
"i",
"]",
"==",
"losses",
".",
"sparse_categorical_crossentropy",
":",
"# case: categorical accuracy with sparse targets",
"acc_fn",
"=",
"metrics_module",
".",
"sparse_categorical_accuracy",
"else",
":",
"acc_fn",
"=",
"metrics_module",
".",
"categorical_accuracy",
"masked_fn",
"=",
"_masked_objective",
"(",
"acc_fn",
")",
"append_metric",
"(",
"i",
",",
"'acc'",
",",
"masked_fn",
"(",
"y_true",
",",
"y_pred",
",",
"mask",
"=",
"masks",
"[",
"i",
"]",
")",
")",
"else",
":",
"metric_fn",
"=",
"metrics_module",
".",
"get",
"(",
"metric",
")",
"masked_metric_fn",
"=",
"_masked_objective",
"(",
"metric_fn",
")",
"metric_result",
"=",
"masked_metric_fn",
"(",
"y_true",
",",
"y_pred",
",",
"mask",
"=",
"masks",
"[",
"i",
"]",
")",
"metric_result",
"=",
"{",
"metric_fn",
".",
"__name__",
":",
"metric_result",
"}",
"for",
"name",
",",
"tensor",
"in",
"six",
".",
"iteritems",
"(",
"metric_result",
")",
":",
"append_metric",
"(",
"i",
",",
"name",
",",
"tensor",
")",
"# Prepare gradient updates and state updates.",
"self",
".",
"total_loss",
"=",
"total_loss",
"self",
".",
"sample_weights",
"=",
"sample_weights",
"self",
".",
"_feed_sample_weights",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"sample_weights",
")",
")",
":",
"if",
"i",
"not",
"in",
"skip_indices",
":",
"self",
".",
"_feed_sample_weights",
".",
"append",
"(",
"sample_weights",
"[",
"i",
"]",
")",
"# Functions for train, test and predict will",
"# be compiled lazily when required.",
"# This saves time when the user is not using all functions.",
"self",
".",
"_function_kwargs",
"=",
"kwargs",
"self",
".",
"train_function",
"=",
"None",
"self",
".",
"test_function",
"=",
"None",
"self",
".",
"predict_function",
"=",
"None",
"# Collected trainable weights, sorted in topological order.",
"trainable_weights",
"=",
"self",
".",
"trainable_weights",
"self",
".",
"_collected_trainable_weights",
"=",
"trainable_weights"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/engine/training.py#L604-L914 | ||
Manu343726/siplasplas | 9fae7559f87087cf8ef34f04bd1e774b84b2ea9c | reference/cindex.py | python | Type.translation_unit | (self) | return self._tu | The TranslationUnit to which this Type is associated. | The TranslationUnit to which this Type is associated. | [
"The",
"TranslationUnit",
"to",
"which",
"this",
"Type",
"is",
"associated",
"."
] | def translation_unit(self):
"""The TranslationUnit to which this Type is associated."""
# If this triggers an AttributeError, the instance was not properly
# instantiated.
return self._tu | [
"def",
"translation_unit",
"(",
"self",
")",
":",
"# If this triggers an AttributeError, the instance was not properly",
"# instantiated.",
"return",
"self",
".",
"_tu"
] | https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1828-L1832 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/device_utils.py | python | _ParseModeString | (mode_str) | return mode | Parse a mode string, e.g. 'drwxrwxrwx', into a st_mode value.
Effectively the reverse of |mode_to_string| in, e.g.:
https://github.com/landley/toybox/blob/master/lib/lib.c#L896 | Parse a mode string, e.g. 'drwxrwxrwx', into a st_mode value. | [
"Parse",
"a",
"mode",
"string",
"e",
".",
"g",
".",
"drwxrwxrwx",
"into",
"a",
"st_mode",
"value",
"."
] | def _ParseModeString(mode_str):
"""Parse a mode string, e.g. 'drwxrwxrwx', into a st_mode value.
Effectively the reverse of |mode_to_string| in, e.g.:
https://github.com/landley/toybox/blob/master/lib/lib.c#L896
"""
if not _FILE_MODE_RE.match(mode_str):
raise ValueError('Unexpected file mode %r', mode_str)
mode = _FILE_MODE_KIND[mode_str[0]]
for c, flag in zip(mode_str[1:], _FILE_MODE_PERMS):
if c != '-' and c.islower():
mode |= flag
for c, (t, flag) in zip(mode_str[3::3], _FILE_MODE_SPECIAL):
if c.lower() == t:
mode |= flag
return mode | [
"def",
"_ParseModeString",
"(",
"mode_str",
")",
":",
"if",
"not",
"_FILE_MODE_RE",
".",
"match",
"(",
"mode_str",
")",
":",
"raise",
"ValueError",
"(",
"'Unexpected file mode %r'",
",",
"mode_str",
")",
"mode",
"=",
"_FILE_MODE_KIND",
"[",
"mode_str",
"[",
"0",
"]",
"]",
"for",
"c",
",",
"flag",
"in",
"zip",
"(",
"mode_str",
"[",
"1",
":",
"]",
",",
"_FILE_MODE_PERMS",
")",
":",
"if",
"c",
"!=",
"'-'",
"and",
"c",
".",
"islower",
"(",
")",
":",
"mode",
"|=",
"flag",
"for",
"c",
",",
"(",
"t",
",",
"flag",
")",
"in",
"zip",
"(",
"mode_str",
"[",
"3",
":",
":",
"3",
"]",
",",
"_FILE_MODE_SPECIAL",
")",
":",
"if",
"c",
".",
"lower",
"(",
")",
"==",
"t",
":",
"mode",
"|=",
"flag",
"return",
"mode"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/device_utils.py#L193-L208 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/converters/onnx/_operators_nd.py | python | _convert_gru | (
builder, node, graph, err
) | convert to CoreML GRU Layer:
https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L3104 | convert to CoreML GRU Layer:
https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L3104 | [
"convert",
"to",
"CoreML",
"GRU",
"Layer",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"apple",
"/",
"coremltools",
"/",
"blob",
"/",
"655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492",
"/",
"mlmodel",
"/",
"format",
"/",
"NeuralNetwork",
".",
"proto#L3104"
] | def _convert_gru(
builder, node, graph, err
): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None
"""
convert to CoreML GRU Layer:
https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L3104
"""
def get_weights(W, W_name, R, R_name, B):
"""
Helper routine to return weights in CoreML LSTM required format
"""
W = np.expand_dims(np.expand_dims(W, 3), 3)
R = np.expand_dims(np.expand_dims(R, 3), 3)
if W is None:
err.missing_initializer(
node,
"Weight tensor: {} not found in the graph initializer".format(W_name),
)
if R is None:
err.missing_initializer(
node,
"Weight tensor: {} not found in the graph initializer".format(R_name),
)
W_z, W_r, W_h = np.split(np.squeeze(W), 3) # type: ignore
R_z, R_r, R_h = np.split(np.squeeze(R), 3) # type: ignore
W_x = [W_z, W_r, W_h]
W_h = [R_z, R_r, R_h]
b = None
if B is not None:
b_Wz, b_Wr, b_Wh, b_Rz, b_Rr, b_Rh = np.split(np.squeeze(B), 6) # type: ignore
b = [b_Wz + b_Rz, b_Wr + b_Rr, b_Wh + b_Rh]
return W_x, W_h, b
def expand_dim(node_name, input_name, output_name, axes):
builder.add_expand_dims(
name=node_name, input_name=input_name, output_name=output_name, axes=axes
)
# Read attributes
# activation alpha and beta
if "activation_alpha" in node.attrs or "activation_beta" in node.attrs:
err.unsupported_feature_warning(
node, "Activation parameter alpha and beta are currently not used"
)
inner_activation = "SIGMOID"
output_activation = "TANH"
if "activations" in node.attrs:
activations_list = node.attrs["activations"]
if len(activations_list) < 2:
err.unsupported_op_configuration(
builder,
node,
graph,
"Error in ONNX model: Less number of activations provided",
)
inner_activation = activations_list[0].upper()
output_activation = activations_list[1].upper()
# Extract direction from ONNX attribute
direction = node.attrs.get("direction", "forward")
if direction == "bidirectional":
return err.unsupported_op_configuration(
builder,
node,
graph,
"Bidirectional GRU not supported!! Please consider adding custom conversion function/layer",
)
hidden_size = node.attrs.get("hidden_size")
# Read inputs
W_name = node.inputs[1]
R_name = node.inputs[2]
B = None
if len(node.inputs) > 3:
B_name = node.inputs[3]
B = node.input_tensors.get(B_name, None)
if W_name not in node.input_tensors or R_name not in node.input_tensors:
return err.unsupported_op_configuration(
builder,
node,
graph,
"Input and Recursion weights must be known!! Please consider adding custom conversion function/layer",
)
W = node.input_tensors.get(W_name, None)
R = node.input_tensors.get(R_name, None)
# Get weights for forward direction
W_x, W_h, b = get_weights(W, W_name, R, R_name, B)
# shape of input
input_size = W_x[0].shape[1]
# Get input and output for hidden and cell
input_h = node.inputs[5] if len(node.inputs) > 5 else node.inputs[0] + "_h_input"
output_h = (
node.outputs[1] if len(node.outputs) > 1 else node.outputs[0] + "_h_output"
)
output_h_5d = output_h + "_5d"
if len(node.inputs) < 6:
# if input is not present in the network, load they as constant
if node.inputs[0] not in graph.shape_dict:
err.unsupported_op_configuration(
builder, node, graph, "Input shape not represented within Graph"
)
# Input is represented as [Seq Len, Batch Size, Input Size]
batch_size = graph.shape_dict[node.inputs[0]][1]
builder.add_load_constant_nd(
name=node.name + "_load_initial_h",
output_name=input_h,
constant_value=0.0,
shape=[1, batch_size, hidden_size],
)
# CoreML GRU expects 5-d tensor
# Expand dimensions of input to 5-d for compatibility
input_rank = builder._get_rank(node.inputs[0])
if input_rank == -1:
return err.unsupported_op_configuration(
builder, node, graph, "Rank unknown for input"
)
if input_rank < 5:
add_nodes = 5 - input_rank
# TODO: Add one expand instead of adding one after another for input, h
expand_dim(
node.name + "_expand_in_0",
node.inputs[0],
node.inputs[0] + "_expand_out_0",
[input_rank],
)
expand_dim(
node.name + "_expand_in_h_0",
input_h,
input_h + "_expand_out_h_0",
[input_rank],
)
for i in range(1, add_nodes):
i_str = str(i)
i_p_str = str(i - 1)
expand_dim(
node.name + "_expand_in_" + i_str,
node.inputs[0] + "_expand_out_" + i_p_str,
node.inputs[0] + "_expand_out_" + i_str,
[input_rank + i],
)
expand_dim(
node.name + "_expand_in_h_" + i_str,
input_h + "_expand_out_h_" + i_p_str,
input_h + "_expand_out_h_" + i_str,
[input_rank + i],
)
builder.add_gru(
name=node.name,
W_h=W_h,
W_x=W_x,
b=b,
hidden_size=hidden_size,
input_size=input_size,
input_names=[
node.inputs[0] + "_expand_out_" + str(add_nodes - 1),
input_h + "_expand_out_h_" + str(add_nodes - 1),
],
output_names=[node.outputs[0] + "_5d_out", output_h_5d],
inner_activation=inner_activation,
activation=output_activation,
output_all=True,
reverse_input=(direction == "reverse"),
)
# CoreML output is [Seq Len, Batch Size, Num Dir * Hidden Size, 1, 1]
# Return output as [Seq Len, Num Dir, Batch Size, Hidden Size]
# Following steps:
# a. Reshape and split hidden size for direction [Seq Len, Batch Size, Num Dir, Hidden Size, 1]
# b. Squeeze last dimension [Seq Len, Batch Size, Num Dir, Hidden Size]
# c. Permute to fix the order [Seq Len, Num Dir, Batch Size, Hidden Size, 1]
builder.add_rank_preserving_reshape(
name=node.name + "_reshape_",
input_name=node.outputs[0] + "_5d_out",
output_name=node.outputs[0] + "_5d_reshaped",
output_shape=[0, 0, 1, -1, 0],
)
builder.add_squeeze(
name=node.name + "_squeeze_out",
input_name=node.outputs[0] + "_5d_reshaped",
output_name=node.outputs[0] + "_4d",
axes=[-1],
)
builder.add_transpose(
name=node.name + "_transpose",
axes=[0, 2, 1, 3],
input_name=node.outputs[0] + "_4d",
output_name=node.outputs[0],
)
# Squeeze dimensions of output_h
builder.add_squeeze(
name=node.name + "_squeeze_out_h",
input_name=output_h_5d,
output_name=output_h,
axes=[-1, -2],
) | [
"def",
"_convert_gru",
"(",
"builder",
",",
"node",
",",
"graph",
",",
"err",
")",
":",
"# type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None",
"def",
"get_weights",
"(",
"W",
",",
"W_name",
",",
"R",
",",
"R_name",
",",
"B",
")",
":",
"\"\"\"\n Helper routine to return weights in CoreML LSTM required format\n \"\"\"",
"W",
"=",
"np",
".",
"expand_dims",
"(",
"np",
".",
"expand_dims",
"(",
"W",
",",
"3",
")",
",",
"3",
")",
"R",
"=",
"np",
".",
"expand_dims",
"(",
"np",
".",
"expand_dims",
"(",
"R",
",",
"3",
")",
",",
"3",
")",
"if",
"W",
"is",
"None",
":",
"err",
".",
"missing_initializer",
"(",
"node",
",",
"\"Weight tensor: {} not found in the graph initializer\"",
".",
"format",
"(",
"W_name",
")",
",",
")",
"if",
"R",
"is",
"None",
":",
"err",
".",
"missing_initializer",
"(",
"node",
",",
"\"Weight tensor: {} not found in the graph initializer\"",
".",
"format",
"(",
"R_name",
")",
",",
")",
"W_z",
",",
"W_r",
",",
"W_h",
"=",
"np",
".",
"split",
"(",
"np",
".",
"squeeze",
"(",
"W",
")",
",",
"3",
")",
"# type: ignore",
"R_z",
",",
"R_r",
",",
"R_h",
"=",
"np",
".",
"split",
"(",
"np",
".",
"squeeze",
"(",
"R",
")",
",",
"3",
")",
"# type: ignore",
"W_x",
"=",
"[",
"W_z",
",",
"W_r",
",",
"W_h",
"]",
"W_h",
"=",
"[",
"R_z",
",",
"R_r",
",",
"R_h",
"]",
"b",
"=",
"None",
"if",
"B",
"is",
"not",
"None",
":",
"b_Wz",
",",
"b_Wr",
",",
"b_Wh",
",",
"b_Rz",
",",
"b_Rr",
",",
"b_Rh",
"=",
"np",
".",
"split",
"(",
"np",
".",
"squeeze",
"(",
"B",
")",
",",
"6",
")",
"# type: ignore",
"b",
"=",
"[",
"b_Wz",
"+",
"b_Rz",
",",
"b_Wr",
"+",
"b_Rr",
",",
"b_Wh",
"+",
"b_Rh",
"]",
"return",
"W_x",
",",
"W_h",
",",
"b",
"def",
"expand_dim",
"(",
"node_name",
",",
"input_name",
",",
"output_name",
",",
"axes",
")",
":",
"builder",
".",
"add_expand_dims",
"(",
"name",
"=",
"node_name",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
",",
"axes",
"=",
"axes",
")",
"# Read attributes",
"# activation alpha and beta",
"if",
"\"activation_alpha\"",
"in",
"node",
".",
"attrs",
"or",
"\"activation_beta\"",
"in",
"node",
".",
"attrs",
":",
"err",
".",
"unsupported_feature_warning",
"(",
"node",
",",
"\"Activation parameter alpha and beta are currently not used\"",
")",
"inner_activation",
"=",
"\"SIGMOID\"",
"output_activation",
"=",
"\"TANH\"",
"if",
"\"activations\"",
"in",
"node",
".",
"attrs",
":",
"activations_list",
"=",
"node",
".",
"attrs",
"[",
"\"activations\"",
"]",
"if",
"len",
"(",
"activations_list",
")",
"<",
"2",
":",
"err",
".",
"unsupported_op_configuration",
"(",
"builder",
",",
"node",
",",
"graph",
",",
"\"Error in ONNX model: Less number of activations provided\"",
",",
")",
"inner_activation",
"=",
"activations_list",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"output_activation",
"=",
"activations_list",
"[",
"1",
"]",
".",
"upper",
"(",
")",
"# Extract direction from ONNX attribute",
"direction",
"=",
"node",
".",
"attrs",
".",
"get",
"(",
"\"direction\"",
",",
"\"forward\"",
")",
"if",
"direction",
"==",
"\"bidirectional\"",
":",
"return",
"err",
".",
"unsupported_op_configuration",
"(",
"builder",
",",
"node",
",",
"graph",
",",
"\"Bidirectional GRU not supported!! Please consider adding custom conversion function/layer\"",
",",
")",
"hidden_size",
"=",
"node",
".",
"attrs",
".",
"get",
"(",
"\"hidden_size\"",
")",
"# Read inputs",
"W_name",
"=",
"node",
".",
"inputs",
"[",
"1",
"]",
"R_name",
"=",
"node",
".",
"inputs",
"[",
"2",
"]",
"B",
"=",
"None",
"if",
"len",
"(",
"node",
".",
"inputs",
")",
">",
"3",
":",
"B_name",
"=",
"node",
".",
"inputs",
"[",
"3",
"]",
"B",
"=",
"node",
".",
"input_tensors",
".",
"get",
"(",
"B_name",
",",
"None",
")",
"if",
"W_name",
"not",
"in",
"node",
".",
"input_tensors",
"or",
"R_name",
"not",
"in",
"node",
".",
"input_tensors",
":",
"return",
"err",
".",
"unsupported_op_configuration",
"(",
"builder",
",",
"node",
",",
"graph",
",",
"\"Input and Recursion weights must be known!! Please consider adding custom conversion function/layer\"",
",",
")",
"W",
"=",
"node",
".",
"input_tensors",
".",
"get",
"(",
"W_name",
",",
"None",
")",
"R",
"=",
"node",
".",
"input_tensors",
".",
"get",
"(",
"R_name",
",",
"None",
")",
"# Get weights for forward direction",
"W_x",
",",
"W_h",
",",
"b",
"=",
"get_weights",
"(",
"W",
",",
"W_name",
",",
"R",
",",
"R_name",
",",
"B",
")",
"# shape of input",
"input_size",
"=",
"W_x",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
"# Get input and output for hidden and cell",
"input_h",
"=",
"node",
".",
"inputs",
"[",
"5",
"]",
"if",
"len",
"(",
"node",
".",
"inputs",
")",
">",
"5",
"else",
"node",
".",
"inputs",
"[",
"0",
"]",
"+",
"\"_h_input\"",
"output_h",
"=",
"(",
"node",
".",
"outputs",
"[",
"1",
"]",
"if",
"len",
"(",
"node",
".",
"outputs",
")",
">",
"1",
"else",
"node",
".",
"outputs",
"[",
"0",
"]",
"+",
"\"_h_output\"",
")",
"output_h_5d",
"=",
"output_h",
"+",
"\"_5d\"",
"if",
"len",
"(",
"node",
".",
"inputs",
")",
"<",
"6",
":",
"# if input is not present in the network, load they as constant",
"if",
"node",
".",
"inputs",
"[",
"0",
"]",
"not",
"in",
"graph",
".",
"shape_dict",
":",
"err",
".",
"unsupported_op_configuration",
"(",
"builder",
",",
"node",
",",
"graph",
",",
"\"Input shape not represented within Graph\"",
")",
"# Input is represented as [Seq Len, Batch Size, Input Size]",
"batch_size",
"=",
"graph",
".",
"shape_dict",
"[",
"node",
".",
"inputs",
"[",
"0",
"]",
"]",
"[",
"1",
"]",
"builder",
".",
"add_load_constant_nd",
"(",
"name",
"=",
"node",
".",
"name",
"+",
"\"_load_initial_h\"",
",",
"output_name",
"=",
"input_h",
",",
"constant_value",
"=",
"0.0",
",",
"shape",
"=",
"[",
"1",
",",
"batch_size",
",",
"hidden_size",
"]",
",",
")",
"# CoreML GRU expects 5-d tensor",
"# Expand dimensions of input to 5-d for compatibility",
"input_rank",
"=",
"builder",
".",
"_get_rank",
"(",
"node",
".",
"inputs",
"[",
"0",
"]",
")",
"if",
"input_rank",
"==",
"-",
"1",
":",
"return",
"err",
".",
"unsupported_op_configuration",
"(",
"builder",
",",
"node",
",",
"graph",
",",
"\"Rank unknown for input\"",
")",
"if",
"input_rank",
"<",
"5",
":",
"add_nodes",
"=",
"5",
"-",
"input_rank",
"# TODO: Add one expand instead of adding one after another for input, h",
"expand_dim",
"(",
"node",
".",
"name",
"+",
"\"_expand_in_0\"",
",",
"node",
".",
"inputs",
"[",
"0",
"]",
",",
"node",
".",
"inputs",
"[",
"0",
"]",
"+",
"\"_expand_out_0\"",
",",
"[",
"input_rank",
"]",
",",
")",
"expand_dim",
"(",
"node",
".",
"name",
"+",
"\"_expand_in_h_0\"",
",",
"input_h",
",",
"input_h",
"+",
"\"_expand_out_h_0\"",
",",
"[",
"input_rank",
"]",
",",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"add_nodes",
")",
":",
"i_str",
"=",
"str",
"(",
"i",
")",
"i_p_str",
"=",
"str",
"(",
"i",
"-",
"1",
")",
"expand_dim",
"(",
"node",
".",
"name",
"+",
"\"_expand_in_\"",
"+",
"i_str",
",",
"node",
".",
"inputs",
"[",
"0",
"]",
"+",
"\"_expand_out_\"",
"+",
"i_p_str",
",",
"node",
".",
"inputs",
"[",
"0",
"]",
"+",
"\"_expand_out_\"",
"+",
"i_str",
",",
"[",
"input_rank",
"+",
"i",
"]",
",",
")",
"expand_dim",
"(",
"node",
".",
"name",
"+",
"\"_expand_in_h_\"",
"+",
"i_str",
",",
"input_h",
"+",
"\"_expand_out_h_\"",
"+",
"i_p_str",
",",
"input_h",
"+",
"\"_expand_out_h_\"",
"+",
"i_str",
",",
"[",
"input_rank",
"+",
"i",
"]",
",",
")",
"builder",
".",
"add_gru",
"(",
"name",
"=",
"node",
".",
"name",
",",
"W_h",
"=",
"W_h",
",",
"W_x",
"=",
"W_x",
",",
"b",
"=",
"b",
",",
"hidden_size",
"=",
"hidden_size",
",",
"input_size",
"=",
"input_size",
",",
"input_names",
"=",
"[",
"node",
".",
"inputs",
"[",
"0",
"]",
"+",
"\"_expand_out_\"",
"+",
"str",
"(",
"add_nodes",
"-",
"1",
")",
",",
"input_h",
"+",
"\"_expand_out_h_\"",
"+",
"str",
"(",
"add_nodes",
"-",
"1",
")",
",",
"]",
",",
"output_names",
"=",
"[",
"node",
".",
"outputs",
"[",
"0",
"]",
"+",
"\"_5d_out\"",
",",
"output_h_5d",
"]",
",",
"inner_activation",
"=",
"inner_activation",
",",
"activation",
"=",
"output_activation",
",",
"output_all",
"=",
"True",
",",
"reverse_input",
"=",
"(",
"direction",
"==",
"\"reverse\"",
")",
",",
")",
"# CoreML output is [Seq Len, Batch Size, Num Dir * Hidden Size, 1, 1]",
"# Return output as [Seq Len, Num Dir, Batch Size, Hidden Size]",
"# Following steps:",
"# a. Reshape and split hidden size for direction [Seq Len, Batch Size, Num Dir, Hidden Size, 1]",
"# b. Squeeze last dimension [Seq Len, Batch Size, Num Dir, Hidden Size]",
"# c. Permute to fix the order [Seq Len, Num Dir, Batch Size, Hidden Size, 1]",
"builder",
".",
"add_rank_preserving_reshape",
"(",
"name",
"=",
"node",
".",
"name",
"+",
"\"_reshape_\"",
",",
"input_name",
"=",
"node",
".",
"outputs",
"[",
"0",
"]",
"+",
"\"_5d_out\"",
",",
"output_name",
"=",
"node",
".",
"outputs",
"[",
"0",
"]",
"+",
"\"_5d_reshaped\"",
",",
"output_shape",
"=",
"[",
"0",
",",
"0",
",",
"1",
",",
"-",
"1",
",",
"0",
"]",
",",
")",
"builder",
".",
"add_squeeze",
"(",
"name",
"=",
"node",
".",
"name",
"+",
"\"_squeeze_out\"",
",",
"input_name",
"=",
"node",
".",
"outputs",
"[",
"0",
"]",
"+",
"\"_5d_reshaped\"",
",",
"output_name",
"=",
"node",
".",
"outputs",
"[",
"0",
"]",
"+",
"\"_4d\"",
",",
"axes",
"=",
"[",
"-",
"1",
"]",
",",
")",
"builder",
".",
"add_transpose",
"(",
"name",
"=",
"node",
".",
"name",
"+",
"\"_transpose\"",
",",
"axes",
"=",
"[",
"0",
",",
"2",
",",
"1",
",",
"3",
"]",
",",
"input_name",
"=",
"node",
".",
"outputs",
"[",
"0",
"]",
"+",
"\"_4d\"",
",",
"output_name",
"=",
"node",
".",
"outputs",
"[",
"0",
"]",
",",
")",
"# Squeeze dimensions of output_h",
"builder",
".",
"add_squeeze",
"(",
"name",
"=",
"node",
".",
"name",
"+",
"\"_squeeze_out_h\"",
",",
"input_name",
"=",
"output_h_5d",
",",
"output_name",
"=",
"output_h",
",",
"axes",
"=",
"[",
"-",
"1",
",",
"-",
"2",
"]",
",",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/onnx/_operators_nd.py#L899-L1118 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tix.py | python | tixCommand.tix_resetoptions | (self, newScheme, newFontSet, newScmPrio=None) | Resets the scheme and fontset of the Tix application to
newScheme and newFontSet, respectively. This affects only those
widgets created after this call. Therefore, it is best to call the
resetoptions command before the creation of any widgets in a Tix
application.
The optional parameter newScmPrio can be given to reset the
priority level of the Tk options set by the Tix schemes.
Because of the way Tk handles the X option database, after Tix has
been has imported and inited, it is not possible to reset the color
schemes and font sets using the tix config command. Instead, the
tix_resetoptions command must be used. | Resets the scheme and fontset of the Tix application to
newScheme and newFontSet, respectively. This affects only those
widgets created after this call. Therefore, it is best to call the
resetoptions command before the creation of any widgets in a Tix
application. | [
"Resets",
"the",
"scheme",
"and",
"fontset",
"of",
"the",
"Tix",
"application",
"to",
"newScheme",
"and",
"newFontSet",
"respectively",
".",
"This",
"affects",
"only",
"those",
"widgets",
"created",
"after",
"this",
"call",
".",
"Therefore",
"it",
"is",
"best",
"to",
"call",
"the",
"resetoptions",
"command",
"before",
"the",
"creation",
"of",
"any",
"widgets",
"in",
"a",
"Tix",
"application",
"."
] | def tix_resetoptions(self, newScheme, newFontSet, newScmPrio=None):
"""Resets the scheme and fontset of the Tix application to
newScheme and newFontSet, respectively. This affects only those
widgets created after this call. Therefore, it is best to call the
resetoptions command before the creation of any widgets in a Tix
application.
The optional parameter newScmPrio can be given to reset the
priority level of the Tk options set by the Tix schemes.
Because of the way Tk handles the X option database, after Tix has
been has imported and inited, it is not possible to reset the color
schemes and font sets using the tix config command. Instead, the
tix_resetoptions command must be used.
"""
if newScmPrio is not None:
return self.tk.call('tix', 'resetoptions', newScheme, newFontSet, newScmPrio)
else:
return self.tk.call('tix', 'resetoptions', newScheme, newFontSet) | [
"def",
"tix_resetoptions",
"(",
"self",
",",
"newScheme",
",",
"newFontSet",
",",
"newScmPrio",
"=",
"None",
")",
":",
"if",
"newScmPrio",
"is",
"not",
"None",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'tix'",
",",
"'resetoptions'",
",",
"newScheme",
",",
"newFontSet",
",",
"newScmPrio",
")",
"else",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'tix'",
",",
"'resetoptions'",
",",
"newScheme",
",",
"newFontSet",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tix.py#L183-L201 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py2/jinja2/meta.py | python | find_undeclared_variables | (ast) | return codegen.undeclared_identifiers | Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast) == set(['bar'])
True
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well. | Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned. | [
"Returns",
"a",
"set",
"of",
"all",
"variables",
"in",
"the",
"AST",
"that",
"will",
"be",
"looked",
"up",
"from",
"the",
"context",
"at",
"runtime",
".",
"Because",
"at",
"compile",
"time",
"it",
"s",
"not",
"known",
"which",
"variables",
"will",
"be",
"used",
"depending",
"on",
"the",
"path",
"the",
"execution",
"takes",
"at",
"runtime",
"all",
"variables",
"are",
"returned",
"."
] | def find_undeclared_variables(ast):
"""Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast) == set(['bar'])
True
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well.
"""
codegen = TrackingCodeGenerator(ast.environment)
codegen.visit(ast)
return codegen.undeclared_identifiers | [
"def",
"find_undeclared_variables",
"(",
"ast",
")",
":",
"codegen",
"=",
"TrackingCodeGenerator",
"(",
"ast",
".",
"environment",
")",
"codegen",
".",
"visit",
"(",
"ast",
")",
"return",
"codegen",
".",
"undeclared_identifiers"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/meta.py#L29-L50 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/resource_variable_ops.py | python | BaseResourceVariable._assign_dependencies | (self) | Makes assignments depend on the cached value, if any.
This prevents undefined behavior with reads not ordered wrt writes.
Yields:
None. | Makes assignments depend on the cached value, if any. | [
"Makes",
"assignments",
"depend",
"on",
"the",
"cached",
"value",
"if",
"any",
"."
] | def _assign_dependencies(self):
"""Makes assignments depend on the cached value, if any.
This prevents undefined behavior with reads not ordered wrt writes.
Yields:
None.
"""
if self._cached_value is not None:
with ops.control_dependencies([self._cached_value]):
yield
else:
yield | [
"def",
"_assign_dependencies",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cached_value",
"is",
"not",
"None",
":",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"self",
".",
"_cached_value",
"]",
")",
":",
"yield",
"else",
":",
"yield"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/resource_variable_ops.py#L497-L509 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py | python | Helper.getline | (self, prompt) | Read one line, using input() when appropriate. | Read one line, using input() when appropriate. | [
"Read",
"one",
"line",
"using",
"input",
"()",
"when",
"appropriate",
"."
] | def getline(self, prompt):
"""Read one line, using input() when appropriate."""
if self.input is sys.stdin:
return input(prompt)
else:
self.output.write(prompt)
self.output.flush()
return self.input.readline() | [
"def",
"getline",
"(",
"self",
",",
"prompt",
")",
":",
"if",
"self",
".",
"input",
"is",
"sys",
".",
"stdin",
":",
"return",
"input",
"(",
"prompt",
")",
"else",
":",
"self",
".",
"output",
".",
"write",
"(",
"prompt",
")",
"self",
".",
"output",
".",
"flush",
"(",
")",
"return",
"self",
".",
"input",
".",
"readline",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py#L1924-L1931 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/combo.py | python | BitmapComboBox.Insert | (*args, **kwargs) | return _combo.BitmapComboBox_Insert(*args, **kwargs) | Insert(self, String item, Bitmap bitmap, int pos, PyObject clientData=None) -> int
Insert an item into the control before the item at the ``pos`` index,
optionally associating some data object with the item. | Insert(self, String item, Bitmap bitmap, int pos, PyObject clientData=None) -> int | [
"Insert",
"(",
"self",
"String",
"item",
"Bitmap",
"bitmap",
"int",
"pos",
"PyObject",
"clientData",
"=",
"None",
")",
"-",
">",
"int"
] | def Insert(*args, **kwargs):
"""
Insert(self, String item, Bitmap bitmap, int pos, PyObject clientData=None) -> int
Insert an item into the control before the item at the ``pos`` index,
optionally associating some data object with the item.
"""
return _combo.BitmapComboBox_Insert(*args, **kwargs) | [
"def",
"Insert",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"BitmapComboBox_Insert",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/combo.py#L989-L996 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PropertyGrid.GetImageSize | (*args, **kwargs) | return _propgrid.PropertyGrid_GetImageSize(*args, **kwargs) | GetImageSize(self, PGProperty p=None, int item=-1) -> Size | GetImageSize(self, PGProperty p=None, int item=-1) -> Size | [
"GetImageSize",
"(",
"self",
"PGProperty",
"p",
"=",
"None",
"int",
"item",
"=",
"-",
"1",
")",
"-",
">",
"Size"
] | def GetImageSize(*args, **kwargs):
"""GetImageSize(self, PGProperty p=None, int item=-1) -> Size"""
return _propgrid.PropertyGrid_GetImageSize(*args, **kwargs) | [
"def",
"GetImageSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_GetImageSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2091-L2093 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/locations.py | python | write_delete_marker_file | (directory) | Write the pip delete marker file into this directory. | Write the pip delete marker file into this directory. | [
"Write",
"the",
"pip",
"delete",
"marker",
"file",
"into",
"this",
"directory",
"."
] | def write_delete_marker_file(directory):
"""
Write the pip delete marker file into this directory.
"""
filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME)
with open(filepath, 'w') as marker_fp:
marker_fp.write(DELETE_MARKER_MESSAGE) | [
"def",
"write_delete_marker_file",
"(",
"directory",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"PIP_DELETE_MARKER_FILENAME",
")",
"with",
"open",
"(",
"filepath",
",",
"'w'",
")",
"as",
"marker_fp",
":",
"marker_fp",
".",
"write",
"(",
"DELETE_MARKER_MESSAGE",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/locations.py#L63-L69 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | llvm/utils/sort_includes.py | python | sort_includes | (f) | Sort the #include lines of a specific file. | Sort the #include lines of a specific file. | [
"Sort",
"the",
"#include",
"lines",
"of",
"a",
"specific",
"file",
"."
] | def sort_includes(f):
"""Sort the #include lines of a specific file."""
# Skip files which are under INPUTS trees or test trees.
if 'INPUTS/' in f.name or 'test/' in f.name:
return
ext = os.path.splitext(f.name)[1]
if ext not in ['.cpp', '.c', '.h', '.inc', '.def']:
return
lines = f.readlines()
look_for_api_header = ext in ['.cpp', '.c']
found_headers = False
headers_begin = 0
headers_end = 0
api_headers = []
local_headers = []
subproject_headers = []
llvm_headers = []
system_headers = []
for (i, l) in enumerate(lines):
if l.strip() == '':
continue
if l.startswith('#include'):
if not found_headers:
headers_begin = i
found_headers = True
headers_end = i
header = l[len('#include'):].lstrip()
if look_for_api_header and header.startswith('"'):
api_headers.append(header)
look_for_api_header = False
continue
if (header.startswith('<') or header.startswith('"gtest/') or
header.startswith('"isl/') or header.startswith('"json/')):
system_headers.append(header)
continue
if (header.startswith('"clang/') or header.startswith('"clang-c/') or
header.startswith('"polly/')):
subproject_headers.append(header)
continue
if (header.startswith('"llvm/') or header.startswith('"llvm-c/')):
llvm_headers.append(header)
continue
local_headers.append(header)
continue
# Only allow comments and #defines prior to any includes. If either are
# mixed with includes, the order might be sensitive.
if found_headers:
break
if l.startswith('//') or l.startswith('#define') or l.startswith('#ifndef'):
continue
break
if not found_headers:
return
local_headers = sorted(set(local_headers))
subproject_headers = sorted(set(subproject_headers))
llvm_headers = sorted(set(llvm_headers))
system_headers = sorted(set(system_headers))
headers = api_headers + local_headers + subproject_headers + llvm_headers + system_headers
header_lines = ['#include ' + h for h in headers]
lines = lines[:headers_begin] + header_lines + lines[headers_end + 1:]
f.seek(0)
f.truncate()
f.writelines(lines) | [
"def",
"sort_includes",
"(",
"f",
")",
":",
"# Skip files which are under INPUTS trees or test trees.",
"if",
"'INPUTS/'",
"in",
"f",
".",
"name",
"or",
"'test/'",
"in",
"f",
".",
"name",
":",
"return",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
".",
"name",
")",
"[",
"1",
"]",
"if",
"ext",
"not",
"in",
"[",
"'.cpp'",
",",
"'.c'",
",",
"'.h'",
",",
"'.inc'",
",",
"'.def'",
"]",
":",
"return",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"look_for_api_header",
"=",
"ext",
"in",
"[",
"'.cpp'",
",",
"'.c'",
"]",
"found_headers",
"=",
"False",
"headers_begin",
"=",
"0",
"headers_end",
"=",
"0",
"api_headers",
"=",
"[",
"]",
"local_headers",
"=",
"[",
"]",
"subproject_headers",
"=",
"[",
"]",
"llvm_headers",
"=",
"[",
"]",
"system_headers",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"l",
")",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"l",
".",
"strip",
"(",
")",
"==",
"''",
":",
"continue",
"if",
"l",
".",
"startswith",
"(",
"'#include'",
")",
":",
"if",
"not",
"found_headers",
":",
"headers_begin",
"=",
"i",
"found_headers",
"=",
"True",
"headers_end",
"=",
"i",
"header",
"=",
"l",
"[",
"len",
"(",
"'#include'",
")",
":",
"]",
".",
"lstrip",
"(",
")",
"if",
"look_for_api_header",
"and",
"header",
".",
"startswith",
"(",
"'\"'",
")",
":",
"api_headers",
".",
"append",
"(",
"header",
")",
"look_for_api_header",
"=",
"False",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'<'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"gtest/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"isl/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"json/'",
")",
")",
":",
"system_headers",
".",
"append",
"(",
"header",
")",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'\"clang/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"clang-c/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"polly/'",
")",
")",
":",
"subproject_headers",
".",
"append",
"(",
"header",
")",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'\"llvm/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"llvm-c/'",
")",
")",
":",
"llvm_headers",
".",
"append",
"(",
"header",
")",
"continue",
"local_headers",
".",
"append",
"(",
"header",
")",
"continue",
"# Only allow comments and #defines prior to any includes. If either are",
"# mixed with includes, the order might be sensitive.",
"if",
"found_headers",
":",
"break",
"if",
"l",
".",
"startswith",
"(",
"'//'",
")",
"or",
"l",
".",
"startswith",
"(",
"'#define'",
")",
"or",
"l",
".",
"startswith",
"(",
"'#ifndef'",
")",
":",
"continue",
"break",
"if",
"not",
"found_headers",
":",
"return",
"local_headers",
"=",
"sorted",
"(",
"set",
"(",
"local_headers",
")",
")",
"subproject_headers",
"=",
"sorted",
"(",
"set",
"(",
"subproject_headers",
")",
")",
"llvm_headers",
"=",
"sorted",
"(",
"set",
"(",
"llvm_headers",
")",
")",
"system_headers",
"=",
"sorted",
"(",
"set",
"(",
"system_headers",
")",
")",
"headers",
"=",
"api_headers",
"+",
"local_headers",
"+",
"subproject_headers",
"+",
"llvm_headers",
"+",
"system_headers",
"header_lines",
"=",
"[",
"'#include '",
"+",
"h",
"for",
"h",
"in",
"headers",
"]",
"lines",
"=",
"lines",
"[",
":",
"headers_begin",
"]",
"+",
"header_lines",
"+",
"lines",
"[",
"headers_end",
"+",
"1",
":",
"]",
"f",
".",
"seek",
"(",
"0",
")",
"f",
".",
"truncate",
"(",
")",
"f",
".",
"writelines",
"(",
"lines",
")"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/utils/sort_includes.py#L14-L82 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Tools/bgen/bgen/bgenOutput.py | python | OutHeader2 | (text) | Output a level 2 header comment (uses '-' dashes). | Output a level 2 header comment (uses '-' dashes). | [
"Output",
"a",
"level",
"2",
"header",
"comment",
"(",
"uses",
"-",
"dashes",
")",
"."
] | def OutHeader2(text):
"""Output a level 2 header comment (uses '-' dashes)."""
OutHeader(text, "-") | [
"def",
"OutHeader2",
"(",
"text",
")",
":",
"OutHeader",
"(",
"text",
",",
"\"-\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/bgen/bgen/bgenOutput.py#L140-L142 | ||
OpenArkStudio/ARK | a7f8413dd416cd1ac5b12adbdd84f010f59f11e2 | build/tools/config_tool/config_xml.py | python | get_node_by_keyvalue | (nodelist, kv_map) | return result_nodes | find all nodes that match the key-value
nodelist: node list
kv_map: property map
return: all matched nodes | find all nodes that match the key-value
nodelist: node list
kv_map: property map
return: all matched nodes | [
"find",
"all",
"nodes",
"that",
"match",
"the",
"key",
"-",
"value",
"nodelist",
":",
"node",
"list",
"kv_map",
":",
"property",
"map",
"return",
":",
"all",
"matched",
"nodes"
] | def get_node_by_keyvalue(nodelist, kv_map):
'''
find all nodes that match the key-value
nodelist: node list
kv_map: property map
return: all matched nodes
'''
result_nodes = []
for node in nodelist:
if if_match(node, kv_map):
result_nodes.append(node)
return result_nodes | [
"def",
"get_node_by_keyvalue",
"(",
"nodelist",
",",
"kv_map",
")",
":",
"result_nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"nodelist",
":",
"if",
"if_match",
"(",
"node",
",",
"kv_map",
")",
":",
"result_nodes",
".",
"append",
"(",
"node",
")",
"return",
"result_nodes"
] | https://github.com/OpenArkStudio/ARK/blob/a7f8413dd416cd1ac5b12adbdd84f010f59f11e2/build/tools/config_tool/config_xml.py#L56-L67 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PageSetupDialogData.EnablePrinter | (*args, **kwargs) | return _windows_.PageSetupDialogData_EnablePrinter(*args, **kwargs) | EnablePrinter(self, bool flag) | EnablePrinter(self, bool flag) | [
"EnablePrinter",
"(",
"self",
"bool",
"flag",
")"
] | def EnablePrinter(*args, **kwargs):
"""EnablePrinter(self, bool flag)"""
return _windows_.PageSetupDialogData_EnablePrinter(*args, **kwargs) | [
"def",
"EnablePrinter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_EnablePrinter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L4890-L4892 | |
kismetwireless/kismet | a7c0dc270c960fb1f58bd9cec4601c201885fd4e | capture_bt_geiger/KismetCaptureBtGeiger/kismetexternal/__init__.py | python | ExternalInterface.publish_event | (self, event, content_json) | Publish an event on the eventbus; see the docs for additional info and
limitations on events coming from the external api eventbus interface.
:param event: Event type UTF-8 string; should not collide with internal Kismet
eventbus events.
:param content_json: UTF-8 string JSON content of eventbus event.
:return: None | Publish an event on the eventbus; see the docs for additional info and
limitations on events coming from the external api eventbus interface. | [
"Publish",
"an",
"event",
"on",
"the",
"eventbus",
";",
"see",
"the",
"docs",
"for",
"additional",
"info",
"and",
"limitations",
"on",
"events",
"coming",
"from",
"the",
"external",
"api",
"eventbus",
"interface",
"."
] | def publish_event(self, event, content_json):
"""
Publish an event on the eventbus; see the docs for additional info and
limitations on events coming from the external api eventbus interface.
:param event: Event type UTF-8 string; should not collide with internal Kismet
eventbus events.
:param content_json: UTF-8 string JSON content of eventbus event.
:return: None
"""
pubevt = eventbus_pb2.EventbusPublishEvent()
pubevt.event_type = event
pubevt.event_content_json = content_json
self.write_ext_packet("EVENTBUSPUBLISH", pubevt) | [
"def",
"publish_event",
"(",
"self",
",",
"event",
",",
"content_json",
")",
":",
"pubevt",
"=",
"eventbus_pb2",
".",
"EventbusPublishEvent",
"(",
")",
"pubevt",
".",
"event_type",
"=",
"event",
"pubevt",
".",
"event_content_json",
"=",
"content_json",
"self",
".",
"write_ext_packet",
"(",
"\"EVENTBUSPUBLISH\"",
",",
"pubevt",
")"
] | https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_bt_geiger/KismetCaptureBtGeiger/kismetexternal/__init__.py#L487-L502 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/tools/scan-build-py/libscanbuild/analyze.py | python | filter_debug_flags | (opts, continuation=dispatch_ctu) | return continuation(opts) | Filter out nondebug macros when requested. | Filter out nondebug macros when requested. | [
"Filter",
"out",
"nondebug",
"macros",
"when",
"requested",
"."
] | def filter_debug_flags(opts, continuation=dispatch_ctu):
""" Filter out nondebug macros when requested. """
if opts.pop('force_debug'):
# lazy implementation just append an undefine macro at the end
opts.update({'flags': opts['flags'] + ['-UNDEBUG']})
return continuation(opts) | [
"def",
"filter_debug_flags",
"(",
"opts",
",",
"continuation",
"=",
"dispatch_ctu",
")",
":",
"if",
"opts",
".",
"pop",
"(",
"'force_debug'",
")",
":",
"# lazy implementation just append an undefine macro at the end",
"opts",
".",
"update",
"(",
"{",
"'flags'",
":",
"opts",
"[",
"'flags'",
"]",
"+",
"[",
"'-UNDEBUG'",
"]",
"}",
")",
"return",
"continuation",
"(",
"opts",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/tools/scan-build-py/libscanbuild/analyze.py#L667-L674 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetCompilerPdbName | (self, config, expand_special) | return pdbname | Get the pdb file name that should be used for compiler invocations, or
None if there's no explicit name specified. | Get the pdb file name that should be used for compiler invocations, or
None if there's no explicit name specified. | [
"Get",
"the",
"pdb",
"file",
"name",
"that",
"should",
"be",
"used",
"for",
"compiler",
"invocations",
"or",
"None",
"if",
"there",
"s",
"no",
"explicit",
"name",
"specified",
"."
] | def GetCompilerPdbName(self, config, expand_special):
"""Get the pdb file name that should be used for compiler invocations, or
None if there's no explicit name specified."""
config = self._TargetConfig(config)
pdbname = self._Setting(
('VCCLCompilerTool', 'ProgramDataBaseFileName'), config)
if pdbname:
pdbname = expand_special(self.ConvertVSMacros(pdbname))
return pdbname | [
"def",
"GetCompilerPdbName",
"(",
"self",
",",
"config",
",",
"expand_special",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"pdbname",
"=",
"self",
".",
"_Setting",
"(",
"(",
"'VCCLCompilerTool'",
",",
"'ProgramDataBaseFileName'",
")",
",",
"config",
")",
"if",
"pdbname",
":",
"pdbname",
"=",
"expand_special",
"(",
"self",
".",
"ConvertVSMacros",
"(",
"pdbname",
")",
")",
"return",
"pdbname"
] | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/msvs_emulation.py#L363-L371 | |
qboticslabs/mastering_ros | d83e78f30acc45b0f18522c1d5fae3a7f52974b9 | chapter_10_codes/seven_dof_arm_gazebo/scripts/pick_and_place_working_1.py | python | CokeCanPickAndPlace._create_pickup_goal | (self, group, target, grasps) | return goal | Create a MoveIt! PickupGoal | Create a MoveIt! PickupGoal | [
"Create",
"a",
"MoveIt!",
"PickupGoal"
] | def _create_pickup_goal(self, group, target, grasps):
"""
Create a MoveIt! PickupGoal
"""
# Create goal:
goal = PickupGoal()
goal.group_name = group
goal.target_name = target
goal.possible_grasps.extend(grasps)
goal.allowed_touch_objects.append(target)
goal.support_surface_name = self._table_object_name
# Configure goal planning options:
goal.allowed_planning_time = 7.0
goal.planning_options.planning_scene_diff.is_diff = True
goal.planning_options.planning_scene_diff.robot_state.is_diff = True
goal.planning_options.plan_only = False
goal.planning_options.replan = True
goal.planning_options.replan_attempts = 20
return goal | [
"def",
"_create_pickup_goal",
"(",
"self",
",",
"group",
",",
"target",
",",
"grasps",
")",
":",
"# Create goal:",
"goal",
"=",
"PickupGoal",
"(",
")",
"goal",
".",
"group_name",
"=",
"group",
"goal",
".",
"target_name",
"=",
"target",
"goal",
".",
"possible_grasps",
".",
"extend",
"(",
"grasps",
")",
"goal",
".",
"allowed_touch_objects",
".",
"append",
"(",
"target",
")",
"goal",
".",
"support_surface_name",
"=",
"self",
".",
"_table_object_name",
"# Configure goal planning options:",
"goal",
".",
"allowed_planning_time",
"=",
"7.0",
"goal",
".",
"planning_options",
".",
"planning_scene_diff",
".",
"is_diff",
"=",
"True",
"goal",
".",
"planning_options",
".",
"planning_scene_diff",
".",
"robot_state",
".",
"is_diff",
"=",
"True",
"goal",
".",
"planning_options",
".",
"plan_only",
"=",
"False",
"goal",
".",
"planning_options",
".",
"replan",
"=",
"True",
"goal",
".",
"planning_options",
".",
"replan_attempts",
"=",
"20",
"return",
"goal"
] | https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_10_codes/seven_dof_arm_gazebo/scripts/pick_and_place_working_1.py#L245-L271 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/virtualenv/virtualenv.py | python | fixup_pth_and_egg_link | (home_dir, sys_path=None) | Makes .pth and .egg-link files use relative paths | Makes .pth and .egg-link files use relative paths | [
"Makes",
".",
"pth",
"and",
".",
"egg",
"-",
"link",
"files",
"use",
"relative",
"paths"
] | def fixup_pth_and_egg_link(home_dir, sys_path=None):
"""Makes .pth and .egg-link files use relative paths"""
home_dir = os.path.normcase(os.path.abspath(home_dir))
if sys_path is None:
sys_path = sys.path
for path in sys_path:
if not path:
path = '.'
if not os.path.isdir(path):
continue
path = os.path.normcase(os.path.abspath(path))
if not path.startswith(home_dir):
logger.debug('Skipping system (non-environment) directory %s' % path)
continue
for filename in os.listdir(path):
filename = os.path.join(path, filename)
if filename.endswith('.pth'):
if not os.access(filename, os.W_OK):
logger.warn('Cannot write .pth file %s, skipping' % filename)
else:
fixup_pth_file(filename)
if filename.endswith('.egg-link'):
if not os.access(filename, os.W_OK):
logger.warn('Cannot write .egg-link file %s, skipping' % filename)
else:
fixup_egg_link(filename) | [
"def",
"fixup_pth_and_egg_link",
"(",
"home_dir",
",",
"sys_path",
"=",
"None",
")",
":",
"home_dir",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"home_dir",
")",
")",
"if",
"sys_path",
"is",
"None",
":",
"sys_path",
"=",
"sys",
".",
"path",
"for",
"path",
"in",
"sys_path",
":",
"if",
"not",
"path",
":",
"path",
"=",
"'.'",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"continue",
"path",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"home_dir",
")",
":",
"logger",
".",
"debug",
"(",
"'Skipping system (non-environment) directory %s'",
"%",
"path",
")",
"continue",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"if",
"filename",
".",
"endswith",
"(",
"'.pth'",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".",
"W_OK",
")",
":",
"logger",
".",
"warn",
"(",
"'Cannot write .pth file %s, skipping'",
"%",
"filename",
")",
"else",
":",
"fixup_pth_file",
"(",
"filename",
")",
"if",
"filename",
".",
"endswith",
"(",
"'.egg-link'",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".",
"W_OK",
")",
":",
"logger",
".",
"warn",
"(",
"'Cannot write .egg-link file %s, skipping'",
"%",
"filename",
")",
"else",
":",
"fixup_egg_link",
"(",
"filename",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/virtualenv/virtualenv.py#L1685-L1710 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PropertyGridInterface.GetPropertyHelpString | (*args, **kwargs) | return _propgrid.PropertyGridInterface_GetPropertyHelpString(*args, **kwargs) | GetPropertyHelpString(self, PGPropArg id) -> String | GetPropertyHelpString(self, PGPropArg id) -> String | [
"GetPropertyHelpString",
"(",
"self",
"PGPropArg",
"id",
")",
"-",
">",
"String"
] | def GetPropertyHelpString(*args, **kwargs):
"""GetPropertyHelpString(self, PGPropArg id) -> String"""
return _propgrid.PropertyGridInterface_GetPropertyHelpString(*args, **kwargs) | [
"def",
"GetPropertyHelpString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_GetPropertyHelpString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L1221-L1223 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/configgenerator.py | python | ConfigGenerator._add_register | (self, name, value) | return reg | Shortcut to add a register into the XML
:param name: <register name="xxx">
:param value: <register value="xxx"> | Shortcut to add a register into the XML
:param name: <register name="xxx">
:param value: <register value="xxx"> | [
"Shortcut",
"to",
"add",
"a",
"register",
"into",
"the",
"XML",
":",
"param",
"name",
":",
"<register",
"name",
"=",
"xxx",
">",
":",
"param",
"value",
":",
"<register",
"value",
"=",
"xxx",
">"
] | def _add_register(self, name, value):
"""
Shortcut to add a register into the XML
:param name: <register name="xxx">
:param value: <register value="xxx">
"""
reg = ETree.Element("register")
reg.attrib["name"] = name
reg.attrib["value"] = value
return reg | [
"def",
"_add_register",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"reg",
"=",
"ETree",
".",
"Element",
"(",
"\"register\"",
")",
"reg",
".",
"attrib",
"[",
"\"name\"",
"]",
"=",
"name",
"reg",
".",
"attrib",
"[",
"\"value\"",
"]",
"=",
"value",
"return",
"reg"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/configgenerator.py#L148-L157 | |
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | scripts/cpp_lint.py | python | _CppLintState.SetCountingStyle | (self, counting_style) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style | [
"def",
"SetCountingStyle",
"(",
"self",
",",
"counting_style",
")",
":",
"self",
".",
"counting",
"=",
"counting_style"
] | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L717-L719 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/training/saver.py | python | _add_collection_def | (meta_graph_def, key) | Adds a collection to MetaGraphDef protocol buffer.
Args:
meta_graph_def: MetaGraphDef protocol buffer.
key: One of the GraphKeys or user-defined string. | Adds a collection to MetaGraphDef protocol buffer. | [
"Adds",
"a",
"collection",
"to",
"MetaGraphDef",
"protocol",
"buffer",
"."
] | def _add_collection_def(meta_graph_def, key):
"""Adds a collection to MetaGraphDef protocol buffer.
Args:
meta_graph_def: MetaGraphDef protocol buffer.
key: One of the GraphKeys or user-defined string.
"""
if not isinstance(key, six.string_types) and not isinstance(key, bytes):
logging.warning("Only collections with string type keys will be "
"serialized. This key has %s", type(key))
return
collection_list = ops.get_collection(key)
if not collection_list:
return
try:
col_def = meta_graph_def.collection_def[key]
to_proto = ops.get_to_proto_function(key)
proto_type = ops.get_collection_proto_type(key)
if to_proto:
kind = "bytes_list"
for x in collection_list:
# Additional type check to make sure the returned proto is indeed
# what we expect.
proto = to_proto(x)
assert isinstance(proto, proto_type)
getattr(col_def, kind).value.append(proto.SerializeToString())
else:
kind = _get_kind_name(collection_list[0])
if kind == "node_list":
getattr(col_def, kind).value.extend([x.name for x in collection_list])
elif kind == "bytes_list":
# NOTE(opensource): This force conversion is to work around the fact
# that Python3 distinguishes between bytes and strings.
getattr(col_def, kind).value.extend(
[compat.as_bytes(x) for x in collection_list])
else:
getattr(col_def, kind).value.extend([x for x in collection_list])
except Exception as e: # pylint: disable=broad-except
logging.warning("Error encountered when serializing %s.\n"
"Type is unsupported, or the types of the items don't "
"match field type in CollectionDef.\n%s", key, str(e))
if key in meta_graph_def.collection_def:
del meta_graph_def.collection_def[key]
return | [
"def",
"_add_collection_def",
"(",
"meta_graph_def",
",",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
"and",
"not",
"isinstance",
"(",
"key",
",",
"bytes",
")",
":",
"logging",
".",
"warning",
"(",
"\"Only collections with string type keys will be \"",
"\"serialized. This key has %s\"",
",",
"type",
"(",
"key",
")",
")",
"return",
"collection_list",
"=",
"ops",
".",
"get_collection",
"(",
"key",
")",
"if",
"not",
"collection_list",
":",
"return",
"try",
":",
"col_def",
"=",
"meta_graph_def",
".",
"collection_def",
"[",
"key",
"]",
"to_proto",
"=",
"ops",
".",
"get_to_proto_function",
"(",
"key",
")",
"proto_type",
"=",
"ops",
".",
"get_collection_proto_type",
"(",
"key",
")",
"if",
"to_proto",
":",
"kind",
"=",
"\"bytes_list\"",
"for",
"x",
"in",
"collection_list",
":",
"# Additional type check to make sure the returned proto is indeed",
"# what we expect.",
"proto",
"=",
"to_proto",
"(",
"x",
")",
"assert",
"isinstance",
"(",
"proto",
",",
"proto_type",
")",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"append",
"(",
"proto",
".",
"SerializeToString",
"(",
")",
")",
"else",
":",
"kind",
"=",
"_get_kind_name",
"(",
"collection_list",
"[",
"0",
"]",
")",
"if",
"kind",
"==",
"\"node_list\"",
":",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"extend",
"(",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"collection_list",
"]",
")",
"elif",
"kind",
"==",
"\"bytes_list\"",
":",
"# NOTE(opensource): This force conversion is to work around the fact",
"# that Python3 distinguishes between bytes and strings.",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"extend",
"(",
"[",
"compat",
".",
"as_bytes",
"(",
"x",
")",
"for",
"x",
"in",
"collection_list",
"]",
")",
"else",
":",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"extend",
"(",
"[",
"x",
"for",
"x",
"in",
"collection_list",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"logging",
".",
"warning",
"(",
"\"Error encountered when serializing %s.\\n\"",
"\"Type is unsupported, or the types of the items don't \"",
"\"match field type in CollectionDef.\\n%s\"",
",",
"key",
",",
"str",
"(",
"e",
")",
")",
"if",
"key",
"in",
"meta_graph_def",
".",
"collection_def",
":",
"del",
"meta_graph_def",
".",
"collection_def",
"[",
"key",
"]",
"return"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/saver.py#L1188-L1231 | ||
ucb-bar/esp-llvm | 8aec2ae754fd66d4e73b9b777a9f20c4583a0f03 | examples/Kaleidoscope/MCJIT/lazy/genk-timing.py | python | KScriptGenerator.setCallWeighting | (self, weight) | Sets the probably of generating a function call | Sets the probably of generating a function call | [
"Sets",
"the",
"probably",
"of",
"generating",
"a",
"function",
"call"
] | def setCallWeighting(self, weight):
""" Sets the probably of generating a function call"""
self.callWeighting = weight | [
"def",
"setCallWeighting",
"(",
"self",
",",
"weight",
")",
":",
"self",
".",
"callWeighting",
"=",
"weight"
] | https://github.com/ucb-bar/esp-llvm/blob/8aec2ae754fd66d4e73b9b777a9f20c4583a0f03/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L80-L82 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/_trustregion_constr/qp_subproblem.py | python | reinforce_box_boundaries | (x, lb, ub) | return np.minimum(np.maximum(x, lb), ub) | Return clipped value of x | Return clipped value of x | [
"Return",
"clipped",
"value",
"of",
"x"
] | def reinforce_box_boundaries(x, lb, ub):
"""Return clipped value of x"""
return np.minimum(np.maximum(x, lb), ub) | [
"def",
"reinforce_box_boundaries",
"(",
"x",
",",
"lb",
",",
"ub",
")",
":",
"return",
"np",
".",
"minimum",
"(",
"np",
".",
"maximum",
"(",
"x",
",",
"lb",
")",
",",
"ub",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_trustregion_constr/qp_subproblem.py#L311-L313 | |
eric612/MobileNet-YOLO | 69b4441cb3ec8d553fbdef788ad033e246f901bd | scripts/cpp_lint.py | python | CheckAltTokens | (filename, clean_lines, linenum, error) | Check alternative keywords being used in boolean expressions.
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. | Check alternative keywords being used in boolean expressions. | [
"Check",
"alternative",
"keywords",
"being",
"used",
"in",
"boolean",
"expressions",
"."
] | def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
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]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) | [
"def",
"CheckAltTokens",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Avoid preprocessor lines",
"if",
"Match",
"(",
"r'^\\s*#'",
",",
"line",
")",
":",
"return",
"# Last ditch effort to avoid multi-line comments. This will not help",
"# if the comment started before the current line or ended after the",
"# current line, but it catches most of the false positives. At least,",
"# it provides a way to workaround this warning for people who use",
"# multi-line comments in preprocessor macros.",
"#",
"# TODO(unknown): remove this once cpplint has better support for",
"# multi-line comments.",
"if",
"line",
".",
"find",
"(",
"'/*'",
")",
">=",
"0",
"or",
"line",
".",
"find",
"(",
"'*/'",
")",
">=",
"0",
":",
"return",
"for",
"match",
"in",
"_ALT_TOKEN_REPLACEMENT_PATTERN",
".",
"finditer",
"(",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/alt_tokens'",
",",
"2",
",",
"'Use operator %s instead of %s'",
"%",
"(",
"_ALT_TOKEN_REPLACEMENT",
"[",
"match",
".",
"group",
"(",
"1",
")",
"]",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")"
] | https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/scripts/cpp_lint.py#L3409-L3438 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/osr.py | python | SpatialReference.ExportToUSGS | (self, *args) | return _osr.SpatialReference_ExportToUSGS(self, *args) | r"""ExportToUSGS(SpatialReference self) -> OGRErr | r"""ExportToUSGS(SpatialReference self) -> OGRErr | [
"r",
"ExportToUSGS",
"(",
"SpatialReference",
"self",
")",
"-",
">",
"OGRErr"
] | def ExportToUSGS(self, *args):
r"""ExportToUSGS(SpatialReference self) -> OGRErr"""
return _osr.SpatialReference_ExportToUSGS(self, *args) | [
"def",
"ExportToUSGS",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_osr",
".",
"SpatialReference_ExportToUSGS",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/osr.py#L822-L824 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | PBXGroup.TakeOverOnlyChild | (self, recurse=False) | If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e. | If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children. | [
"If",
"this",
"PBXGroup",
"has",
"only",
"one",
"child",
"and",
"it",
"s",
"also",
"a",
"PBXGroup",
"take",
"it",
"over",
"by",
"making",
"all",
"of",
"its",
"children",
"this",
"object",
"s",
"children",
"."
] | def TakeOverOnlyChild(self, recurse=False):
"""If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e.
"""
# At this stage, check that child class types are PBXGroup exactly,
# instead of using isinstance. The only subclass of PBXGroup,
# PBXVariantGroup, should not participate in reparenting in the same way:
# reparenting by merging different object types would be wrong.
while (
len(self._properties["children"]) == 1
and self._properties["children"][0].__class__ == PBXGroup
):
# Loop to take over the innermost only-child group possible.
child = self._properties["children"][0]
# Assume the child's properties, including its children. Save a copy
# of this object's old properties, because they'll still be needed.
# This object retains its existing id and parent attributes.
old_properties = self._properties
self._properties = child._properties
self._children_by_path = child._children_by_path
if (
"sourceTree" not in self._properties
or self._properties["sourceTree"] == "<group>"
):
# The child was relative to its parent. Fix up the path. Note that
# children with a sourceTree other than "<group>" are not relative to
# their parents, so no path fix-up is needed in that case.
if "path" in old_properties:
if "path" in self._properties:
# Both the original parent and child have paths set.
self._properties["path"] = posixpath.join(
old_properties["path"], self._properties["path"]
)
else:
# Only the original parent has a path, use it.
self._properties["path"] = old_properties["path"]
if "sourceTree" in old_properties:
# The original parent had a sourceTree set, use it.
self._properties["sourceTree"] = old_properties["sourceTree"]
# If the original parent had a name set, keep using it. If the original
# parent didn't have a name but the child did, let the child's name
# live on. If the name attribute seems unnecessary now, get rid of it.
if "name" in old_properties and old_properties["name"] not in (
None,
self.Name(),
):
self._properties["name"] = old_properties["name"]
if (
"name" in self._properties
and "path" in self._properties
and self._properties["name"] == self._properties["path"]
):
del self._properties["name"]
# Notify all children of their new parent.
for child in self._properties["children"]:
child.parent = self
# If asked to recurse, recurse.
if recurse:
for child in self._properties["children"]:
if child.__class__ == PBXGroup:
child.TakeOverOnlyChild(recurse) | [
"def",
"TakeOverOnlyChild",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"# At this stage, check that child class types are PBXGroup exactly,",
"# instead of using isinstance. The only subclass of PBXGroup,",
"# PBXVariantGroup, should not participate in reparenting in the same way:",
"# reparenting by merging different object types would be wrong.",
"while",
"(",
"len",
"(",
"self",
".",
"_properties",
"[",
"\"children\"",
"]",
")",
"==",
"1",
"and",
"self",
".",
"_properties",
"[",
"\"children\"",
"]",
"[",
"0",
"]",
".",
"__class__",
"==",
"PBXGroup",
")",
":",
"# Loop to take over the innermost only-child group possible.",
"child",
"=",
"self",
".",
"_properties",
"[",
"\"children\"",
"]",
"[",
"0",
"]",
"# Assume the child's properties, including its children. Save a copy",
"# of this object's old properties, because they'll still be needed.",
"# This object retains its existing id and parent attributes.",
"old_properties",
"=",
"self",
".",
"_properties",
"self",
".",
"_properties",
"=",
"child",
".",
"_properties",
"self",
".",
"_children_by_path",
"=",
"child",
".",
"_children_by_path",
"if",
"(",
"\"sourceTree\"",
"not",
"in",
"self",
".",
"_properties",
"or",
"self",
".",
"_properties",
"[",
"\"sourceTree\"",
"]",
"==",
"\"<group>\"",
")",
":",
"# The child was relative to its parent. Fix up the path. Note that",
"# children with a sourceTree other than \"<group>\" are not relative to",
"# their parents, so no path fix-up is needed in that case.",
"if",
"\"path\"",
"in",
"old_properties",
":",
"if",
"\"path\"",
"in",
"self",
".",
"_properties",
":",
"# Both the original parent and child have paths set.",
"self",
".",
"_properties",
"[",
"\"path\"",
"]",
"=",
"posixpath",
".",
"join",
"(",
"old_properties",
"[",
"\"path\"",
"]",
",",
"self",
".",
"_properties",
"[",
"\"path\"",
"]",
")",
"else",
":",
"# Only the original parent has a path, use it.",
"self",
".",
"_properties",
"[",
"\"path\"",
"]",
"=",
"old_properties",
"[",
"\"path\"",
"]",
"if",
"\"sourceTree\"",
"in",
"old_properties",
":",
"# The original parent had a sourceTree set, use it.",
"self",
".",
"_properties",
"[",
"\"sourceTree\"",
"]",
"=",
"old_properties",
"[",
"\"sourceTree\"",
"]",
"# If the original parent had a name set, keep using it. If the original",
"# parent didn't have a name but the child did, let the child's name",
"# live on. If the name attribute seems unnecessary now, get rid of it.",
"if",
"\"name\"",
"in",
"old_properties",
"and",
"old_properties",
"[",
"\"name\"",
"]",
"not",
"in",
"(",
"None",
",",
"self",
".",
"Name",
"(",
")",
",",
")",
":",
"self",
".",
"_properties",
"[",
"\"name\"",
"]",
"=",
"old_properties",
"[",
"\"name\"",
"]",
"if",
"(",
"\"name\"",
"in",
"self",
".",
"_properties",
"and",
"\"path\"",
"in",
"self",
".",
"_properties",
"and",
"self",
".",
"_properties",
"[",
"\"name\"",
"]",
"==",
"self",
".",
"_properties",
"[",
"\"path\"",
"]",
")",
":",
"del",
"self",
".",
"_properties",
"[",
"\"name\"",
"]",
"# Notify all children of their new parent.",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"\"children\"",
"]",
":",
"child",
".",
"parent",
"=",
"self",
"# If asked to recurse, recurse.",
"if",
"recurse",
":",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"\"children\"",
"]",
":",
"if",
"child",
".",
"__class__",
"==",
"PBXGroup",
":",
"child",
".",
"TakeOverOnlyChild",
"(",
"recurse",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L1408-L1486 | ||
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | protobuf/python/google/protobuf/internal/decoder.py | python | _RaiseInvalidWireType | (buffer, pos, end) | Skip function for unknown wire types. Raises an exception. | Skip function for unknown wire types. Raises an exception. | [
"Skip",
"function",
"for",
"unknown",
"wire",
"types",
".",
"Raises",
"an",
"exception",
"."
] | def _RaiseInvalidWireType(buffer, pos, end):
"""Skip function for unknown wire types. Raises an exception."""
raise _DecodeError('Tag had invalid wire type.') | [
"def",
"_RaiseInvalidWireType",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"raise",
"_DecodeError",
"(",
"'Tag had invalid wire type.'",
")"
] | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/internal/decoder.py#L835-L838 | ||
digibyte/digibyte | 0b8a04fb06d5470a15168e2f675aec57bcc24dac | contrib/devtools/security-check.py | python | get_ELF_program_headers | (executable) | return headers | Return type and flags for ELF program headers | Return type and flags for ELF program headers | [
"Return",
"type",
"and",
"flags",
"for",
"ELF",
"program",
"headers"
] | def get_ELF_program_headers(executable):
'''Return type and flags for ELF program headers'''
p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
in_headers = False
count = 0
headers = []
for line in stdout.splitlines():
if line.startswith('Program Headers:'):
in_headers = True
if line == '':
in_headers = False
if in_headers:
if count == 1: # header line
ofs_typ = line.find('Type')
ofs_offset = line.find('Offset')
ofs_flags = line.find('Flg')
ofs_align = line.find('Align')
if ofs_typ == -1 or ofs_offset == -1 or ofs_flags == -1 or ofs_align == -1:
raise ValueError('Cannot parse elfread -lW output')
elif count > 1:
typ = line[ofs_typ:ofs_offset].rstrip()
flags = line[ofs_flags:ofs_align].rstrip()
headers.append((typ, flags))
count += 1
return headers | [
"def",
"get_ELF_program_headers",
"(",
"executable",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"READELF_CMD",
",",
"'-l'",
",",
"'-W'",
",",
"executable",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"universal_newlines",
"=",
"True",
")",
"(",
"stdout",
",",
"stderr",
")",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
":",
"raise",
"IOError",
"(",
"'Error opening file'",
")",
"in_headers",
"=",
"False",
"count",
"=",
"0",
"headers",
"=",
"[",
"]",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'Program Headers:'",
")",
":",
"in_headers",
"=",
"True",
"if",
"line",
"==",
"''",
":",
"in_headers",
"=",
"False",
"if",
"in_headers",
":",
"if",
"count",
"==",
"1",
":",
"# header line",
"ofs_typ",
"=",
"line",
".",
"find",
"(",
"'Type'",
")",
"ofs_offset",
"=",
"line",
".",
"find",
"(",
"'Offset'",
")",
"ofs_flags",
"=",
"line",
".",
"find",
"(",
"'Flg'",
")",
"ofs_align",
"=",
"line",
".",
"find",
"(",
"'Align'",
")",
"if",
"ofs_typ",
"==",
"-",
"1",
"or",
"ofs_offset",
"==",
"-",
"1",
"or",
"ofs_flags",
"==",
"-",
"1",
"or",
"ofs_align",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'Cannot parse elfread -lW output'",
")",
"elif",
"count",
">",
"1",
":",
"typ",
"=",
"line",
"[",
"ofs_typ",
":",
"ofs_offset",
"]",
".",
"rstrip",
"(",
")",
"flags",
"=",
"line",
"[",
"ofs_flags",
":",
"ofs_align",
"]",
".",
"rstrip",
"(",
")",
"headers",
".",
"append",
"(",
"(",
"typ",
",",
"flags",
")",
")",
"count",
"+=",
"1",
"return",
"headers"
] | https://github.com/digibyte/digibyte/blob/0b8a04fb06d5470a15168e2f675aec57bcc24dac/contrib/devtools/security-check.py#L35-L62 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/textwrap.py | python | dedent | (text) | return text | Remove any common leading whitespace from every line in `text`.
This can be used to make triple-quoted strings line up with the left
edge of the display, while still presenting them in the source code
in indented form.
Note that tabs and spaces are both treated as whitespace, but they
are not equal: the lines " hello" and "\thello" are
considered to have no common leading whitespace. (This behaviour is
new in Python 2.5; older versions of this module incorrectly
expanded tabs before searching for common leading whitespace.) | Remove any common leading whitespace from every line in `text`. | [
"Remove",
"any",
"common",
"leading",
"whitespace",
"from",
"every",
"line",
"in",
"text",
"."
] | def dedent(text):
"""Remove any common leading whitespace from every line in `text`.
This can be used to make triple-quoted strings line up with the left
edge of the display, while still presenting them in the source code
in indented form.
Note that tabs and spaces are both treated as whitespace, but they
are not equal: the lines " hello" and "\thello" are
considered to have no common leading whitespace. (This behaviour is
new in Python 2.5; older versions of this module incorrectly
expanded tabs before searching for common leading whitespace.)
"""
# Look for the longest leading string of spaces and tabs common to
# all lines.
margin = None
text = _whitespace_only_re.sub('', text)
indents = _leading_whitespace_re.findall(text)
for indent in indents:
if margin is None:
margin = indent
# Current line more deeply indented than previous winner:
# no change (previous winner is still on top).
elif indent.startswith(margin):
pass
# Current line consistent with and no deeper than previous winner:
# it's the new winner.
elif margin.startswith(indent):
margin = indent
# Current line and previous winner have no common whitespace:
# there is no margin.
else:
margin = ""
break
# sanity check (testing/debugging only)
if 0 and margin:
for line in text.split("\n"):
assert not line or line.startswith(margin), \
"line = %r, margin = %r" % (line, margin)
if margin:
text = re.sub(r'(?m)^' + margin, '', text)
return text | [
"def",
"dedent",
"(",
"text",
")",
":",
"# Look for the longest leading string of spaces and tabs common to",
"# all lines.",
"margin",
"=",
"None",
"text",
"=",
"_whitespace_only_re",
".",
"sub",
"(",
"''",
",",
"text",
")",
"indents",
"=",
"_leading_whitespace_re",
".",
"findall",
"(",
"text",
")",
"for",
"indent",
"in",
"indents",
":",
"if",
"margin",
"is",
"None",
":",
"margin",
"=",
"indent",
"# Current line more deeply indented than previous winner:",
"# no change (previous winner is still on top).",
"elif",
"indent",
".",
"startswith",
"(",
"margin",
")",
":",
"pass",
"# Current line consistent with and no deeper than previous winner:",
"# it's the new winner.",
"elif",
"margin",
".",
"startswith",
"(",
"indent",
")",
":",
"margin",
"=",
"indent",
"# Current line and previous winner have no common whitespace:",
"# there is no margin.",
"else",
":",
"margin",
"=",
"\"\"",
"break",
"# sanity check (testing/debugging only)",
"if",
"0",
"and",
"margin",
":",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"assert",
"not",
"line",
"or",
"line",
".",
"startswith",
"(",
"margin",
")",
",",
"\"line = %r, margin = %r\"",
"%",
"(",
"line",
",",
"margin",
")",
"if",
"margin",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r'(?m)^'",
"+",
"margin",
",",
"''",
",",
"text",
")",
"return",
"text"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/textwrap.py#L366-L412 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.DocumentStartExtend | (*args, **kwargs) | return _stc.StyledTextCtrl_DocumentStartExtend(*args, **kwargs) | DocumentStartExtend(self)
Move caret to first position in document extending selection to new caret position. | DocumentStartExtend(self) | [
"DocumentStartExtend",
"(",
"self",
")"
] | def DocumentStartExtend(*args, **kwargs):
"""
DocumentStartExtend(self)
Move caret to first position in document extending selection to new caret position.
"""
return _stc.StyledTextCtrl_DocumentStartExtend(*args, **kwargs) | [
"def",
"DocumentStartExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_DocumentStartExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4464-L4470 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/tf/ObjectDetectionAPI.py | python | ObjectDetectionAPIProposalReplacement.insert_detection_output_instead_of_proposal | (graph: Graph, match: SubgraphMatch,
pipeline_config: PipelineConfig) | return {'proposal_node': ObjectDetectionAPIProposalReplacement.ie_to_tf_proposals(graph, proposal_node, match,
pipeline_config,
max_proposals)} | The function inserts DetectionOutput operation instead of Proposal operation which may result in an increase of
the accuracy for some models. The function is enabled with the custom attribute "operation_to_insert" with
value "DetectionOutput" in the transformation configuration file section for the
"ObjectDetectionAPIProposalReplacement" transformation.
:param graph: the graph to operate on
:param match: the object containing information about the matched sub-graph
:param pipeline_config: object containing information from the pipeline.config file of the model
:return: the dictionary with mapping information needed for other transformations | The function inserts DetectionOutput operation instead of Proposal operation which may result in an increase of
the accuracy for some models. The function is enabled with the custom attribute "operation_to_insert" with
value "DetectionOutput" in the transformation configuration file section for the
"ObjectDetectionAPIProposalReplacement" transformation. | [
"The",
"function",
"inserts",
"DetectionOutput",
"operation",
"instead",
"of",
"Proposal",
"operation",
"which",
"may",
"result",
"in",
"an",
"increase",
"of",
"the",
"accuracy",
"for",
"some",
"models",
".",
"The",
"function",
"is",
"enabled",
"with",
"the",
"custom",
"attribute",
"operation_to_insert",
"with",
"value",
"DetectionOutput",
"in",
"the",
"transformation",
"configuration",
"file",
"section",
"for",
"the",
"ObjectDetectionAPIProposalReplacement",
"transformation",
"."
] | def insert_detection_output_instead_of_proposal(graph: Graph, match: SubgraphMatch,
pipeline_config: PipelineConfig):
"""
The function inserts DetectionOutput operation instead of Proposal operation which may result in an increase of
the accuracy for some models. The function is enabled with the custom attribute "operation_to_insert" with
value "DetectionOutput" in the transformation configuration file section for the
"ObjectDetectionAPIProposalReplacement" transformation.
:param graph: the graph to operate on
:param match: the object containing information about the matched sub-graph
:param pipeline_config: object containing information from the pipeline.config file of the model
:return: the dictionary with mapping information needed for other transformations
"""
max_proposals = _value_or_raise(match, pipeline_config, 'first_stage_max_proposals')
# Convolution/matmul node that produces classes confidence
# Transpose result of the tensor with classes confidences so it will be in a correct layout for Softmax
class_conf_nodes = backward_bfs_for_operation(match.single_input_node(1)[0], ['Add'])
assert len(class_conf_nodes) >= 1, 'Expected to find nodes of type "Add" starting from the node "{}" in ' \
'backward direction'.format(match.single_input_node(1)[0].id)
class_conf = class_conf_nodes[0]
# prepare input with class confidences. The DetectionOutput operation which will consume this tensor as a
# second input expects probabilities to be normalized with SoftMax operation per each bounding box class. In
# order to do this we first reshape the tensor so the last dimension contains probability for 2 classes
# (background and foreground) for each bounding box. Before feeding this tensor to the DO operation the tensor
# is flattened to the shape [num_batches, num_classes * num_bounding_boxes]
reshape_conf = create_op_node_with_second_input(graph, Reshape, int64_array([0, -1, 2]),
dict(name='predictions/Reshape'))
# transpose from NCHW to NHWC will be inserted as input to the Reshape automatically. This is expected
class_conf.out_port(0).disconnect()
class_conf.out_port(0).connect(reshape_conf.in_port(0))
softmax_conf = Softmax(graph, dict(axis=2, name=reshape_conf.id + '/Softmax')).create_node([reshape_conf])
flattened_conf = create_op_node_with_second_input(graph, Reshape, int64_array([0, -1]),
dict(name=softmax_conf.name + '/Flatten'), softmax_conf)
# prepare input with bounding boxes shape offsets
offsets = backward_bfs_for_operation(match.single_input_node(0)[0], ['Add'])[0]
flatten_offsets = create_op_node_with_second_input(graph, Reshape, int64_array([0, -1]),
dict(name=offsets.soft_get('name', offsets.id) + '/Flatten'),
offsets)
# TensorFlow produces anchor boxes in absolute coordinates in YXYX order. Need to normalize them to [0, 1]
# interval and append a tensor with variances. Refer to the ObjectDetectionAPISSDPostprocessorReplacement
# transformation comments about variances. The YXYX->XYXY order change will be performed with the output of the
# inserted DetectionOutput operation
yxyx_anchors = match.single_input_node(2)[0]
# get the input image height and width to divide the anchors values by it
initial_input_node_name = 'input_tensor' if 'input_tensor' in graph.nodes else 'image_tensor'
if initial_input_node_name not in graph.nodes():
raise Error('Input node "{}" of the graph is not found. Do not run the Model Optimizer with '
'"--input" command line parameter.'.format(initial_input_node_name))
parameter_node = Node(graph, initial_input_node_name)
input_shape = Shape(graph, {'name': parameter_node.name}).create_node([parameter_node])
input_image_hw = node_to_get_shape_value_of_indices(input_shape, [1, 2]) # NHWC layout
hwhw = create_op_with_const_inputs(graph, Tile, {1: int64_array([2])}, {'name': 'image_hwhw'}, input_image_hw)
hwhw_float = Cast(graph, {'dst_type': np.float32}).create_node([hwhw])
scaled_anchors = Div(graph, {'name': 'scaled_anchors'}).create_node([yxyx_anchors, hwhw_float])
flattened_anchors = create_op_with_const_inputs(graph, Reshape, {1: int64_array([1, 1, -1])},
{'name': 'flattened_anchors'}, scaled_anchors)
cropped_anchors = AttributedClamp(graph, {'min': 0.0, 'max': 1.0, 'name': 'clamped_yxyx',
'nchw_layout': True}).create_node([flattened_anchors])
# the input tensor "scaled_anchors" for the "flattened_anchors" may be 4D. In order to avoid inserting Transpose
# operation mark the "flattened_anchors" with the correct data layout
mark_as_correct_data_layout(flattened_anchors)
# create tensor of shape [4] with variance values which then are tiled by the number of boxes which is obtained
# from the 'yxyx_anchors' node
variances = Const(graph, {'value': _variance_from_pipeline_config(pipeline_config)}).create_node()
anchors_shape = Shape(graph, {'name': 'anchors_shape'}).create_node([yxyx_anchors])
anchors_count = node_to_get_shape_value_of_indices(anchors_shape, [0])
tiled_variances = Tile(graph, {'name': 'tiled_variances'}).create_node([variances, anchors_count])
reshaped_tiled_variances = create_op_with_const_inputs(graph, Reshape, {1: int64_array([1, 1, -1])},
{'name': 'flattened_variances'}, tiled_variances)
# now we can merge actual anchors coordinates with a tensor with variances as it is expected by the
# DetectionOutput operation
duplicate_anchors = Concat(graph, {'axis': 1, 'name': 'anchors_with_variances'}).create_node(
[cropped_anchors, reshaped_tiled_variances])
do = DetectionOutput(graph,
{'background_label_id': 0,
'clip_after_nms': True,
'clip_before_nms': False,
'code_type': 'caffe.PriorBoxParameter.CENTER_SIZE',
'confidence_threshold': 0.0,
'decrease_label_id': False,
'input_height': 1,
'input_width': 1,
'keep_top_k': max_proposals,
'normalized': True,
'objectness_score': 0,
'share_location': True,
'top_k': 6000,
'variance_encoded_in_target': False,
'nms_threshold': _value_or_raise(match, pipeline_config, 'first_stage_nms_iou_threshold'),
'name': 'first_do',
}).create_node([flatten_offsets, flattened_conf, duplicate_anchors])
# DetectionOutput output tensor has YXYX box coordinates order
# switch to 3D to avoid issues that part of the model with 4D shapes should be inferred in NCHW layout
do_3d = create_op_with_const_inputs(graph, Squeeze, {1: int64_array(0)}, {'name': do.name + '/SqueezeDO'}, do)
mark_as_correct_data_layout(do_3d)
# DetectionOutput output tensor produces a tensor of tuples with the following 7 elements:
# [batch_id, class_id, confidence, x1, y1, x2, y2]. Here we split the DetectionOutput result into the 7
# tensors with each of these elements for predictions. Then we crop predicted box coordinates (scaled) to be
# within [0, 1] range (as it is predicted in the TF model) and then combine tensors back to the Proposal
# operation output format: [batch_id, x1, y1, x2, y2].
do_split = create_op_node_with_second_input(graph, Split, int64_array(2), {'num_splits': 7,
'name': do.name + '/Split'}, do_3d)
coords = Concat(graph, {'axis': -1, 'in_ports_count': 4, 'name': do_split.name + '/coords'}).create_node()
# concat bounding boxes with the same order (XYXY) as Proposal produces
for port_idx in range(4):
do_split.out_port(3 + port_idx).connect(coords.in_port(port_idx))
clamped_coords = AttributedClamp(graph, {'min': 0.0, 'max': 1.0, 'name': 'clamped_xyxy'}).create_node([coords])
# prepare final proposal boxes [batch_id, x1, y1, x2, y2]
proposal_node = Concat(graph, {'axis': -1, 'in_ports_count': 2, 'name': 'proposals'}).create_node()
do_split.out_port(0).connect(proposal_node.in_port(0))
clamped_coords.out_port(0).connect(proposal_node.in_port(1))
return {'proposal_node': ObjectDetectionAPIProposalReplacement.ie_to_tf_proposals(graph, proposal_node, match,
pipeline_config,
max_proposals)} | [
"def",
"insert_detection_output_instead_of_proposal",
"(",
"graph",
":",
"Graph",
",",
"match",
":",
"SubgraphMatch",
",",
"pipeline_config",
":",
"PipelineConfig",
")",
":",
"max_proposals",
"=",
"_value_or_raise",
"(",
"match",
",",
"pipeline_config",
",",
"'first_stage_max_proposals'",
")",
"# Convolution/matmul node that produces classes confidence",
"# Transpose result of the tensor with classes confidences so it will be in a correct layout for Softmax",
"class_conf_nodes",
"=",
"backward_bfs_for_operation",
"(",
"match",
".",
"single_input_node",
"(",
"1",
")",
"[",
"0",
"]",
",",
"[",
"'Add'",
"]",
")",
"assert",
"len",
"(",
"class_conf_nodes",
")",
">=",
"1",
",",
"'Expected to find nodes of type \"Add\" starting from the node \"{}\" in '",
"'backward direction'",
".",
"format",
"(",
"match",
".",
"single_input_node",
"(",
"1",
")",
"[",
"0",
"]",
".",
"id",
")",
"class_conf",
"=",
"class_conf_nodes",
"[",
"0",
"]",
"# prepare input with class confidences. The DetectionOutput operation which will consume this tensor as a",
"# second input expects probabilities to be normalized with SoftMax operation per each bounding box class. In",
"# order to do this we first reshape the tensor so the last dimension contains probability for 2 classes",
"# (background and foreground) for each bounding box. Before feeding this tensor to the DO operation the tensor",
"# is flattened to the shape [num_batches, num_classes * num_bounding_boxes]",
"reshape_conf",
"=",
"create_op_node_with_second_input",
"(",
"graph",
",",
"Reshape",
",",
"int64_array",
"(",
"[",
"0",
",",
"-",
"1",
",",
"2",
"]",
")",
",",
"dict",
"(",
"name",
"=",
"'predictions/Reshape'",
")",
")",
"# transpose from NCHW to NHWC will be inserted as input to the Reshape automatically. This is expected",
"class_conf",
".",
"out_port",
"(",
"0",
")",
".",
"disconnect",
"(",
")",
"class_conf",
".",
"out_port",
"(",
"0",
")",
".",
"connect",
"(",
"reshape_conf",
".",
"in_port",
"(",
"0",
")",
")",
"softmax_conf",
"=",
"Softmax",
"(",
"graph",
",",
"dict",
"(",
"axis",
"=",
"2",
",",
"name",
"=",
"reshape_conf",
".",
"id",
"+",
"'/Softmax'",
")",
")",
".",
"create_node",
"(",
"[",
"reshape_conf",
"]",
")",
"flattened_conf",
"=",
"create_op_node_with_second_input",
"(",
"graph",
",",
"Reshape",
",",
"int64_array",
"(",
"[",
"0",
",",
"-",
"1",
"]",
")",
",",
"dict",
"(",
"name",
"=",
"softmax_conf",
".",
"name",
"+",
"'/Flatten'",
")",
",",
"softmax_conf",
")",
"# prepare input with bounding boxes shape offsets",
"offsets",
"=",
"backward_bfs_for_operation",
"(",
"match",
".",
"single_input_node",
"(",
"0",
")",
"[",
"0",
"]",
",",
"[",
"'Add'",
"]",
")",
"[",
"0",
"]",
"flatten_offsets",
"=",
"create_op_node_with_second_input",
"(",
"graph",
",",
"Reshape",
",",
"int64_array",
"(",
"[",
"0",
",",
"-",
"1",
"]",
")",
",",
"dict",
"(",
"name",
"=",
"offsets",
".",
"soft_get",
"(",
"'name'",
",",
"offsets",
".",
"id",
")",
"+",
"'/Flatten'",
")",
",",
"offsets",
")",
"# TensorFlow produces anchor boxes in absolute coordinates in YXYX order. Need to normalize them to [0, 1]",
"# interval and append a tensor with variances. Refer to the ObjectDetectionAPISSDPostprocessorReplacement",
"# transformation comments about variances. The YXYX->XYXY order change will be performed with the output of the",
"# inserted DetectionOutput operation",
"yxyx_anchors",
"=",
"match",
".",
"single_input_node",
"(",
"2",
")",
"[",
"0",
"]",
"# get the input image height and width to divide the anchors values by it",
"initial_input_node_name",
"=",
"'input_tensor'",
"if",
"'input_tensor'",
"in",
"graph",
".",
"nodes",
"else",
"'image_tensor'",
"if",
"initial_input_node_name",
"not",
"in",
"graph",
".",
"nodes",
"(",
")",
":",
"raise",
"Error",
"(",
"'Input node \"{}\" of the graph is not found. Do not run the Model Optimizer with '",
"'\"--input\" command line parameter.'",
".",
"format",
"(",
"initial_input_node_name",
")",
")",
"parameter_node",
"=",
"Node",
"(",
"graph",
",",
"initial_input_node_name",
")",
"input_shape",
"=",
"Shape",
"(",
"graph",
",",
"{",
"'name'",
":",
"parameter_node",
".",
"name",
"}",
")",
".",
"create_node",
"(",
"[",
"parameter_node",
"]",
")",
"input_image_hw",
"=",
"node_to_get_shape_value_of_indices",
"(",
"input_shape",
",",
"[",
"1",
",",
"2",
"]",
")",
"# NHWC layout",
"hwhw",
"=",
"create_op_with_const_inputs",
"(",
"graph",
",",
"Tile",
",",
"{",
"1",
":",
"int64_array",
"(",
"[",
"2",
"]",
")",
"}",
",",
"{",
"'name'",
":",
"'image_hwhw'",
"}",
",",
"input_image_hw",
")",
"hwhw_float",
"=",
"Cast",
"(",
"graph",
",",
"{",
"'dst_type'",
":",
"np",
".",
"float32",
"}",
")",
".",
"create_node",
"(",
"[",
"hwhw",
"]",
")",
"scaled_anchors",
"=",
"Div",
"(",
"graph",
",",
"{",
"'name'",
":",
"'scaled_anchors'",
"}",
")",
".",
"create_node",
"(",
"[",
"yxyx_anchors",
",",
"hwhw_float",
"]",
")",
"flattened_anchors",
"=",
"create_op_with_const_inputs",
"(",
"graph",
",",
"Reshape",
",",
"{",
"1",
":",
"int64_array",
"(",
"[",
"1",
",",
"1",
",",
"-",
"1",
"]",
")",
"}",
",",
"{",
"'name'",
":",
"'flattened_anchors'",
"}",
",",
"scaled_anchors",
")",
"cropped_anchors",
"=",
"AttributedClamp",
"(",
"graph",
",",
"{",
"'min'",
":",
"0.0",
",",
"'max'",
":",
"1.0",
",",
"'name'",
":",
"'clamped_yxyx'",
",",
"'nchw_layout'",
":",
"True",
"}",
")",
".",
"create_node",
"(",
"[",
"flattened_anchors",
"]",
")",
"# the input tensor \"scaled_anchors\" for the \"flattened_anchors\" may be 4D. In order to avoid inserting Transpose",
"# operation mark the \"flattened_anchors\" with the correct data layout",
"mark_as_correct_data_layout",
"(",
"flattened_anchors",
")",
"# create tensor of shape [4] with variance values which then are tiled by the number of boxes which is obtained",
"# from the 'yxyx_anchors' node",
"variances",
"=",
"Const",
"(",
"graph",
",",
"{",
"'value'",
":",
"_variance_from_pipeline_config",
"(",
"pipeline_config",
")",
"}",
")",
".",
"create_node",
"(",
")",
"anchors_shape",
"=",
"Shape",
"(",
"graph",
",",
"{",
"'name'",
":",
"'anchors_shape'",
"}",
")",
".",
"create_node",
"(",
"[",
"yxyx_anchors",
"]",
")",
"anchors_count",
"=",
"node_to_get_shape_value_of_indices",
"(",
"anchors_shape",
",",
"[",
"0",
"]",
")",
"tiled_variances",
"=",
"Tile",
"(",
"graph",
",",
"{",
"'name'",
":",
"'tiled_variances'",
"}",
")",
".",
"create_node",
"(",
"[",
"variances",
",",
"anchors_count",
"]",
")",
"reshaped_tiled_variances",
"=",
"create_op_with_const_inputs",
"(",
"graph",
",",
"Reshape",
",",
"{",
"1",
":",
"int64_array",
"(",
"[",
"1",
",",
"1",
",",
"-",
"1",
"]",
")",
"}",
",",
"{",
"'name'",
":",
"'flattened_variances'",
"}",
",",
"tiled_variances",
")",
"# now we can merge actual anchors coordinates with a tensor with variances as it is expected by the",
"# DetectionOutput operation",
"duplicate_anchors",
"=",
"Concat",
"(",
"graph",
",",
"{",
"'axis'",
":",
"1",
",",
"'name'",
":",
"'anchors_with_variances'",
"}",
")",
".",
"create_node",
"(",
"[",
"cropped_anchors",
",",
"reshaped_tiled_variances",
"]",
")",
"do",
"=",
"DetectionOutput",
"(",
"graph",
",",
"{",
"'background_label_id'",
":",
"0",
",",
"'clip_after_nms'",
":",
"True",
",",
"'clip_before_nms'",
":",
"False",
",",
"'code_type'",
":",
"'caffe.PriorBoxParameter.CENTER_SIZE'",
",",
"'confidence_threshold'",
":",
"0.0",
",",
"'decrease_label_id'",
":",
"False",
",",
"'input_height'",
":",
"1",
",",
"'input_width'",
":",
"1",
",",
"'keep_top_k'",
":",
"max_proposals",
",",
"'normalized'",
":",
"True",
",",
"'objectness_score'",
":",
"0",
",",
"'share_location'",
":",
"True",
",",
"'top_k'",
":",
"6000",
",",
"'variance_encoded_in_target'",
":",
"False",
",",
"'nms_threshold'",
":",
"_value_or_raise",
"(",
"match",
",",
"pipeline_config",
",",
"'first_stage_nms_iou_threshold'",
")",
",",
"'name'",
":",
"'first_do'",
",",
"}",
")",
".",
"create_node",
"(",
"[",
"flatten_offsets",
",",
"flattened_conf",
",",
"duplicate_anchors",
"]",
")",
"# DetectionOutput output tensor has YXYX box coordinates order",
"# switch to 3D to avoid issues that part of the model with 4D shapes should be inferred in NCHW layout",
"do_3d",
"=",
"create_op_with_const_inputs",
"(",
"graph",
",",
"Squeeze",
",",
"{",
"1",
":",
"int64_array",
"(",
"0",
")",
"}",
",",
"{",
"'name'",
":",
"do",
".",
"name",
"+",
"'/SqueezeDO'",
"}",
",",
"do",
")",
"mark_as_correct_data_layout",
"(",
"do_3d",
")",
"# DetectionOutput output tensor produces a tensor of tuples with the following 7 elements:",
"# [batch_id, class_id, confidence, x1, y1, x2, y2]. Here we split the DetectionOutput result into the 7",
"# tensors with each of these elements for predictions. Then we crop predicted box coordinates (scaled) to be",
"# within [0, 1] range (as it is predicted in the TF model) and then combine tensors back to the Proposal",
"# operation output format: [batch_id, x1, y1, x2, y2].",
"do_split",
"=",
"create_op_node_with_second_input",
"(",
"graph",
",",
"Split",
",",
"int64_array",
"(",
"2",
")",
",",
"{",
"'num_splits'",
":",
"7",
",",
"'name'",
":",
"do",
".",
"name",
"+",
"'/Split'",
"}",
",",
"do_3d",
")",
"coords",
"=",
"Concat",
"(",
"graph",
",",
"{",
"'axis'",
":",
"-",
"1",
",",
"'in_ports_count'",
":",
"4",
",",
"'name'",
":",
"do_split",
".",
"name",
"+",
"'/coords'",
"}",
")",
".",
"create_node",
"(",
")",
"# concat bounding boxes with the same order (XYXY) as Proposal produces",
"for",
"port_idx",
"in",
"range",
"(",
"4",
")",
":",
"do_split",
".",
"out_port",
"(",
"3",
"+",
"port_idx",
")",
".",
"connect",
"(",
"coords",
".",
"in_port",
"(",
"port_idx",
")",
")",
"clamped_coords",
"=",
"AttributedClamp",
"(",
"graph",
",",
"{",
"'min'",
":",
"0.0",
",",
"'max'",
":",
"1.0",
",",
"'name'",
":",
"'clamped_xyxy'",
"}",
")",
".",
"create_node",
"(",
"[",
"coords",
"]",
")",
"# prepare final proposal boxes [batch_id, x1, y1, x2, y2]",
"proposal_node",
"=",
"Concat",
"(",
"graph",
",",
"{",
"'axis'",
":",
"-",
"1",
",",
"'in_ports_count'",
":",
"2",
",",
"'name'",
":",
"'proposals'",
"}",
")",
".",
"create_node",
"(",
")",
"do_split",
".",
"out_port",
"(",
"0",
")",
".",
"connect",
"(",
"proposal_node",
".",
"in_port",
"(",
"0",
")",
")",
"clamped_coords",
".",
"out_port",
"(",
"0",
")",
".",
"connect",
"(",
"proposal_node",
".",
"in_port",
"(",
"1",
")",
")",
"return",
"{",
"'proposal_node'",
":",
"ObjectDetectionAPIProposalReplacement",
".",
"ie_to_tf_proposals",
"(",
"graph",
",",
"proposal_node",
",",
"match",
",",
"pipeline_config",
",",
"max_proposals",
")",
"}"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/tf/ObjectDetectionAPI.py#L1364-L1492 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/lib2to3/pgen2/parse.py | python | Parser.push | (self, type, newdfa, newstate, context) | Push a nonterminal. (Internal) | Push a nonterminal. (Internal) | [
"Push",
"a",
"nonterminal",
".",
"(",
"Internal",
")"
] | def push(self, type, newdfa, newstate, context):
"""Push a nonterminal. (Internal)"""
dfa, state, node = self.stack[-1]
newnode = (type, None, context, [])
self.stack[-1] = (dfa, newstate, node)
self.stack.append((newdfa, 0, newnode)) | [
"def",
"push",
"(",
"self",
",",
"type",
",",
"newdfa",
",",
"newstate",
",",
"context",
")",
":",
"dfa",
",",
"state",
",",
"node",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"newnode",
"=",
"(",
"type",
",",
"None",
",",
"context",
",",
"[",
"]",
")",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"=",
"(",
"dfa",
",",
"newstate",
",",
"node",
")",
"self",
".",
"stack",
".",
"append",
"(",
"(",
"newdfa",
",",
"0",
",",
"newnode",
")",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/pgen2/parse.py#L184-L189 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/jinja2/compiler.py | python | CodeGenerator.pull_locals | (self, frame) | Pull all the references identifiers into the local scope. | Pull all the references identifiers into the local scope. | [
"Pull",
"all",
"the",
"references",
"identifiers",
"into",
"the",
"local",
"scope",
"."
] | def pull_locals(self, frame):
"""Pull all the references identifiers into the local scope."""
for name in frame.identifiers.undeclared:
self.writeline('l_%s = context.resolve(%r)' % (name, name)) | [
"def",
"pull_locals",
"(",
"self",
",",
"frame",
")",
":",
"for",
"name",
"in",
"frame",
".",
"identifiers",
".",
"undeclared",
":",
"self",
".",
"writeline",
"(",
"'l_%s = context.resolve(%r)'",
"%",
"(",
"name",
",",
"name",
")",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/compiler.py#L574-L577 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | Dataset.AddFieldDomain | (self, *args) | return _gdal.Dataset_AddFieldDomain(self, *args) | r"""AddFieldDomain(Dataset self, FieldDomain fieldDomain) -> bool | r"""AddFieldDomain(Dataset self, FieldDomain fieldDomain) -> bool | [
"r",
"AddFieldDomain",
"(",
"Dataset",
"self",
"FieldDomain",
"fieldDomain",
")",
"-",
">",
"bool"
] | def AddFieldDomain(self, *args):
r"""AddFieldDomain(Dataset self, FieldDomain fieldDomain) -> bool"""
return _gdal.Dataset_AddFieldDomain(self, *args) | [
"def",
"AddFieldDomain",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"Dataset_AddFieldDomain",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L2325-L2327 | |
nnrg/opennero | 43e12a1bcba6e228639db3886fec1dc47ddc24cb | mods/Maze/client.py | python | pauseAgent | (ui) | return closure | return a function that pauses and continues the agent | return a function that pauses and continues the agent | [
"return",
"a",
"function",
"that",
"pauses",
"and",
"continues",
"the",
"agent"
] | def pauseAgent(ui):
""" return a function that pauses and continues the agent """
def closure():
"""pauses and continues the agent"""
if ui.pauseAgentButton.text == 'Continue':
ui.pauseAgentButton.text = 'Pause'
enable_ai()
else:
ui.pauseAgentButton.text = 'Continue'
disable_ai()
return closure | [
"def",
"pauseAgent",
"(",
"ui",
")",
":",
"def",
"closure",
"(",
")",
":",
"\"\"\"pauses and continues the agent\"\"\"",
"if",
"ui",
".",
"pauseAgentButton",
".",
"text",
"==",
"'Continue'",
":",
"ui",
".",
"pauseAgentButton",
".",
"text",
"=",
"'Pause'",
"enable_ai",
"(",
")",
"else",
":",
"ui",
".",
"pauseAgentButton",
".",
"text",
"=",
"'Continue'",
"disable_ai",
"(",
")",
"return",
"closure"
] | https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Maze/client.py#L211-L221 | |
nileshkulkarni/csm | 0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc | csm/utils/transformations.py | python | vector_product | (v0, v1, axis=0) | return numpy.cross(v0, v1, axis=axis) | Return vector perpendicular to vectors.
>>> v = vector_product([2, 0, 0], [0, 3, 0])
>>> numpy.allclose(v, [0, 0, 6])
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> v = vector_product(v0, v1)
>>> numpy.allclose(v, [[0, 0, 0, 0], [0, 0, 6, 6], [0, -6, 0, -6]])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> v = vector_product(v0, v1, axis=1)
>>> numpy.allclose(v, [[0, 0, 6], [0, -6, 0], [6, 0, 0], [0, -6, 6]])
True | Return vector perpendicular to vectors. | [
"Return",
"vector",
"perpendicular",
"to",
"vectors",
"."
] | def vector_product(v0, v1, axis=0):
"""Return vector perpendicular to vectors.
>>> v = vector_product([2, 0, 0], [0, 3, 0])
>>> numpy.allclose(v, [0, 0, 6])
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> v = vector_product(v0, v1)
>>> numpy.allclose(v, [[0, 0, 0, 0], [0, 0, 6, 6], [0, -6, 0, -6]])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> v = vector_product(v0, v1, axis=1)
>>> numpy.allclose(v, [[0, 0, 6], [0, -6, 0], [6, 0, 0], [0, -6, 6]])
True
"""
return numpy.cross(v0, v1, axis=axis) | [
"def",
"vector_product",
"(",
"v0",
",",
"v1",
",",
"axis",
"=",
"0",
")",
":",
"return",
"numpy",
".",
"cross",
"(",
"v0",
",",
"v1",
",",
"axis",
"=",
"axis",
")"
] | https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/utils/transformations.py#L1786-L1804 | |
Vipermdl/OCR_detection_IC15 | 8eebd353d6fac97f5832a138d7af3bd3071670db | base/base_data_loader.py | python | BaseDataLoader.__len__ | (self) | return self._n_samples() // self.batch_size | :return: Total number of batches | :return: Total number of batches | [
":",
"return",
":",
"Total",
"number",
"of",
"batches"
] | def __len__(self):
"""
:return: Total number of batches
"""
return self._n_samples() // self.batch_size | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_n_samples",
"(",
")",
"//",
"self",
".",
"batch_size"
] | https://github.com/Vipermdl/OCR_detection_IC15/blob/8eebd353d6fac97f5832a138d7af3bd3071670db/base/base_data_loader.py#L38-L42 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html2.py | python | WebView.SetEditable | (*args, **kwargs) | return _html2.WebView_SetEditable(*args, **kwargs) | SetEditable(self, bool enable=True) | SetEditable(self, bool enable=True) | [
"SetEditable",
"(",
"self",
"bool",
"enable",
"=",
"True",
")"
] | def SetEditable(*args, **kwargs):
"""SetEditable(self, bool enable=True)"""
return _html2.WebView_SetEditable(*args, **kwargs) | [
"def",
"SetEditable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html2",
".",
"WebView_SetEditable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html2.py#L199-L201 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py | python | BaseContext.get_logger | (self) | return get_logger() | Return package logger -- if it does not already exist then
it is created. | Return package logger -- if it does not already exist then
it is created. | [
"Return",
"package",
"logger",
"--",
"if",
"it",
"does",
"not",
"already",
"exist",
"then",
"it",
"is",
"created",
"."
] | def get_logger(self):
'''Return package logger -- if it does not already exist then
it is created.
'''
from .util import get_logger
return get_logger() | [
"def",
"get_logger",
"(",
"self",
")",
":",
"from",
".",
"util",
"import",
"get_logger",
"return",
"get_logger",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py#L151-L156 | |
cinder/Cinder | e83f5bb9c01a63eec20168d02953a0879e5100f7 | docs/libs/pystache/context.py | python | ContextStack._get_simple | (self, name) | Query the stack for a non-dotted name. | Query the stack for a non-dotted name. | [
"Query",
"the",
"stack",
"for",
"a",
"non",
"-",
"dotted",
"name",
"."
] | def _get_simple(self, name):
"""
Query the stack for a non-dotted name.
"""
for item in reversed(self._stack):
result = _get_value(item, name)
if result is not _NOT_FOUND:
return result
raise KeyNotFoundError(name, "part missing") | [
"def",
"_get_simple",
"(",
"self",
",",
"name",
")",
":",
"for",
"item",
"in",
"reversed",
"(",
"self",
".",
"_stack",
")",
":",
"result",
"=",
"_get_value",
"(",
"item",
",",
"name",
")",
"if",
"result",
"is",
"not",
"_NOT_FOUND",
":",
"return",
"result",
"raise",
"KeyNotFoundError",
"(",
"name",
",",
"\"part missing\"",
")"
] | https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/pystache/context.py#L304-L314 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/multi_threads_helpers.py | python | IntegratePeaksThread.set_integrated_peak_info | (self, scan_number, peak_integration_dict) | return | set the integrated peak information including
* calculate Lorentz correction
* add the integration result dictionary
* add motor step information
:return: | set the integrated peak information including
* calculate Lorentz correction
* add the integration result dictionary
* add motor step information
:return: | [
"set",
"the",
"integrated",
"peak",
"information",
"including",
"*",
"calculate",
"Lorentz",
"correction",
"*",
"add",
"the",
"integration",
"result",
"dictionary",
"*",
"add",
"motor",
"step",
"information",
":",
"return",
":"
] | def set_integrated_peak_info(self, scan_number, peak_integration_dict):
"""
set the integrated peak information including
* calculate Lorentz correction
* add the integration result dictionary
* add motor step information
:return:
"""
# get peak information
peak_info_obj = self._mainWindow.controller.get_peak_info(self._expNumber, scan_number)
# get Q-vector of the peak center and calculate |Q| from it
peak_center_q = peak_info_obj.get_peak_centre_v3d().norm()
# get wave length
wavelength = self._mainWindow.controller.get_wave_length(self._expNumber, [scan_number])
# get motor step (choose from omega, phi and chi)
try:
motor_move_tup = self._mainWindow.controller.get_motor_step(self._expNumber, scan_number)
motor_name, motor_step, motor_std_dev = motor_move_tup
except RuntimeError as run_err:
return str(run_err)
except AssertionError as ass_err:
return str(ass_err)
# calculate lorentz correction
# TODO/FIXME/NOW2 : peak center Q shall be from calculation!
lorentz_factor = peak_integration_utility.calculate_lorentz_correction_factor(peak_center_q, wavelength,
motor_step)
peak_info_obj.lorentz_correction_factor = lorentz_factor
# set motor
peak_info_obj.set_motor(motor_name, motor_step, motor_std_dev)
# set peak integration dictionary
peak_info_obj.set_integration(peak_integration_dict)
return | [
"def",
"set_integrated_peak_info",
"(",
"self",
",",
"scan_number",
",",
"peak_integration_dict",
")",
":",
"# get peak information",
"peak_info_obj",
"=",
"self",
".",
"_mainWindow",
".",
"controller",
".",
"get_peak_info",
"(",
"self",
".",
"_expNumber",
",",
"scan_number",
")",
"# get Q-vector of the peak center and calculate |Q| from it",
"peak_center_q",
"=",
"peak_info_obj",
".",
"get_peak_centre_v3d",
"(",
")",
".",
"norm",
"(",
")",
"# get wave length",
"wavelength",
"=",
"self",
".",
"_mainWindow",
".",
"controller",
".",
"get_wave_length",
"(",
"self",
".",
"_expNumber",
",",
"[",
"scan_number",
"]",
")",
"# get motor step (choose from omega, phi and chi)",
"try",
":",
"motor_move_tup",
"=",
"self",
".",
"_mainWindow",
".",
"controller",
".",
"get_motor_step",
"(",
"self",
".",
"_expNumber",
",",
"scan_number",
")",
"motor_name",
",",
"motor_step",
",",
"motor_std_dev",
"=",
"motor_move_tup",
"except",
"RuntimeError",
"as",
"run_err",
":",
"return",
"str",
"(",
"run_err",
")",
"except",
"AssertionError",
"as",
"ass_err",
":",
"return",
"str",
"(",
"ass_err",
")",
"# calculate lorentz correction",
"# TODO/FIXME/NOW2 : peak center Q shall be from calculation!",
"lorentz_factor",
"=",
"peak_integration_utility",
".",
"calculate_lorentz_correction_factor",
"(",
"peak_center_q",
",",
"wavelength",
",",
"motor_step",
")",
"peak_info_obj",
".",
"lorentz_correction_factor",
"=",
"lorentz_factor",
"# set motor",
"peak_info_obj",
".",
"set_motor",
"(",
"motor_name",
",",
"motor_step",
",",
"motor_std_dev",
")",
"# set peak integration dictionary",
"peak_info_obj",
".",
"set_integration",
"(",
"peak_integration_dict",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/multi_threads_helpers.py#L315-L351 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | llvm/utils/lit/lit/llvm/subst.py | python | ToolSubst.__init__ | (self, key, command=None, pre=r'.-^/\<', post='-.', verbatim=False,
unresolved='warn', extra_args=None) | Construct a ToolSubst.
key: The text which is to be substituted.
command: The command to substitute when the key is matched. By default,
this will treat `key` as a tool name and search for it. If it is
a string, it is intereprted as an exact path. If it is an instance of
FindTool, the specified tool name is searched for on disk.
pre: If specified, the substitution will not find matches where
the character immediately preceding the word-boundary that begins
`key` is any of the characters in the string `pre`.
post: If specified, the substitution will not find matches where
the character immediately after the word-boundary that ends `key`
is any of the characters specified in the string `post`.
verbatim: If True, `key` is an exact regex that is passed to the
underlying substitution
unresolved: Action to take if the tool substitution cannot be
resolved. Valid values:
'warn' - log a warning but add the substitution anyway.
'fatal' - Exit the test suite and log a fatal error.
'break' - Don't add any of the substitutions from the current
group, and return a value indicating a failure.
'ignore' - Don't add the substitution, and don't log an error
extra_args: If specified, represents a list of arguments that will be
appended to the tool's substitution.
explicit_path: If specified, the exact path will be used as a substitution.
Otherwise, the tool will be searched for as if by calling which(tool) | Construct a ToolSubst. | [
"Construct",
"a",
"ToolSubst",
"."
] | def __init__(self, key, command=None, pre=r'.-^/\<', post='-.', verbatim=False,
unresolved='warn', extra_args=None):
"""Construct a ToolSubst.
key: The text which is to be substituted.
command: The command to substitute when the key is matched. By default,
this will treat `key` as a tool name and search for it. If it is
a string, it is intereprted as an exact path. If it is an instance of
FindTool, the specified tool name is searched for on disk.
pre: If specified, the substitution will not find matches where
the character immediately preceding the word-boundary that begins
`key` is any of the characters in the string `pre`.
post: If specified, the substitution will not find matches where
the character immediately after the word-boundary that ends `key`
is any of the characters specified in the string `post`.
verbatim: If True, `key` is an exact regex that is passed to the
underlying substitution
unresolved: Action to take if the tool substitution cannot be
resolved. Valid values:
'warn' - log a warning but add the substitution anyway.
'fatal' - Exit the test suite and log a fatal error.
'break' - Don't add any of the substitutions from the current
group, and return a value indicating a failure.
'ignore' - Don't add the substitution, and don't log an error
extra_args: If specified, represents a list of arguments that will be
appended to the tool's substitution.
explicit_path: If specified, the exact path will be used as a substitution.
Otherwise, the tool will be searched for as if by calling which(tool)
"""
self.unresolved = unresolved
self.extra_args = extra_args
self.key = key
self.command = command if command is not None else FindTool(key)
self.was_resolved = False
if verbatim:
self.regex = key
return
def not_in(chars, where=''):
if not chars:
return ''
pattern_str = '|'.join(re.escape(x) for x in chars)
return r'(?{}!({}))'.format(where, pattern_str)
def wordify(word):
match = wordifier.match(word)
introducer = match.group(1)
word = match.group(2)
return introducer + r'\b' + word + r'\b'
self.regex = not_in(pre, '<') + wordify(key) + not_in(post) | [
"def",
"__init__",
"(",
"self",
",",
"key",
",",
"command",
"=",
"None",
",",
"pre",
"=",
"r'.-^/\\<'",
",",
"post",
"=",
"'-.'",
",",
"verbatim",
"=",
"False",
",",
"unresolved",
"=",
"'warn'",
",",
"extra_args",
"=",
"None",
")",
":",
"self",
".",
"unresolved",
"=",
"unresolved",
"self",
".",
"extra_args",
"=",
"extra_args",
"self",
".",
"key",
"=",
"key",
"self",
".",
"command",
"=",
"command",
"if",
"command",
"is",
"not",
"None",
"else",
"FindTool",
"(",
"key",
")",
"self",
".",
"was_resolved",
"=",
"False",
"if",
"verbatim",
":",
"self",
".",
"regex",
"=",
"key",
"return",
"def",
"not_in",
"(",
"chars",
",",
"where",
"=",
"''",
")",
":",
"if",
"not",
"chars",
":",
"return",
"''",
"pattern_str",
"=",
"'|'",
".",
"join",
"(",
"re",
".",
"escape",
"(",
"x",
")",
"for",
"x",
"in",
"chars",
")",
"return",
"r'(?{}!({}))'",
".",
"format",
"(",
"where",
",",
"pattern_str",
")",
"def",
"wordify",
"(",
"word",
")",
":",
"match",
"=",
"wordifier",
".",
"match",
"(",
"word",
")",
"introducer",
"=",
"match",
".",
"group",
"(",
"1",
")",
"word",
"=",
"match",
".",
"group",
"(",
"2",
")",
"return",
"introducer",
"+",
"r'\\b'",
"+",
"word",
"+",
"r'\\b'",
"self",
".",
"regex",
"=",
"not_in",
"(",
"pre",
",",
"'<'",
")",
"+",
"wordify",
"(",
"key",
")",
"+",
"not_in",
"(",
"post",
")"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/utils/lit/lit/llvm/subst.py#L42-L100 | ||
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetCflagsCC | (self, config) | return ['/TP'] + self._GetPchFlags(config, '.cc') | Returns the flags that need to be added to .cc compilations. | Returns the flags that need to be added to .cc compilations. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"cc",
"compilations",
"."
] | def GetCflagsCC(self, config):
"""Returns the flags that need to be added to .cc compilations."""
config = self._TargetConfig(config)
return ['/TP'] + self._GetPchFlags(config, '.cc') | [
"def",
"GetCflagsCC",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"return",
"[",
"'/TP'",
"]",
"+",
"self",
".",
"_GetPchFlags",
"(",
"config",
",",
"'.cc'",
")"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/msvs_emulation.py#L496-L499 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/wrappers/framework.py | python | NonInteractiveDebugWrapperSession.prepare_run_debug_urls | (self, fetches, feed_dict) | Abstract method to be implemented by concrete subclasses.
This method prepares the run-specific debug URL(s).
Args:
fetches: Same as the `fetches` argument to `Session.run()`
feed_dict: Same as the `feed_dict` argument to `Session.run()`
Returns:
debug_urls: (`str` or `list` of `str`) Debug URLs to be used in
this `Session.run()` call. | Abstract method to be implemented by concrete subclasses. | [
"Abstract",
"method",
"to",
"be",
"implemented",
"by",
"concrete",
"subclasses",
"."
] | def prepare_run_debug_urls(self, fetches, feed_dict):
"""Abstract method to be implemented by concrete subclasses.
This method prepares the run-specific debug URL(s).
Args:
fetches: Same as the `fetches` argument to `Session.run()`
feed_dict: Same as the `feed_dict` argument to `Session.run()`
Returns:
debug_urls: (`str` or `list` of `str`) Debug URLs to be used in
this `Session.run()` call.
""" | [
"def",
"prepare_run_debug_urls",
"(",
"self",
",",
"fetches",
",",
"feed_dict",
")",
":"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/wrappers/framework.py#L799-L811 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/gdal-utils/osgeo_utils/auxiliary/base.py | python | get_byte | (number: int, i: int) | return (number & (0xff << (i * 8))) >> (i * 8) | returns the i-th byte from an integer | returns the i-th byte from an integer | [
"returns",
"the",
"i",
"-",
"th",
"byte",
"from",
"an",
"integer"
] | def get_byte(number: int, i: int):
""" returns the i-th byte from an integer"""
return (number & (0xff << (i * 8))) >> (i * 8) | [
"def",
"get_byte",
"(",
"number",
":",
"int",
",",
"i",
":",
"int",
")",
":",
"return",
"(",
"number",
"&",
"(",
"0xff",
"<<",
"(",
"i",
"*",
"8",
")",
")",
")",
">>",
"(",
"i",
"*",
"8",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/gdal-utils/osgeo_utils/auxiliary/base.py#L72-L74 | |
zeroc-ice/ice | 6df7df6039674d58fb5ab9a08e46f28591a210f7 | python/python/Ice/__init__.py | python | Value.ice_staticId | () | return '::Ice::Object' | Obtains the type id of this Slice class or interface.
Returns:
The type id. | Obtains the type id of this Slice class or interface.
Returns:
The type id. | [
"Obtains",
"the",
"type",
"id",
"of",
"this",
"Slice",
"class",
"or",
"interface",
".",
"Returns",
":",
"The",
"type",
"id",
"."
] | def ice_staticId():
'''Obtains the type id of this Slice class or interface.
Returns:
The type id.
'''
return '::Ice::Object' | [
"def",
"ice_staticId",
"(",
")",
":",
"return",
"'::Ice::Object'"
] | https://github.com/zeroc-ice/ice/blob/6df7df6039674d58fb5ab9a08e46f28591a210f7/python/python/Ice/__init__.py#L334-L339 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/hang_analyzer/dumper.py | python | Dumper.__init__ | (self, root_logger: logging.Logger, dbg_output: str) | Initialize dumper. | Initialize dumper. | [
"Initialize",
"dumper",
"."
] | def __init__(self, root_logger: logging.Logger, dbg_output: str):
"""Initialize dumper."""
self._root_logger = root_logger
self._dbg_output = dbg_output | [
"def",
"__init__",
"(",
"self",
",",
"root_logger",
":",
"logging",
".",
"Logger",
",",
"dbg_output",
":",
"str",
")",
":",
"self",
".",
"_root_logger",
"=",
"root_logger",
"self",
".",
"_dbg_output",
"=",
"dbg_output"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/hang_analyzer/dumper.py#L49-L52 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/skia/tools/copyright/fileparser.py | python | CParser.FindAllCommentBlocks | (self, file_contents) | return self._comment_pattern.findall(file_contents) | Returns a list of all comment blocks within these file contents. | Returns a list of all comment blocks within these file contents. | [
"Returns",
"a",
"list",
"of",
"all",
"comment",
"blocks",
"within",
"these",
"file",
"contents",
"."
] | def FindAllCommentBlocks(self, file_contents):
"""Returns a list of all comment blocks within these file contents.
"""
return self._comment_pattern.findall(file_contents) | [
"def",
"FindAllCommentBlocks",
"(",
"self",
",",
"file_contents",
")",
":",
"return",
"self",
".",
"_comment_pattern",
".",
"findall",
"(",
"file_contents",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/tools/copyright/fileparser.py#L76-L79 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/guess-the-majority-in-a-hidden-array.py | python | Solution.guessMajority | (self, reader) | return 3 if count_a > count_b else idx_b | :type reader: ArrayReader
:rtype: integer | :type reader: ArrayReader
:rtype: integer | [
":",
"type",
"reader",
":",
"ArrayReader",
":",
"rtype",
":",
"integer"
] | def guessMajority(self, reader):
"""
:type reader: ArrayReader
:rtype: integer
"""
count_a, count_b, idx_b = 1, 0, None
value_0_1_2_3 = reader.query(0, 1, 2, 3)
for i in reversed(xrange(4, reader.length())):
value_0_1_2_i = reader.query(0, 1, 2, i)
if value_0_1_2_i == value_0_1_2_3: # nums[i] == nums[3]
count_a = count_a+1
else:
count_b, idx_b = count_b+1, i
value_0_1_2_4 = value_0_1_2_i
for i in xrange(3):
value_a_b_3_4 = reader.query(*[v for v in [0, 1, 2, 3, 4] if v != i])
if value_a_b_3_4 == value_0_1_2_4: # nums[i] == nums[3]
count_a = count_a+1
else:
count_b, idx_b = count_b+1, i
if count_a == count_b:
return -1
return 3 if count_a > count_b else idx_b | [
"def",
"guessMajority",
"(",
"self",
",",
"reader",
")",
":",
"count_a",
",",
"count_b",
",",
"idx_b",
"=",
"1",
",",
"0",
",",
"None",
"value_0_1_2_3",
"=",
"reader",
".",
"query",
"(",
"0",
",",
"1",
",",
"2",
",",
"3",
")",
"for",
"i",
"in",
"reversed",
"(",
"xrange",
"(",
"4",
",",
"reader",
".",
"length",
"(",
")",
")",
")",
":",
"value_0_1_2_i",
"=",
"reader",
".",
"query",
"(",
"0",
",",
"1",
",",
"2",
",",
"i",
")",
"if",
"value_0_1_2_i",
"==",
"value_0_1_2_3",
":",
"# nums[i] == nums[3]",
"count_a",
"=",
"count_a",
"+",
"1",
"else",
":",
"count_b",
",",
"idx_b",
"=",
"count_b",
"+",
"1",
",",
"i",
"value_0_1_2_4",
"=",
"value_0_1_2_i",
"for",
"i",
"in",
"xrange",
"(",
"3",
")",
":",
"value_a_b_3_4",
"=",
"reader",
".",
"query",
"(",
"*",
"[",
"v",
"for",
"v",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
",",
"4",
"]",
"if",
"v",
"!=",
"i",
"]",
")",
"if",
"value_a_b_3_4",
"==",
"value_0_1_2_4",
":",
"# nums[i] == nums[3]",
"count_a",
"=",
"count_a",
"+",
"1",
"else",
":",
"count_b",
",",
"idx_b",
"=",
"count_b",
"+",
"1",
",",
"i",
"if",
"count_a",
"==",
"count_b",
":",
"return",
"-",
"1",
"return",
"3",
"if",
"count_a",
">",
"count_b",
"else",
"idx_b"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/guess-the-majority-in-a-hidden-array.py#L20-L42 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/msw/gizmos.py | python | TreeListColumnInfo.SetImage | (*args, **kwargs) | return _gizmos.TreeListColumnInfo_SetImage(*args, **kwargs) | SetImage(self, int image) | SetImage(self, int image) | [
"SetImage",
"(",
"self",
"int",
"image",
")"
] | def SetImage(*args, **kwargs):
"""SetImage(self, int image)"""
return _gizmos.TreeListColumnInfo_SetImage(*args, **kwargs) | [
"def",
"SetImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListColumnInfo_SetImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L440-L442 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/buttonpanel.py | python | ButtonInfo.Draw | (self, dc, rect) | Draws the button on :class:`ButtonPanel`. Actually the drawing is done in :class:`BPArt`.
:param `dc`: an instance of :class:`DC`;
:param Rect `rect`: the main caption text client rectangle. | Draws the button on :class:`ButtonPanel`. Actually the drawing is done in :class:`BPArt`. | [
"Draws",
"the",
"button",
"on",
":",
"class",
":",
"ButtonPanel",
".",
"Actually",
"the",
"drawing",
"is",
"done",
"in",
":",
"class",
":",
"BPArt",
"."
] | def Draw(self, dc, rect):
"""
Draws the button on :class:`ButtonPanel`. Actually the drawing is done in :class:`BPArt`.
:param `dc`: an instance of :class:`DC`;
:param Rect `rect`: the main caption text client rectangle.
"""
if not self.IsShown():
return
buttonBitmap = self.GetBitmap()
isVertical = self._parent.IsVertical()
text = self.GetText()
buttonStatus = self.GetStatus()
isToggled = self.GetToggled()
textAlignment = self.GetTextAlignment()
self._parent._art.DrawButton(dc, rect, buttonBitmap, isVertical,
buttonStatus, isToggled, textAlignment, text)
self.SetRect(rect) | [
"def",
"Draw",
"(",
"self",
",",
"dc",
",",
"rect",
")",
":",
"if",
"not",
"self",
".",
"IsShown",
"(",
")",
":",
"return",
"buttonBitmap",
"=",
"self",
".",
"GetBitmap",
"(",
")",
"isVertical",
"=",
"self",
".",
"_parent",
".",
"IsVertical",
"(",
")",
"text",
"=",
"self",
".",
"GetText",
"(",
")",
"buttonStatus",
"=",
"self",
".",
"GetStatus",
"(",
")",
"isToggled",
"=",
"self",
".",
"GetToggled",
"(",
")",
"textAlignment",
"=",
"self",
".",
"GetTextAlignment",
"(",
")",
"self",
".",
"_parent",
".",
"_art",
".",
"DrawButton",
"(",
"dc",
",",
"rect",
",",
"buttonBitmap",
",",
"isVertical",
",",
"buttonStatus",
",",
"isToggled",
",",
"textAlignment",
",",
"text",
")",
"self",
".",
"SetRect",
"(",
"rect",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L1458-L1479 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/nvmpic.py | python | NvmAccessProviderCmsisDapPic.read_device_id | (self) | return id_array | Get the device info from the device
:returns: Device ID raw bytes (Little endian) | Get the device info from the device | [
"Get",
"the",
"device",
"info",
"from",
"the",
"device"
] | def read_device_id(self):
"""
Get the device info from the device
:returns: Device ID raw bytes (Little endian)
"""
pic_id = self.pic.read_id()
id_array = binary.pack_le16(pic_id)
self.logger.info("Device ID read out: '%04X'", pic_id)
return id_array | [
"def",
"read_device_id",
"(",
"self",
")",
":",
"pic_id",
"=",
"self",
".",
"pic",
".",
"read_id",
"(",
")",
"id_array",
"=",
"binary",
".",
"pack_le16",
"(",
"pic_id",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Device ID read out: '%04X'\"",
",",
"pic_id",
")",
"return",
"id_array"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvmpic.py#L151-L160 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/distutils/cmd.py | python | Command.move_file | (self, src, dst, level=1) | return file_util.move_file(src, dst, dry_run=self.dry_run) | Move a file respecting dry-run flag. | Move a file respecting dry-run flag. | [
"Move",
"a",
"file",
"respecting",
"dry",
"-",
"run",
"flag",
"."
] | def move_file (self, src, dst, level=1):
"""Move a file respecting dry-run flag."""
return file_util.move_file(src, dst, dry_run=self.dry_run) | [
"def",
"move_file",
"(",
"self",
",",
"src",
",",
"dst",
",",
"level",
"=",
"1",
")",
":",
"return",
"file_util",
".",
"move_file",
"(",
"src",
",",
"dst",
",",
"dry_run",
"=",
"self",
".",
"dry_run",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/cmd.py#L358-L360 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Decimal.logical_or | (self, other, context=None) | return _dec_from_triple(0, result.lstrip('0') or '0', 0) | Applies an 'or' operation between self and other's digits. | Applies an 'or' operation between self and other's digits. | [
"Applies",
"an",
"or",
"operation",
"between",
"self",
"and",
"other",
"s",
"digits",
"."
] | def logical_or(self, other, context=None):
"""Applies an 'or' operation between self and other's digits."""
if context is None:
context = getcontext()
other = _convert_other(other, raiseit=True)
if not self._islogical() or not other._islogical():
return context._raise_error(InvalidOperation)
# fill to context.prec
(opa, opb) = self._fill_logical(context, self._int, other._int)
# make the operation, and clean starting zeroes
result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
return _dec_from_triple(0, result.lstrip('0') or '0', 0) | [
"def",
"logical_or",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"if",
"not",
"self",
".",
"_islogical",
"(",
")",
"or",
"not",
"other",
".",
"_islogical",
"(",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
")",
"# fill to context.prec",
"(",
"opa",
",",
"opb",
")",
"=",
"self",
".",
"_fill_logical",
"(",
"context",
",",
"self",
".",
"_int",
",",
"other",
".",
"_int",
")",
"# make the operation, and clean starting zeroes",
"result",
"=",
"\"\"",
".",
"join",
"(",
"[",
"str",
"(",
"int",
"(",
"a",
")",
"|",
"int",
"(",
"b",
")",
")",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"opa",
",",
"opb",
")",
"]",
")",
"return",
"_dec_from_triple",
"(",
"0",
",",
"result",
".",
"lstrip",
"(",
"'0'",
")",
"or",
"'0'",
",",
"0",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L3300-L3315 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pyassem.py | python | FlowGraph.getBlocksInOrder | (self) | return order | Return the blocks in reverse postorder
i.e. each node appears before all of its successors | Return the blocks in reverse postorder | [
"Return",
"the",
"blocks",
"in",
"reverse",
"postorder"
] | def getBlocksInOrder(self):
"""Return the blocks in reverse postorder
i.e. each node appears before all of its successors
"""
order = order_blocks(self.entry, self.exit)
return order | [
"def",
"getBlocksInOrder",
"(",
"self",
")",
":",
"order",
"=",
"order_blocks",
"(",
"self",
".",
"entry",
",",
"self",
".",
"exit",
")",
"return",
"order"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pyassem.py#L76-L82 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py | python | Logger.isEnabledFor | (self, level) | Is this logger enabled for level 'level'? | Is this logger enabled for level 'level'? | [
"Is",
"this",
"logger",
"enabled",
"for",
"level",
"level",
"?"
] | def isEnabledFor(self, level):
"""
Is this logger enabled for level 'level'?
"""
try:
return self._cache[level]
except KeyError:
_acquireLock()
try:
if self.manager.disable >= level:
is_enabled = self._cache[level] = False
else:
is_enabled = self._cache[level] = (
level >= self.getEffectiveLevel()
)
finally:
_releaseLock()
return is_enabled | [
"def",
"isEnabledFor",
"(",
"self",
",",
"level",
")",
":",
"try",
":",
"return",
"self",
".",
"_cache",
"[",
"level",
"]",
"except",
"KeyError",
":",
"_acquireLock",
"(",
")",
"try",
":",
"if",
"self",
".",
"manager",
".",
"disable",
">=",
"level",
":",
"is_enabled",
"=",
"self",
".",
"_cache",
"[",
"level",
"]",
"=",
"False",
"else",
":",
"is_enabled",
"=",
"self",
".",
"_cache",
"[",
"level",
"]",
"=",
"(",
"level",
">=",
"self",
".",
"getEffectiveLevel",
"(",
")",
")",
"finally",
":",
"_releaseLock",
"(",
")",
"return",
"is_enabled"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py#L1614-L1631 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathUtils.py | python | getOffsetArea | (
fcShape,
offset,
removeHoles=False,
# Default: XY plane
plane=Part.makeCircle(10),
tolerance=1e-4,
) | return offsetShape | Make an offset area of a shape, projected onto a plane.
Positive offsets expand the area, negative offsets shrink it.
Inspired by _buildPathArea() from PathAreaOp.py module. Adjustments made
based on notes by @sliptonic at this webpage:
https://github.com/sliptonic/FreeCAD/wiki/PathArea-notes. | Make an offset area of a shape, projected onto a plane.
Positive offsets expand the area, negative offsets shrink it.
Inspired by _buildPathArea() from PathAreaOp.py module. Adjustments made
based on notes by | [
"Make",
"an",
"offset",
"area",
"of",
"a",
"shape",
"projected",
"onto",
"a",
"plane",
".",
"Positive",
"offsets",
"expand",
"the",
"area",
"negative",
"offsets",
"shrink",
"it",
".",
"Inspired",
"by",
"_buildPathArea",
"()",
"from",
"PathAreaOp",
".",
"py",
"module",
".",
"Adjustments",
"made",
"based",
"on",
"notes",
"by"
] | def getOffsetArea(
fcShape,
offset,
removeHoles=False,
# Default: XY plane
plane=Part.makeCircle(10),
tolerance=1e-4,
):
"""Make an offset area of a shape, projected onto a plane.
Positive offsets expand the area, negative offsets shrink it.
Inspired by _buildPathArea() from PathAreaOp.py module. Adjustments made
based on notes by @sliptonic at this webpage:
https://github.com/sliptonic/FreeCAD/wiki/PathArea-notes."""
PathLog.debug("getOffsetArea()")
areaParams = {}
areaParams["Offset"] = offset
areaParams["Fill"] = 1 # 1
areaParams["Outline"] = removeHoles
areaParams["Coplanar"] = 0
areaParams["SectionCount"] = 1 # -1 = full(all per depthparams??) sections
areaParams["Reorient"] = True
areaParams["OpenMode"] = 0
areaParams["MaxArcPoints"] = 400 # 400
areaParams["Project"] = True
areaParams["FitArcs"] = False # Can be buggy & expensive
areaParams["Deflection"] = tolerance
areaParams["Accuracy"] = tolerance
areaParams["Tolerance"] = 1e-5 # Equal point tolerance
areaParams["Simplify"] = True
areaParams["CleanDistance"] = tolerance / 5
area = Path.Area() # Create instance of Area() class object
# Set working plane normal to Z=1
area.setPlane(makeWorkplane(plane))
area.add(fcShape)
area.setParams(**areaParams) # set parameters
offsetShape = area.getShape()
if not offsetShape.Faces:
return False
return offsetShape | [
"def",
"getOffsetArea",
"(",
"fcShape",
",",
"offset",
",",
"removeHoles",
"=",
"False",
",",
"# Default: XY plane",
"plane",
"=",
"Part",
".",
"makeCircle",
"(",
"10",
")",
",",
"tolerance",
"=",
"1e-4",
",",
")",
":",
"PathLog",
".",
"debug",
"(",
"\"getOffsetArea()\"",
")",
"areaParams",
"=",
"{",
"}",
"areaParams",
"[",
"\"Offset\"",
"]",
"=",
"offset",
"areaParams",
"[",
"\"Fill\"",
"]",
"=",
"1",
"# 1",
"areaParams",
"[",
"\"Outline\"",
"]",
"=",
"removeHoles",
"areaParams",
"[",
"\"Coplanar\"",
"]",
"=",
"0",
"areaParams",
"[",
"\"SectionCount\"",
"]",
"=",
"1",
"# -1 = full(all per depthparams??) sections",
"areaParams",
"[",
"\"Reorient\"",
"]",
"=",
"True",
"areaParams",
"[",
"\"OpenMode\"",
"]",
"=",
"0",
"areaParams",
"[",
"\"MaxArcPoints\"",
"]",
"=",
"400",
"# 400",
"areaParams",
"[",
"\"Project\"",
"]",
"=",
"True",
"areaParams",
"[",
"\"FitArcs\"",
"]",
"=",
"False",
"# Can be buggy & expensive",
"areaParams",
"[",
"\"Deflection\"",
"]",
"=",
"tolerance",
"areaParams",
"[",
"\"Accuracy\"",
"]",
"=",
"tolerance",
"areaParams",
"[",
"\"Tolerance\"",
"]",
"=",
"1e-5",
"# Equal point tolerance",
"areaParams",
"[",
"\"Simplify\"",
"]",
"=",
"True",
"areaParams",
"[",
"\"CleanDistance\"",
"]",
"=",
"tolerance",
"/",
"5",
"area",
"=",
"Path",
".",
"Area",
"(",
")",
"# Create instance of Area() class object",
"# Set working plane normal to Z=1",
"area",
".",
"setPlane",
"(",
"makeWorkplane",
"(",
"plane",
")",
")",
"area",
".",
"add",
"(",
"fcShape",
")",
"area",
".",
"setParams",
"(",
"*",
"*",
"areaParams",
")",
"# set parameters",
"offsetShape",
"=",
"area",
".",
"getShape",
"(",
")",
"if",
"not",
"offsetShape",
".",
"Faces",
":",
"return",
"False",
"return",
"offsetShape"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathUtils.py#L284-L325 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/MolStandardize/charge.py | python | Uncharger.uncharge | (self, mol) | return mol | Neutralize molecule by adding/removing hydrogens. Attempts to preserve zwitterions.
:param mol: The molecule to uncharge.
:type mol: :rdkit:`Mol <Chem.rdchem.Mol-class.html>`
:return: The uncharged molecule.
:rtype: :rdkit:`Mol <Chem.rdchem.Mol-class.html>` | Neutralize molecule by adding/removing hydrogens. Attempts to preserve zwitterions. | [
"Neutralize",
"molecule",
"by",
"adding",
"/",
"removing",
"hydrogens",
".",
"Attempts",
"to",
"preserve",
"zwitterions",
"."
] | def uncharge(self, mol):
"""Neutralize molecule by adding/removing hydrogens. Attempts to preserve zwitterions.
:param mol: The molecule to uncharge.
:type mol: :rdkit:`Mol <Chem.rdchem.Mol-class.html>`
:return: The uncharged molecule.
:rtype: :rdkit:`Mol <Chem.rdchem.Mol-class.html>`
"""
log.debug('Running Uncharger')
mol = copy.deepcopy(mol)
# Get atom ids for matches
p = [x[0] for x in mol.GetSubstructMatches(self._pos_h)]
q = [x[0] for x in mol.GetSubstructMatches(self._pos_quat)]
n = [x[0] for x in mol.GetSubstructMatches(self._neg)]
a = [x[0] for x in mol.GetSubstructMatches(self._neg_acid)]
# Neutralize negative charges
if q:
# Surplus negative charges more than non-neutralizable positive charges
neg_surplus = len(n) - len(q)
if a and neg_surplus > 0:
# zwitterion with more negative charges than quaternary positive centres
while neg_surplus > 0 and a:
# Add hydrogen to first negative acid atom, increase formal charge
# Until quaternary positive == negative total or no more negative acid
atom = mol.GetAtomWithIdx(a.pop(0))
atom.SetNumExplicitHs(atom.GetNumExplicitHs() + 1)
atom.SetFormalCharge(atom.GetFormalCharge() + 1)
neg_surplus -= 1
log.info('Removed negative charge')
else:
for atom in [mol.GetAtomWithIdx(x) for x in n]:
while atom.GetFormalCharge() < 0:
atom.SetNumExplicitHs(atom.GetNumExplicitHs() + 1)
atom.SetFormalCharge(atom.GetFormalCharge() + 1)
log.info('Removed negative charge')
# Neutralize positive charges
for atom in [mol.GetAtomWithIdx(x) for x in p]:
# Remove hydrogen and reduce formal change until neutral or no more hydrogens
while atom.GetFormalCharge() > 0 and atom.GetNumExplicitHs() > 0:
atom.SetNumExplicitHs(atom.GetNumExplicitHs() - 1)
atom.SetFormalCharge(atom.GetFormalCharge() - 1)
log.info('Removed positive charge')
return mol | [
"def",
"uncharge",
"(",
"self",
",",
"mol",
")",
":",
"log",
".",
"debug",
"(",
"'Running Uncharger'",
")",
"mol",
"=",
"copy",
".",
"deepcopy",
"(",
"mol",
")",
"# Get atom ids for matches",
"p",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"mol",
".",
"GetSubstructMatches",
"(",
"self",
".",
"_pos_h",
")",
"]",
"q",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"mol",
".",
"GetSubstructMatches",
"(",
"self",
".",
"_pos_quat",
")",
"]",
"n",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"mol",
".",
"GetSubstructMatches",
"(",
"self",
".",
"_neg",
")",
"]",
"a",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"mol",
".",
"GetSubstructMatches",
"(",
"self",
".",
"_neg_acid",
")",
"]",
"# Neutralize negative charges",
"if",
"q",
":",
"# Surplus negative charges more than non-neutralizable positive charges",
"neg_surplus",
"=",
"len",
"(",
"n",
")",
"-",
"len",
"(",
"q",
")",
"if",
"a",
"and",
"neg_surplus",
">",
"0",
":",
"# zwitterion with more negative charges than quaternary positive centres",
"while",
"neg_surplus",
">",
"0",
"and",
"a",
":",
"# Add hydrogen to first negative acid atom, increase formal charge",
"# Until quaternary positive == negative total or no more negative acid",
"atom",
"=",
"mol",
".",
"GetAtomWithIdx",
"(",
"a",
".",
"pop",
"(",
"0",
")",
")",
"atom",
".",
"SetNumExplicitHs",
"(",
"atom",
".",
"GetNumExplicitHs",
"(",
")",
"+",
"1",
")",
"atom",
".",
"SetFormalCharge",
"(",
"atom",
".",
"GetFormalCharge",
"(",
")",
"+",
"1",
")",
"neg_surplus",
"-=",
"1",
"log",
".",
"info",
"(",
"'Removed negative charge'",
")",
"else",
":",
"for",
"atom",
"in",
"[",
"mol",
".",
"GetAtomWithIdx",
"(",
"x",
")",
"for",
"x",
"in",
"n",
"]",
":",
"while",
"atom",
".",
"GetFormalCharge",
"(",
")",
"<",
"0",
":",
"atom",
".",
"SetNumExplicitHs",
"(",
"atom",
".",
"GetNumExplicitHs",
"(",
")",
"+",
"1",
")",
"atom",
".",
"SetFormalCharge",
"(",
"atom",
".",
"GetFormalCharge",
"(",
")",
"+",
"1",
")",
"log",
".",
"info",
"(",
"'Removed negative charge'",
")",
"# Neutralize positive charges",
"for",
"atom",
"in",
"[",
"mol",
".",
"GetAtomWithIdx",
"(",
"x",
")",
"for",
"x",
"in",
"p",
"]",
":",
"# Remove hydrogen and reduce formal change until neutral or no more hydrogens",
"while",
"atom",
".",
"GetFormalCharge",
"(",
")",
">",
"0",
"and",
"atom",
".",
"GetNumExplicitHs",
"(",
")",
">",
"0",
":",
"atom",
".",
"SetNumExplicitHs",
"(",
"atom",
".",
"GetNumExplicitHs",
"(",
")",
"-",
"1",
")",
"atom",
".",
"SetFormalCharge",
"(",
"atom",
".",
"GetFormalCharge",
"(",
")",
"-",
"1",
")",
"log",
".",
"info",
"(",
"'Removed positive charge'",
")",
"return",
"mol"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/MolStandardize/charge.py#L282-L326 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/framework/tensor_util.py | python | _GetDenseDimensions | (list_of_lists) | Returns the inferred dense dimensions of a list of lists. | Returns the inferred dense dimensions of a list of lists. | [
"Returns",
"the",
"inferred",
"dense",
"dimensions",
"of",
"a",
"list",
"of",
"lists",
"."
] | def _GetDenseDimensions(list_of_lists):
"""Returns the inferred dense dimensions of a list of lists."""
if not isinstance(list_of_lists, (list, tuple)):
return []
elif not list_of_lists:
return [0]
else:
return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0]) | [
"def",
"_GetDenseDimensions",
"(",
"list_of_lists",
")",
":",
"if",
"not",
"isinstance",
"(",
"list_of_lists",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"]",
"elif",
"not",
"list_of_lists",
":",
"return",
"[",
"0",
"]",
"else",
":",
"return",
"[",
"len",
"(",
"list_of_lists",
")",
"]",
"+",
"_GetDenseDimensions",
"(",
"list_of_lists",
"[",
"0",
"]",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/tensor_util.py#L170-L177 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ApplyPaalmanPingsCorrection.py | python | ApplyPaalmanPingsCorrection._get_factor_workspaces | (self) | return {factor: self._get_correction_factor_workspace(factor) for factor in self._factors} | :return: A dictionary of the factors to the factor workspaces. | :return: A dictionary of the factors to the factor workspaces. | [
":",
"return",
":",
"A",
"dictionary",
"of",
"the",
"factors",
"to",
"the",
"factor",
"workspaces",
"."
] | def _get_factor_workspaces(self):
"""
:return: A dictionary of the factors to the factor workspaces.
"""
return {factor: self._get_correction_factor_workspace(factor) for factor in self._factors} | [
"def",
"_get_factor_workspaces",
"(",
"self",
")",
":",
"return",
"{",
"factor",
":",
"self",
".",
"_get_correction_factor_workspace",
"(",
"factor",
")",
"for",
"factor",
"in",
"self",
".",
"_factors",
"}"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ApplyPaalmanPingsCorrection.py#L319-L323 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.is_pure_virtual_method | (self) | return conf.lib.clang_CXXMethod_isPureVirtual(self) | Returns True if the cursor refers to a C++ member function or member
function template that is declared pure virtual. | Returns True if the cursor refers to a C++ member function or member
function template that is declared pure virtual. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"member",
"function",
"or",
"member",
"function",
"template",
"that",
"is",
"declared",
"pure",
"virtual",
"."
] | def is_pure_virtual_method(self):
"""Returns True if the cursor refers to a C++ member function or member
function template that is declared pure virtual.
"""
return conf.lib.clang_CXXMethod_isPureVirtual(self) | [
"def",
"is_pure_virtual_method",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXMethod_isPureVirtual",
"(",
"self",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1464-L1468 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/filters.py | python | evalcontextfilter | (f) | return f | Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4 | Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`. | [
"Decorator",
"for",
"marking",
"eval",
"-",
"context",
"dependent",
"filters",
".",
"An",
"eval",
"context",
"object",
"is",
"passed",
"as",
"first",
"argument",
".",
"For",
"more",
"information",
"about",
"the",
"eval",
"context",
"see",
":",
"ref",
":",
"eval",
"-",
"context",
"."
] | def evalcontextfilter(f):
"""Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfilter = True
return f | [
"def",
"evalcontextfilter",
"(",
"f",
")",
":",
"f",
".",
"evalcontextfilter",
"=",
"True",
"return",
"f"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/filters.py#L37-L45 | |
potassco/clingo | e0c91d8f95cc28de1c480a871f9c97c30de83d40 | libpyclingo/clingo/backend.py | python | Observer.theory_term_string | (self, term_id : int, name : str) | Observe string theory terms.
Parameters
----------
term_id
The id of the term.
name
The string value of the term. | Observe string theory terms. | [
"Observe",
"string",
"theory",
"terms",
"."
] | def theory_term_string(self, term_id : int, name : str) -> None:
'''
Observe string theory terms.
Parameters
----------
term_id
The id of the term.
name
The string value of the term.
''' | [
"def",
"theory_term_string",
"(",
"self",
",",
"term_id",
":",
"int",
",",
"name",
":",
"str",
")",
"->",
"None",
":"
] | https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/backend.py#L271-L281 | ||
cmu-db/noisepage | 79276e68fe83322f1249e8a8be96bd63c583ae56 | build-support/cpplint.py | python | IsInitializerList | (clean_lines, linenum) | return False | Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise. | Check if current line is inside constructor initializer list. | [
"Check",
"if",
"current",
"line",
"is",
"inside",
"constructor",
"initializer",
"list",
"."
] | def IsInitializerList(clean_lines, linenum):
"""Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise.
"""
for i in xrange(linenum, 1, -1):
line = clean_lines.elided[i]
if i == linenum:
remove_function_body = Match(r'^(.*)\{\s*$', line)
if remove_function_body:
line = remove_function_body.group(1)
if Search(r'\s:\s*\w+[({]', line):
# A lone colon tend to indicate the start of a constructor
# initializer list. It could also be a ternary operator, which
# also tend to appear in constructor initializer lists as
# opposed to parameter lists.
return True
if Search(r'\}\s*,\s*$', line):
# A closing brace followed by a comma is probably the end of a
# brace-initialized member in constructor initializer list.
return True
if Search(r'[{};]\s*$', line):
# Found one of the following:
# - A closing brace or semicolon, probably the end of the previous
# function.
# - An opening brace, probably the start of current class or namespace.
#
# Current line is probably not inside an initializer list since
# we saw one of those things without seeing the starting colon.
return False
# Got to the beginning of the file without seeing the start of
# constructor initializer list.
return False | [
"def",
"IsInitializerList",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"1",
",",
"-",
"1",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
"if",
"i",
"==",
"linenum",
":",
"remove_function_body",
"=",
"Match",
"(",
"r'^(.*)\\{\\s*$'",
",",
"line",
")",
"if",
"remove_function_body",
":",
"line",
"=",
"remove_function_body",
".",
"group",
"(",
"1",
")",
"if",
"Search",
"(",
"r'\\s:\\s*\\w+[({]'",
",",
"line",
")",
":",
"# A lone colon tend to indicate the start of a constructor",
"# initializer list. It could also be a ternary operator, which",
"# also tend to appear in constructor initializer lists as",
"# opposed to parameter lists.",
"return",
"True",
"if",
"Search",
"(",
"r'\\}\\s*,\\s*$'",
",",
"line",
")",
":",
"# A closing brace followed by a comma is probably the end of a",
"# brace-initialized member in constructor initializer list.",
"return",
"True",
"if",
"Search",
"(",
"r'[{};]\\s*$'",
",",
"line",
")",
":",
"# Found one of the following:",
"# - A closing brace or semicolon, probably the end of the previous",
"# function.",
"# - An opening brace, probably the start of current class or namespace.",
"#",
"# Current line is probably not inside an initializer list since",
"# we saw one of those things without seeing the starting colon.",
"return",
"False",
"# Got to the beginning of the file without seeing the start of",
"# constructor initializer list.",
"return",
"False"
] | https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L5242-L5281 | |
jeog/TDAmeritradeAPI | 91c738afd7d57b54f6231170bd64c2550fafd34d | python/tdma_api/execute.py | python | OrderTicket.get_duration | (self) | return clib.get_val('OrderTicket_GetDuration_ABI', c_int, self._obj) | Returns duration type as ORDER_DURATION_[] constant. | Returns duration type as ORDER_DURATION_[] constant. | [
"Returns",
"duration",
"type",
"as",
"ORDER_DURATION_",
"[]",
"constant",
"."
] | def get_duration(self):
"""Returns duration type as ORDER_DURATION_[] constant."""
return clib.get_val('OrderTicket_GetDuration_ABI', c_int, self._obj) | [
"def",
"get_duration",
"(",
"self",
")",
":",
"return",
"clib",
".",
"get_val",
"(",
"'OrderTicket_GetDuration_ABI'",
",",
"c_int",
",",
"self",
".",
"_obj",
")"
] | https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/execute.py#L314-L316 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/contrib/slim/quantization/imperative/fuse_utils.py | python | fuse_layers | (model, layers_to_fuse, inplace=False) | return model | fuse layers in layers_to_fuse
Args:
model(paddle.nn.Layer): The model to be fused.
layers_to_fuse(list): The layers' names to be fused. For
example,"fuse_list = [["conv1", "bn1"], ["conv2", "bn2"]]".
A TypeError would be raised if "fuse" was set as
True but "fuse_list" was None.
Default: None.
inplace(bool): Whether apply fusing to the input model.
Default: False.
Return
fused_model(paddle.nn.Layer): The fused model. | fuse layers in layers_to_fuse | [
"fuse",
"layers",
"in",
"layers_to_fuse"
] | def fuse_layers(model, layers_to_fuse, inplace=False):
'''
fuse layers in layers_to_fuse
Args:
model(paddle.nn.Layer): The model to be fused.
layers_to_fuse(list): The layers' names to be fused. For
example,"fuse_list = [["conv1", "bn1"], ["conv2", "bn2"]]".
A TypeError would be raised if "fuse" was set as
True but "fuse_list" was None.
Default: None.
inplace(bool): Whether apply fusing to the input model.
Default: False.
Return
fused_model(paddle.nn.Layer): The fused model.
'''
if inplace == False:
model = copy.deepcopy(model)
for layers in layers_to_fuse:
_fuse_layers(model, layers)
return model | [
"def",
"fuse_layers",
"(",
"model",
",",
"layers_to_fuse",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"inplace",
"==",
"False",
":",
"model",
"=",
"copy",
".",
"deepcopy",
"(",
"model",
")",
"for",
"layers",
"in",
"layers_to_fuse",
":",
"_fuse_layers",
"(",
"model",
",",
"layers",
")",
"return",
"model"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/slim/quantization/imperative/fuse_utils.py#L31-L52 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | bindings/python/htcondor/dags/dag.py | python | DAG.edges | (
self,
) | Iterate over ``((parent, child), edge)`` tuples,
for every edge in the graph. | Iterate over ``((parent, child), edge)`` tuples,
for every edge in the graph. | [
"Iterate",
"over",
"((",
"parent",
"child",
")",
"edge",
")",
"tuples",
"for",
"every",
"edge",
"in",
"the",
"graph",
"."
] | def edges(
self,
) -> Iterator[Tuple[Tuple[node.BaseNode, node.BaseNode], edges.BaseEdge]]:
"""
Iterate over ``((parent, child), edge)`` tuples,
for every edge in the graph.
"""
yield from self._edges | [
"def",
"edges",
"(",
"self",
",",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"Tuple",
"[",
"node",
".",
"BaseNode",
",",
"node",
".",
"BaseNode",
"]",
",",
"edges",
".",
"BaseEdge",
"]",
"]",
":",
"yield",
"from",
"self",
".",
"_edges"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/dags/dag.py#L269-L276 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | InputStream.readline | (*args, **kwargs) | return _core_.InputStream_readline(*args, **kwargs) | readline(self, int size=-1) -> PyObject | readline(self, int size=-1) -> PyObject | [
"readline",
"(",
"self",
"int",
"size",
"=",
"-",
"1",
")",
"-",
">",
"PyObject"
] | def readline(*args, **kwargs):
"""readline(self, int size=-1) -> PyObject"""
return _core_.InputStream_readline(*args, **kwargs) | [
"def",
"readline",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"InputStream_readline",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2174-L2176 | |
telefonicaid/fiware-orion | 27c3202b9ddcfb9e3635a0af8d373f76e89b1d24 | scripts/cpplint.py | python | CleansedLines._CollapseStrings | (elided) | return elided | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Collapses strings and chars on a line to simple "" or '' blocks. | [
"Collapses",
"strings",
"and",
"chars",
"on",
"a",
"line",
"to",
"simple",
"or",
"blocks",
"."
] | def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if not _RE_PATTERN_INCLUDE.match(elided):
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
return elided | [
"def",
"_CollapseStrings",
"(",
"elided",
")",
":",
"if",
"not",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"elided",
")",
":",
"# Remove escaped characters first to make quote/single quote collapsing",
"# basic. Things that look like escaped characters shouldn't occur",
"# outside of strings and chars.",
"elided",
"=",
"_RE_PATTERN_CLEANSE_LINE_ESCAPES",
".",
"sub",
"(",
"''",
",",
"elided",
")",
"elided",
"=",
"_RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES",
".",
"sub",
"(",
"\"''\"",
",",
"elided",
")",
"elided",
"=",
"_RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES",
".",
"sub",
"(",
"'\"\"'",
",",
"elided",
")",
"return",
"elided"
] | https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/cpplint.py#L947-L965 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/ndarray/ndarray.py | python | NDArray.one_hot | (self, *args, **kwargs) | return op.one_hot(self, *args, **kwargs) | Convenience fluent method for :py:func:`one_hot`.
The arguments are the same as for :py:func:`one_hot`, with
this array as data. | Convenience fluent method for :py:func:`one_hot`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"one_hot",
"."
] | def one_hot(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`one_hot`.
The arguments are the same as for :py:func:`one_hot`, with
this array as data.
"""
return op.one_hot(self, *args, **kwargs) | [
"def",
"one_hot",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"one_hot",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L1174-L1180 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextBuffer.EndParagraphSpacing | (*args, **kwargs) | return _richtext.RichTextBuffer_EndParagraphSpacing(*args, **kwargs) | EndParagraphSpacing(self) -> bool | EndParagraphSpacing(self) -> bool | [
"EndParagraphSpacing",
"(",
"self",
")",
"-",
">",
"bool"
] | def EndParagraphSpacing(*args, **kwargs):
"""EndParagraphSpacing(self) -> bool"""
return _richtext.RichTextBuffer_EndParagraphSpacing(*args, **kwargs) | [
"def",
"EndParagraphSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_EndParagraphSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2409-L2411 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TextAttr.SetBulletFont | (*args, **kwargs) | return _controls_.TextAttr_SetBulletFont(*args, **kwargs) | SetBulletFont(self, String bulletFont) | SetBulletFont(self, String bulletFont) | [
"SetBulletFont",
"(",
"self",
"String",
"bulletFont",
")"
] | def SetBulletFont(*args, **kwargs):
"""SetBulletFont(self, String bulletFont)"""
return _controls_.TextAttr_SetBulletFont(*args, **kwargs) | [
"def",
"SetBulletFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_SetBulletFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1611-L1613 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py | python | PartitionedVariable._distribute_strategy | (self) | return None | The `tf.distribute.Strategy` that this variable was created under. | The `tf.distribute.Strategy` that this variable was created under. | [
"The",
"tf",
".",
"distribute",
".",
"Strategy",
"that",
"this",
"variable",
"was",
"created",
"under",
"."
] | def _distribute_strategy(self):
"""The `tf.distribute.Strategy` that this variable was created under."""
# NOTE(yuefengz): Today, no partitioned variables in a distribute strategy.
return None | [
"def",
"_distribute_strategy",
"(",
"self",
")",
":",
"# NOTE(yuefengz): Today, no partitioned variables in a distribute strategy.",
"return",
"None"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py#L2983-L2986 | |
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/lang/impl.py | python | _Root.shape | (self) | return _root_fb.root.shape | Same as :func:`taichi.SNode.shape` | Same as :func:`taichi.SNode.shape` | [
"Same",
"as",
":",
"func",
":",
"taichi",
".",
"SNode",
".",
"shape"
] | def shape(self):
"""Same as :func:`taichi.SNode.shape`"""
return _root_fb.root.shape | [
"def",
"shape",
"(",
"self",
")",
":",
"return",
"_root_fb",
".",
"root",
".",
"shape"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/impl.py#L512-L514 | |
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/datasets/pascal_voc.py | python | pascal_voc._load_pascal_annotation | (self, index) | return {'boxes' : boxes,
'gt_classes': gt_classes,
'gt_overlaps' : overlaps,
'flipped' : False,
'seg_areas' : seg_areas} | Load image and bounding boxes info from XML file in the PASCAL VOC
format. | Load image and bounding boxes info from XML file in the PASCAL VOC
format. | [
"Load",
"image",
"and",
"bounding",
"boxes",
"info",
"from",
"XML",
"file",
"in",
"the",
"PASCAL",
"VOC",
"format",
"."
] | def _load_pascal_annotation(self, index):
"""
Load image and bounding boxes info from XML file in the PASCAL VOC
format.
"""
filename = os.path.join(self._data_path, 'Annotations', index + '.xml')
tree = ET.parse(filename)
objs = tree.findall('object')
if not self.config['use_diff']:
# Exclude the samples labeled as difficult
non_diff_objs = [
obj for obj in objs if int(obj.find('difficult').text) == 0]
# if len(non_diff_objs) != len(objs):
# print 'Removed {} difficult objects'.format(
# len(objs) - len(non_diff_objs))
objs = non_diff_objs
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)
# "Seg" area for pascal is just the box area
seg_areas = np.zeros((num_objs), dtype=np.float32)
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
bbox = obj.find('bndbox')
# Make pixel indexes 0-based
x1 = float(bbox.find('xmin').text) - 1
y1 = float(bbox.find('ymin').text) - 1
x2 = float(bbox.find('xmax').text) - 1
y2 = float(bbox.find('ymax').text) - 1
cls = self._class_to_ind[obj.find('name').text.lower().strip()]
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1)
overlaps = scipy.sparse.csr_matrix(overlaps)
return {'boxes' : boxes,
'gt_classes': gt_classes,
'gt_overlaps' : overlaps,
'flipped' : False,
'seg_areas' : seg_areas} | [
"def",
"_load_pascal_annotation",
"(",
"self",
",",
"index",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_data_path",
",",
"'Annotations'",
",",
"index",
"+",
"'.xml'",
")",
"tree",
"=",
"ET",
".",
"parse",
"(",
"filename",
")",
"objs",
"=",
"tree",
".",
"findall",
"(",
"'object'",
")",
"if",
"not",
"self",
".",
"config",
"[",
"'use_diff'",
"]",
":",
"# Exclude the samples labeled as difficult",
"non_diff_objs",
"=",
"[",
"obj",
"for",
"obj",
"in",
"objs",
"if",
"int",
"(",
"obj",
".",
"find",
"(",
"'difficult'",
")",
".",
"text",
")",
"==",
"0",
"]",
"# if len(non_diff_objs) != len(objs):",
"# print 'Removed {} difficult objects'.format(",
"# len(objs) - len(non_diff_objs))",
"objs",
"=",
"non_diff_objs",
"num_objs",
"=",
"len",
"(",
"objs",
")",
"boxes",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
",",
"4",
")",
",",
"dtype",
"=",
"np",
".",
"uint16",
")",
"gt_classes",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"overlaps",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
",",
"self",
".",
"num_classes",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# \"Seg\" area for pascal is just the box area",
"seg_areas",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# Load object bounding boxes into a data frame.",
"for",
"ix",
",",
"obj",
"in",
"enumerate",
"(",
"objs",
")",
":",
"bbox",
"=",
"obj",
".",
"find",
"(",
"'bndbox'",
")",
"# Make pixel indexes 0-based",
"x1",
"=",
"float",
"(",
"bbox",
".",
"find",
"(",
"'xmin'",
")",
".",
"text",
")",
"-",
"1",
"y1",
"=",
"float",
"(",
"bbox",
".",
"find",
"(",
"'ymin'",
")",
".",
"text",
")",
"-",
"1",
"x2",
"=",
"float",
"(",
"bbox",
".",
"find",
"(",
"'xmax'",
")",
".",
"text",
")",
"-",
"1",
"y2",
"=",
"float",
"(",
"bbox",
".",
"find",
"(",
"'ymax'",
")",
".",
"text",
")",
"-",
"1",
"cls",
"=",
"self",
".",
"_class_to_ind",
"[",
"obj",
".",
"find",
"(",
"'name'",
")",
".",
"text",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"]",
"boxes",
"[",
"ix",
",",
":",
"]",
"=",
"[",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"]",
"gt_classes",
"[",
"ix",
"]",
"=",
"cls",
"overlaps",
"[",
"ix",
",",
"cls",
"]",
"=",
"1.0",
"seg_areas",
"[",
"ix",
"]",
"=",
"(",
"x2",
"-",
"x1",
"+",
"1",
")",
"*",
"(",
"y2",
"-",
"y1",
"+",
"1",
")",
"overlaps",
"=",
"scipy",
".",
"sparse",
".",
"csr_matrix",
"(",
"overlaps",
")",
"return",
"{",
"'boxes'",
":",
"boxes",
",",
"'gt_classes'",
":",
"gt_classes",
",",
"'gt_overlaps'",
":",
"overlaps",
",",
"'flipped'",
":",
"False",
",",
"'seg_areas'",
":",
"seg_areas",
"}"
] | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/datasets/pascal_voc.py#L180-L224 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/dateutil/parser.py | python | _parsems | (value) | Parse a I[.F] seconds value into (seconds, microseconds). | Parse a I[.F] seconds value into (seconds, microseconds). | [
"Parse",
"a",
"I",
"[",
".",
"F",
"]",
"seconds",
"value",
"into",
"(",
"seconds",
"microseconds",
")",
"."
] | def _parsems(value):
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
if "." not in value:
return int(value), 0
else:
i, f = value.split(".")
return int(i), int(f.ljust(6, "0")[:6]) | [
"def",
"_parsems",
"(",
"value",
")",
":",
"if",
"\".\"",
"not",
"in",
"value",
":",
"return",
"int",
"(",
"value",
")",
",",
"0",
"else",
":",
"i",
",",
"f",
"=",
"value",
".",
"split",
"(",
"\".\"",
")",
"return",
"int",
"(",
"i",
")",
",",
"int",
"(",
"f",
".",
"ljust",
"(",
"6",
",",
"\"0\"",
")",
"[",
":",
"6",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/dateutil/parser.py#L1365-L1371 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/os.py | python | execlp | (file, *args) | execlp(file, *args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process. | execlp(file, *args) | [
"execlp",
"(",
"file",
"*",
"args",
")"
] | def execlp(file, *args):
"""execlp(file, *args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process. """
execvp(file, args) | [
"def",
"execlp",
"(",
"file",
",",
"*",
"args",
")",
":",
"execvp",
"(",
"file",
",",
"args",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/os.py#L322-L327 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | tools/Polygraphy/polygraphy/tools/args/base.py | python | BaseArgs.register | (self, maker) | Registers another argument group with this one.
This can be used to pick up dependencies for example.
Args:
maker (BaseArgs): Another argument group. | Registers another argument group with this one.
This can be used to pick up dependencies for example. | [
"Registers",
"another",
"argument",
"group",
"with",
"this",
"one",
".",
"This",
"can",
"be",
"used",
"to",
"pick",
"up",
"dependencies",
"for",
"example",
"."
] | def register(self, maker):
"""
Registers another argument group with this one.
This can be used to pick up dependencies for example.
Args:
maker (BaseArgs): Another argument group.
"""
pass | [
"def",
"register",
"(",
"self",
",",
"maker",
")",
":",
"pass"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/Polygraphy/polygraphy/tools/args/base.py#L47-L55 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/gn/bin/gyp_flag_compare.py | python | Comparison.__init__ | (self, gyp_target, gn_target=None) | Creates a comparison of a GN and GYP target. If the target names differ
between the two build systems, then two names may be passed. | Creates a comparison of a GN and GYP target. If the target names differ
between the two build systems, then two names may be passed. | [
"Creates",
"a",
"comparison",
"of",
"a",
"GN",
"and",
"GYP",
"target",
".",
"If",
"the",
"target",
"names",
"differ",
"between",
"the",
"two",
"build",
"systems",
"then",
"two",
"names",
"may",
"be",
"passed",
"."
] | def __init__(self, gyp_target, gn_target=None):
"""Creates a comparison of a GN and GYP target. If the target names differ
between the two build systems, then two names may be passed.
"""
if gn_target is None:
gn_target = gyp_target
self._gyp_target = gyp_target
self._gn_target = gn_target
self._skipped = []
self._total_diffs = 0
self._missing_gyp_flags = {}
self._missing_gn_flags = {}
self._missing_gyp_files = {}
self._missing_gn_files = {}
self._CompareFiles() | [
"def",
"__init__",
"(",
"self",
",",
"gyp_target",
",",
"gn_target",
"=",
"None",
")",
":",
"if",
"gn_target",
"is",
"None",
":",
"gn_target",
"=",
"gyp_target",
"self",
".",
"_gyp_target",
"=",
"gyp_target",
"self",
".",
"_gn_target",
"=",
"gn_target",
"self",
".",
"_skipped",
"=",
"[",
"]",
"self",
".",
"_total_diffs",
"=",
"0",
"self",
".",
"_missing_gyp_flags",
"=",
"{",
"}",
"self",
".",
"_missing_gn_flags",
"=",
"{",
"}",
"self",
".",
"_missing_gyp_files",
"=",
"{",
"}",
"self",
".",
"_missing_gn_files",
"=",
"{",
"}",
"self",
".",
"_CompareFiles",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/gn/bin/gyp_flag_compare.py#L90-L109 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Joystick.GetXMin | (*args, **kwargs) | return _misc_.Joystick_GetXMin(*args, **kwargs) | GetXMin(self) -> int | GetXMin(self) -> int | [
"GetXMin",
"(",
"self",
")",
"-",
">",
"int"
] | def GetXMin(*args, **kwargs):
"""GetXMin(self) -> int"""
return _misc_.Joystick_GetXMin(*args, **kwargs) | [
"def",
"GetXMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Joystick_GetXMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2186-L2188 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_abcoll.py | python | MutableSequence.append | (self, value) | S.append(object) -- append object to the end of the sequence | S.append(object) -- append object to the end of the sequence | [
"S",
".",
"append",
"(",
"object",
")",
"--",
"append",
"object",
"to",
"the",
"end",
"of",
"the",
"sequence"
] | def append(self, value):
'S.append(object) -- append object to the end of the sequence'
self.insert(len(self), value) | [
"def",
"append",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"insert",
"(",
"len",
"(",
"self",
")",
",",
"value",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_abcoll.py#L638-L640 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/item.py | python | Item.delete_attribute | (self, attr_name, attr_value=None) | Queue the deletion of an attribute from an item in DynamoDB.
This call will result in a UpdateItem request being issued
with update action of DELETE when the save method is called.
:type attr_name: str
:param attr_name: Name of the attribute you want to alter.
:type attr_value: set
:param attr_value: A set of values to be removed from the attribute.
This parameter is optional. If None, the whole attribute is
removed from the item. | Queue the deletion of an attribute from an item in DynamoDB.
This call will result in a UpdateItem request being issued
with update action of DELETE when the save method is called. | [
"Queue",
"the",
"deletion",
"of",
"an",
"attribute",
"from",
"an",
"item",
"in",
"DynamoDB",
".",
"This",
"call",
"will",
"result",
"in",
"a",
"UpdateItem",
"request",
"being",
"issued",
"with",
"update",
"action",
"of",
"DELETE",
"when",
"the",
"save",
"method",
"is",
"called",
"."
] | def delete_attribute(self, attr_name, attr_value=None):
"""
Queue the deletion of an attribute from an item in DynamoDB.
This call will result in a UpdateItem request being issued
with update action of DELETE when the save method is called.
:type attr_name: str
:param attr_name: Name of the attribute you want to alter.
:type attr_value: set
:param attr_value: A set of values to be removed from the attribute.
This parameter is optional. If None, the whole attribute is
removed from the item.
"""
self._updates[attr_name] = ("DELETE", attr_value) | [
"def",
"delete_attribute",
"(",
"self",
",",
"attr_name",
",",
"attr_value",
"=",
"None",
")",
":",
"self",
".",
"_updates",
"[",
"attr_name",
"]",
"=",
"(",
"\"DELETE\"",
",",
"attr_value",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/item.py#L89-L103 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatnotebook.py | python | FNBDropSource.GiveFeedback | (self, effect) | return False | You may give some custom UI feedback during the drag and drop operation
in this function. It is called on each mouse move, so your implementation
must not be too slow.
:param `effect`: the effect to implement. One of ``wx.DragCopy``, ``wx.DragMove``,
``wx.DragLink`` and ``wx.DragNone``.
:return: Return ``False`` if you want default feedback, or ``True`` if you
implement your own feedback. The return values is ignored under GTK.
:note: To show your own custom drag and drop UI feedback, you must override
this method. | You may give some custom UI feedback during the drag and drop operation
in this function. It is called on each mouse move, so your implementation
must not be too slow. | [
"You",
"may",
"give",
"some",
"custom",
"UI",
"feedback",
"during",
"the",
"drag",
"and",
"drop",
"operation",
"in",
"this",
"function",
".",
"It",
"is",
"called",
"on",
"each",
"mouse",
"move",
"so",
"your",
"implementation",
"must",
"not",
"be",
"too",
"slow",
"."
] | def GiveFeedback(self, effect):
"""
You may give some custom UI feedback during the drag and drop operation
in this function. It is called on each mouse move, so your implementation
must not be too slow.
:param `effect`: the effect to implement. One of ``wx.DragCopy``, ``wx.DragMove``,
``wx.DragLink`` and ``wx.DragNone``.
:return: Return ``False`` if you want default feedback, or ``True`` if you
implement your own feedback. The return values is ignored under GTK.
:note: To show your own custom drag and drop UI feedback, you must override
this method.
"""
self._win.DrawDragHint()
return False | [
"def",
"GiveFeedback",
"(",
"self",
",",
"effect",
")",
":",
"self",
".",
"_win",
".",
"DrawDragHint",
"(",
")",
"return",
"False"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L992-L1009 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/retdec-3.2/scripts/retdec-utils.py | python | CmdRunner._get_memory_from_measured_output | (self, output) | return memory | Get memory in MB from output string generated by `config.LOG_TIME`.
`/usr/bin/time` format is expected. | Get memory in MB from output string generated by `config.LOG_TIME`.
`/usr/bin/time` format is expected. | [
"Get",
"memory",
"in",
"MB",
"from",
"output",
"string",
"generated",
"by",
"config",
".",
"LOG_TIME",
".",
"/",
"usr",
"/",
"bin",
"/",
"time",
"format",
"is",
"expected",
"."
] | def _get_memory_from_measured_output(self, output):
"""Get memory in MB from output string generated by `config.LOG_TIME`.
`/usr/bin/time` format is expected."""
memory = 0
s = re.search(r'Maximum resident set size \(kbytes\): (\d+)', output)
if s:
g = s.group(1)
if g:
memory_kb = int(g)
memory = int(memory_kb / 1024) # to MB
if memory == 0:
memory = 1
return memory | [
"def",
"_get_memory_from_measured_output",
"(",
"self",
",",
"output",
")",
":",
"memory",
"=",
"0",
"s",
"=",
"re",
".",
"search",
"(",
"r'Maximum resident set size \\(kbytes\\): (\\d+)'",
",",
"output",
")",
"if",
"s",
":",
"g",
"=",
"s",
".",
"group",
"(",
"1",
")",
"if",
"g",
":",
"memory_kb",
"=",
"int",
"(",
"g",
")",
"memory",
"=",
"int",
"(",
"memory_kb",
"/",
"1024",
")",
"# to MB",
"if",
"memory",
"==",
"0",
":",
"memory",
"=",
"1",
"return",
"memory"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/retdec-utils.py#L171-L183 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/wms/ogc/common/configs.py | python | Configs.__init__ | (self, config_file, default_values=None) | Load config key/value pairs from the config file. | Load config key/value pairs from the config file. | [
"Load",
"config",
"key",
"/",
"value",
"pairs",
"from",
"the",
"config",
"file",
"."
] | def __init__(self, config_file, default_values=None):
"""Load config key/value pairs from the config file."""
if default_values:
self._config_values = default_values
else:
self._config_values = {}
try:
fp = open(config_file)
for line in fp:
line = line.strip()
if line and line[0] != "#":
(key, value) = line.split(" ")
self._config_values[key] = value
fp.close()
except IOError:
pass
except:
pass | [
"def",
"__init__",
"(",
"self",
",",
"config_file",
",",
"default_values",
"=",
"None",
")",
":",
"if",
"default_values",
":",
"self",
".",
"_config_values",
"=",
"default_values",
"else",
":",
"self",
".",
"_config_values",
"=",
"{",
"}",
"try",
":",
"fp",
"=",
"open",
"(",
"config_file",
")",
"for",
"line",
"in",
"fp",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"and",
"line",
"[",
"0",
"]",
"!=",
"\"#\"",
":",
"(",
"key",
",",
"value",
")",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"self",
".",
"_config_values",
"[",
"key",
"]",
"=",
"value",
"fp",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"pass",
"except",
":",
"pass"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/wms/ogc/common/configs.py#L25-L42 | ||
hszhao/PSPNet | cf7e5a99ba37e46118026e96be5821a9bc63bde0 | python/caffe/io.py | python | Transformer.set_raw_scale | (self, in_, scale) | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255. | [
"Set",
"the",
"scale",
"of",
"raw",
"features",
"s",
".",
"t",
".",
"the",
"input",
"blob",
"=",
"input",
"*",
"scale",
".",
"While",
"Python",
"represents",
"images",
"in",
"[",
"0",
"1",
"]",
"certain",
"Caffe",
"models",
"like",
"CaffeNet",
"and",
"AlexNet",
"represent",
"images",
"in",
"[",
"0",
"255",
"]",
"so",
"the",
"raw_scale",
"of",
"these",
"models",
"must",
"be",
"255",
"."
] | def set_raw_scale(self, in_, scale):
"""
Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.raw_scale[in_] = scale | [
"def",
"set_raw_scale",
"(",
"self",
",",
"in_",
",",
"scale",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"self",
".",
"raw_scale",
"[",
"in_",
"]",
"=",
"scale"
] | https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/python/caffe/io.py#L220-L233 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Image.RGBtoHSV | (*args, **kwargs) | return _core_.Image_RGBtoHSV(*args, **kwargs) | RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue
Converts a color in RGB color space to HSV color space. | RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue | [
"RGBtoHSV",
"(",
"Image_RGBValue",
"rgb",
")",
"-",
">",
"Image_HSVValue"
] | def RGBtoHSV(*args, **kwargs):
"""
RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue
Converts a color in RGB color space to HSV color space.
"""
return _core_.Image_RGBtoHSV(*args, **kwargs) | [
"def",
"RGBtoHSV",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_RGBtoHSV",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3661-L3667 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/math_ops.py | python | _maybe_get_dtype | (x) | return x | Returns a numpy type if available from x. Skips if x is numpy.ndarray. | Returns a numpy type if available from x. Skips if x is numpy.ndarray. | [
"Returns",
"a",
"numpy",
"type",
"if",
"available",
"from",
"x",
".",
"Skips",
"if",
"x",
"is",
"numpy",
".",
"ndarray",
"."
] | def _maybe_get_dtype(x):
"""Returns a numpy type if available from x. Skips if x is numpy.ndarray."""
# Don't put np.ndarray in this list, because np.result_type looks at the
# value (not just dtype) of np.ndarray to decide the result type.
if isinstance(x, numbers.Real):
return x
if isinstance(x, ops.Tensor):
return x.dtype.as_numpy_dtype
if isinstance(x, dtypes.DType):
return x.as_numpy_dtype
if isinstance(x, tensor_shape.TensorShape):
return np.int32
if isinstance(x, (list, tuple)):
raise ValueError(f"Cannot determine dtype. Got sequence {x}.")
return x | [
"def",
"_maybe_get_dtype",
"(",
"x",
")",
":",
"# Don't put np.ndarray in this list, because np.result_type looks at the",
"# value (not just dtype) of np.ndarray to decide the result type.",
"if",
"isinstance",
"(",
"x",
",",
"numbers",
".",
"Real",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"ops",
".",
"Tensor",
")",
":",
"return",
"x",
".",
"dtype",
".",
"as_numpy_dtype",
"if",
"isinstance",
"(",
"x",
",",
"dtypes",
".",
"DType",
")",
":",
"return",
"x",
".",
"as_numpy_dtype",
"if",
"isinstance",
"(",
"x",
",",
"tensor_shape",
".",
"TensorShape",
")",
":",
"return",
"np",
".",
"int32",
"if",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"ValueError",
"(",
"f\"Cannot determine dtype. Got sequence {x}.\"",
")",
"return",
"x"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_ops.py#L1326-L1340 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/difflib.py | python | SequenceMatcher.get_grouped_opcodes | (self, n=3) | Isolate change clusters by eliminating ranges with no changes.
Return a generator of groups with upto n lines of context.
Each group is in the same format as returned by get_opcodes().
>>> from pprint import pprint
>>> a = map(str, range(1,40))
>>> b = a[:]
>>> b[8:8] = ['i'] # Make an insertion
>>> b[20] += 'x' # Make a replacement
>>> b[23:28] = [] # Make a deletion
>>> b[30] += 'y' # Make another replacement
>>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
[[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
[('equal', 16, 19, 17, 20),
('replace', 19, 20, 20, 21),
('equal', 20, 22, 21, 23),
('delete', 22, 27, 23, 23),
('equal', 27, 30, 23, 26)],
[('equal', 31, 34, 27, 30),
('replace', 34, 35, 30, 31),
('equal', 35, 38, 31, 34)]] | Isolate change clusters by eliminating ranges with no changes. | [
"Isolate",
"change",
"clusters",
"by",
"eliminating",
"ranges",
"with",
"no",
"changes",
"."
] | def get_grouped_opcodes(self, n=3):
""" Isolate change clusters by eliminating ranges with no changes.
Return a generator of groups with upto n lines of context.
Each group is in the same format as returned by get_opcodes().
>>> from pprint import pprint
>>> a = map(str, range(1,40))
>>> b = a[:]
>>> b[8:8] = ['i'] # Make an insertion
>>> b[20] += 'x' # Make a replacement
>>> b[23:28] = [] # Make a deletion
>>> b[30] += 'y' # Make another replacement
>>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
[[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
[('equal', 16, 19, 17, 20),
('replace', 19, 20, 20, 21),
('equal', 20, 22, 21, 23),
('delete', 22, 27, 23, 23),
('equal', 27, 30, 23, 26)],
[('equal', 31, 34, 27, 30),
('replace', 34, 35, 30, 31),
('equal', 35, 38, 31, 34)]]
"""
codes = self.get_opcodes()
if not codes:
codes = [("equal", 0, 1, 0, 1)]
# Fixup leading and trailing groups if they show no changes.
if codes[0][0] == 'equal':
tag, i1, i2, j1, j2 = codes[0]
codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
if codes[-1][0] == 'equal':
tag, i1, i2, j1, j2 = codes[-1]
codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
nn = n + n
group = []
for tag, i1, i2, j1, j2 in codes:
# End the current group and start a new one whenever
# there is a large range with no changes.
if tag == 'equal' and i2-i1 > nn:
group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
yield group
group = []
i1, j1 = max(i1, i2-n), max(j1, j2-n)
group.append((tag, i1, i2, j1 ,j2))
if group and not (len(group)==1 and group[0][0] == 'equal'):
yield group | [
"def",
"get_grouped_opcodes",
"(",
"self",
",",
"n",
"=",
"3",
")",
":",
"codes",
"=",
"self",
".",
"get_opcodes",
"(",
")",
"if",
"not",
"codes",
":",
"codes",
"=",
"[",
"(",
"\"equal\"",
",",
"0",
",",
"1",
",",
"0",
",",
"1",
")",
"]",
"# Fixup leading and trailing groups if they show no changes.",
"if",
"codes",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"'equal'",
":",
"tag",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
"=",
"codes",
"[",
"0",
"]",
"codes",
"[",
"0",
"]",
"=",
"tag",
",",
"max",
"(",
"i1",
",",
"i2",
"-",
"n",
")",
",",
"i2",
",",
"max",
"(",
"j1",
",",
"j2",
"-",
"n",
")",
",",
"j2",
"if",
"codes",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
"'equal'",
":",
"tag",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
"=",
"codes",
"[",
"-",
"1",
"]",
"codes",
"[",
"-",
"1",
"]",
"=",
"tag",
",",
"i1",
",",
"min",
"(",
"i2",
",",
"i1",
"+",
"n",
")",
",",
"j1",
",",
"min",
"(",
"j2",
",",
"j1",
"+",
"n",
")",
"nn",
"=",
"n",
"+",
"n",
"group",
"=",
"[",
"]",
"for",
"tag",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
"in",
"codes",
":",
"# End the current group and start a new one whenever",
"# there is a large range with no changes.",
"if",
"tag",
"==",
"'equal'",
"and",
"i2",
"-",
"i1",
">",
"nn",
":",
"group",
".",
"append",
"(",
"(",
"tag",
",",
"i1",
",",
"min",
"(",
"i2",
",",
"i1",
"+",
"n",
")",
",",
"j1",
",",
"min",
"(",
"j2",
",",
"j1",
"+",
"n",
")",
")",
")",
"yield",
"group",
"group",
"=",
"[",
"]",
"i1",
",",
"j1",
"=",
"max",
"(",
"i1",
",",
"i2",
"-",
"n",
")",
",",
"max",
"(",
"j1",
",",
"j2",
"-",
"n",
")",
"group",
".",
"append",
"(",
"(",
"tag",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
")",
")",
"if",
"group",
"and",
"not",
"(",
"len",
"(",
"group",
")",
"==",
"1",
"and",
"group",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"'equal'",
")",
":",
"yield",
"group"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/difflib.py#L586-L634 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/definition.py | python | define_service | (service_descriptor, module) | return service_class | Define a new service proxy.
Args:
service_descriptor: ServiceDescriptor class that describes the service.
module: Module to add service to. Request and response types are found
relative to this module.
Returns:
Service class proxy capable of communicating with a remote server. | Define a new service proxy. | [
"Define",
"a",
"new",
"service",
"proxy",
"."
] | def define_service(service_descriptor, module):
"""Define a new service proxy.
Args:
service_descriptor: ServiceDescriptor class that describes the service.
module: Module to add service to. Request and response types are found
relative to this module.
Returns:
Service class proxy capable of communicating with a remote server.
"""
class_dict = {'__module__': module.__name__}
class_name = service_descriptor.name.encode('utf-8')
for method_descriptor in service_descriptor.methods or []:
request_definition = messages.find_definition(
method_descriptor.request_type, module)
response_definition = messages.find_definition(
method_descriptor.response_type, module)
method_name = method_descriptor.name.encode('utf-8')
def remote_method(self, request):
"""Actual service method."""
raise NotImplementedError('Method is not implemented')
remote_method.__name__ = method_name
remote_method_decorator = remote.method(request_definition,
response_definition)
class_dict[method_name] = remote_method_decorator(remote_method)
service_class = type(class_name, (remote.Service,), class_dict)
return service_class | [
"def",
"define_service",
"(",
"service_descriptor",
",",
"module",
")",
":",
"class_dict",
"=",
"{",
"'__module__'",
":",
"module",
".",
"__name__",
"}",
"class_name",
"=",
"service_descriptor",
".",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
"for",
"method_descriptor",
"in",
"service_descriptor",
".",
"methods",
"or",
"[",
"]",
":",
"request_definition",
"=",
"messages",
".",
"find_definition",
"(",
"method_descriptor",
".",
"request_type",
",",
"module",
")",
"response_definition",
"=",
"messages",
".",
"find_definition",
"(",
"method_descriptor",
".",
"response_type",
",",
"module",
")",
"method_name",
"=",
"method_descriptor",
".",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
"def",
"remote_method",
"(",
"self",
",",
"request",
")",
":",
"\"\"\"Actual service method.\"\"\"",
"raise",
"NotImplementedError",
"(",
"'Method is not implemented'",
")",
"remote_method",
".",
"__name__",
"=",
"method_name",
"remote_method_decorator",
"=",
"remote",
".",
"method",
"(",
"request_definition",
",",
"response_definition",
")",
"class_dict",
"[",
"method_name",
"]",
"=",
"remote_method_decorator",
"(",
"remote_method",
")",
"service_class",
"=",
"type",
"(",
"class_name",
",",
"(",
"remote",
".",
"Service",
",",
")",
",",
"class_dict",
")",
"return",
"service_class"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/definition.py#L169-L200 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py | python | DifferentialEvolutionSolver._randtobest1 | (self, samples) | return bprime | randtobest1bin, randtobest1exp | randtobest1bin, randtobest1exp | [
"randtobest1bin",
"randtobest1exp"
] | def _randtobest1(self, samples):
"""randtobest1bin, randtobest1exp"""
r0, r1, r2 = samples[:3]
bprime = np.copy(self.population[r0])
bprime += self.scale * (self.population[0] - bprime)
bprime += self.scale * (self.population[r1] -
self.population[r2])
return bprime | [
"def",
"_randtobest1",
"(",
"self",
",",
"samples",
")",
":",
"r0",
",",
"r1",
",",
"r2",
"=",
"samples",
"[",
":",
"3",
"]",
"bprime",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"population",
"[",
"r0",
"]",
")",
"bprime",
"+=",
"self",
".",
"scale",
"*",
"(",
"self",
".",
"population",
"[",
"0",
"]",
"-",
"bprime",
")",
"bprime",
"+=",
"self",
".",
"scale",
"*",
"(",
"self",
".",
"population",
"[",
"r1",
"]",
"-",
"self",
".",
"population",
"[",
"r2",
"]",
")",
"return",
"bprime"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py#L958-L965 | |
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | SynthText_Chinese/text_utils.py | python | TextSource.is_good | (self, txt, f=0.35) | return [ (len(l)> self.min_nchar
and self.check_symb_frac(l,f)
and is_txt(l)) for l in txt ] | T/F return : T iff the lines in txt (a list of txt lines)
are "valid".
A given line l is valid iff:
1. It is not empty.
2. symbol_fraction > f
3. Has at-least self.min_nchar characters
4. Not all characters are i,x,0,O,- | T/F return : T iff the lines in txt (a list of txt lines)
are "valid".
A given line l is valid iff:
1. It is not empty.
2. symbol_fraction > f
3. Has at-least self.min_nchar characters
4. Not all characters are i,x,0,O,- | [
"T",
"/",
"F",
"return",
":",
"T",
"iff",
"the",
"lines",
"in",
"txt",
"(",
"a",
"list",
"of",
"txt",
"lines",
")",
"are",
"valid",
".",
"A",
"given",
"line",
"l",
"is",
"valid",
"iff",
":",
"1",
".",
"It",
"is",
"not",
"empty",
".",
"2",
".",
"symbol_fraction",
">",
"f",
"3",
".",
"Has",
"at",
"-",
"least",
"self",
".",
"min_nchar",
"characters",
"4",
".",
"Not",
"all",
"characters",
"are",
"i",
"x",
"0",
"O",
"-"
] | def is_good(self, txt, f=0.35):
"""
T/F return : T iff the lines in txt (a list of txt lines)
are "valid".
A given line l is valid iff:
1. It is not empty.
2. symbol_fraction > f
3. Has at-least self.min_nchar characters
4. Not all characters are i,x,0,O,-
"""
def is_txt(l):
char_ex = ['i','I','o','O','0','-']
chs = [ch in char_ex for ch in l]
return not np.all(chs)
return [ (len(l)> self.min_nchar
and self.check_symb_frac(l,f)
and is_txt(l)) for l in txt ] | [
"def",
"is_good",
"(",
"self",
",",
"txt",
",",
"f",
"=",
"0.35",
")",
":",
"def",
"is_txt",
"(",
"l",
")",
":",
"char_ex",
"=",
"[",
"'i'",
",",
"'I'",
",",
"'o'",
",",
"'O'",
",",
"'0'",
",",
"'-'",
"]",
"chs",
"=",
"[",
"ch",
"in",
"char_ex",
"for",
"ch",
"in",
"l",
"]",
"return",
"not",
"np",
".",
"all",
"(",
"chs",
")",
"return",
"[",
"(",
"len",
"(",
"l",
")",
">",
"self",
".",
"min_nchar",
"and",
"self",
".",
"check_symb_frac",
"(",
"l",
",",
"f",
")",
"and",
"is_txt",
"(",
"l",
")",
")",
"for",
"l",
"in",
"txt",
"]"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/text_utils.py#L577-L594 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/linalg_grad.py | python | _BatchMatrixDeterminantGrad | (op, grad) | return multipliers * a_adj_inv | Gradient for BatchMatrixDeterminant. | Gradient for BatchMatrixDeterminant. | [
"Gradient",
"for",
"BatchMatrixDeterminant",
"."
] | def _BatchMatrixDeterminantGrad(op, grad):
"""Gradient for BatchMatrixDeterminant."""
a = op.inputs[0]
c = op.outputs[0]
a_adj_inv = linalg_ops.batch_matrix_inverse(a, adjoint=True)
multipliers = array_ops.reshape(
grad * c, array_ops.concat(0, [array_ops.shape(c), [1, 1]]))
return multipliers * a_adj_inv | [
"def",
"_BatchMatrixDeterminantGrad",
"(",
"op",
",",
"grad",
")",
":",
"a",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"c",
"=",
"op",
".",
"outputs",
"[",
"0",
"]",
"a_adj_inv",
"=",
"linalg_ops",
".",
"batch_matrix_inverse",
"(",
"a",
",",
"adjoint",
"=",
"True",
")",
"multipliers",
"=",
"array_ops",
".",
"reshape",
"(",
"grad",
"*",
"c",
",",
"array_ops",
".",
"concat",
"(",
"0",
",",
"[",
"array_ops",
".",
"shape",
"(",
"c",
")",
",",
"[",
"1",
",",
"1",
"]",
"]",
")",
")",
"return",
"multipliers",
"*",
"a_adj_inv"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/linalg_grad.py#L75-L82 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.