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
google-research/sound-separation
0b23ae22123b041b9538295f32a92151cb77bff9
models/neurips2020_mixit/model.py
python
model_fn
(features, labels, mode, params)
return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=loss, eval_metric_ops=metrics, train_op=train_op, training_hooks=[logging_hook])
Constructs a spectrogram_lstm model with summaries. Args: features: Dictionary {name: Tensor} of model inputs. labels: Any training-only inputs. mode: Build mode, one of tf.estimator.ModeKeys. params: Dictionary of Model hyperparameters. Returns: EstimatorSpec describing the model.
Constructs a spectrogram_lstm model with summaries.
[ "Constructs", "a", "spectrogram_lstm", "model", "with", "summaries", "." ]
def model_fn(features, labels, mode, params): """Constructs a spectrogram_lstm model with summaries. Args: features: Dictionary {name: Tensor} of model inputs. labels: Any training-only inputs. mode: Build mode, one of tf.estimator.ModeKeys. params: Dictionary of Model hyperparameters. Returns: EstimatorSpec describing the model. """ del labels hparams = params['hparams'] mixture_waveforms = features['receiver_audio'] batch_size = signal_util.static_or_dynamic_dim_size(mixture_waveforms, 0) # Create mixtures of mixtures (MoMs) on-the-fly by splitting batch in half. if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL: mixture_waveforms_1mix = mixture_waveforms # Build MoMs by splitting batch in half. with tf.control_dependencies([tf.compat.v1.assert_equal( tf.mod(batch_size, 2), 0)]): mixture_waveforms = tf.reshape(mixture_waveforms, (batch_size // 2, 2, -1)) # Create the MoMs by summing up single mixtures. mix_of_mix_waveforms = tf.reduce_sum(mixture_waveforms, axis=1, keepdims=True) else: # Inference mode, mixture_waveforms is just an input placeholder. mix_of_mix_waveforms = mixture_waveforms # In eval mode, separate both MoMs and single mixtures. if mode == tf.estimator.ModeKeys.EVAL: input_waveforms = tf.concat([mix_of_mix_waveforms, mixture_waveforms_1mix], axis=0) else: input_waveforms = mix_of_mix_waveforms # Separate the input waveforms. separated_waveforms = separate_waveforms(input_waveforms, hparams) # In eval mode, split into separated from MoMs and from single mixtures. if mode == tf.estimator.ModeKeys.EVAL: # Separated sources from single mixtures. separated_waveforms_1mix = separated_waveforms[batch_size // 2:, :, :] # Separated sources from MoMs. separated_waveforms = separated_waveforms[:batch_size // 2, :, :] predictions = {'separated_waveforms': separated_waveforms} if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # Get reference sources. source_waveforms = features['source_images'][:, :, 0] max_sources = signal_util.static_or_dynamic_dim_size(source_waveforms, 1) source_waveforms_1mix = tf.concat([source_waveforms, tf.zeros_like(source_waveforms)], axis=1) if batch_size > 1: source_waveforms = tf.reshape(source_waveforms, (batch_size // 2, 2 * max_sources, -1)) else: source_waveforms = tf.concat([source_waveforms, tf.zeros_like(source_waveforms)], axis=1) # MixIT loss. loss, _ = mixit.apply(log_mse_loss, mixture_waveforms, separated_waveforms) loss = tf.identity(tf.reduce_mean(loss), name='loss_mixit') tf.losses.add_loss(loss) # Build the optimizer. loss = tf.losses.get_total_loss() learning_rate = tf.train.exponential_decay( hparams.lr, tf.train.get_or_create_global_step(), decay_steps=hparams.lr_decay_steps, decay_rate=hparams.lr_decay_rate) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) if params.get('use_tpu', False): optimizer = tf.tpu.CrossShardOptimizer(optimizer) # Build the train_op. train_op = optimizer.minimize( loss, global_step=tf.compat.v1.train.get_or_create_global_step()) # Permute separated to match references for summaries. unique_signal_types = list(set(hparams.signal_types)) loss_fns = {signal_type: log_mse_loss for signal_type in unique_signal_types} _, separated_waveforms = groupwise.apply( loss_fns, hparams.signal_types, source_waveforms, separated_waveforms, unique_signal_types) if mode == tf.estimator.ModeKeys.EVAL: # Also align sources separated from single mixtures. _, separated_waveforms_1mix = groupwise.apply( loss_fns, hparams.signal_types, source_waveforms_1mix, separated_waveforms_1mix, unique_signal_types) # In eval mode, evaluate separated from single mixtures, instead of from MoMs. if mode == tf.estimator.ModeKeys.EVAL: separated_waveforms = separated_waveforms_1mix source_waveforms = source_waveforms_1mix mix_of_mix_waveforms = mixture_waveforms_1mix # Compute spectrograms to be used in summaries. transformer = signal_transformer.SignalTransformer( sample_rate=hparams.sr, window_time_seconds=hparams.ws, hop_time_seconds=hparams.hs) source_spectrograms = transformer.forward(source_waveforms) mixture_spectrograms = transformer.forward(mix_of_mix_waveforms) separated_spectrograms = transformer.forward(separated_waveforms) summary_dict = {} # Audio summaries. summary_dict['audio'] = summaries.compute_audio_summaries( signal_names=hparams.signal_names, separated_waveforms=separated_waveforms, source_waveforms=source_waveforms, mixture_waveforms=mix_of_mix_waveforms) # Spectrogram image summaries. summary_dict['images'] = summaries.compute_spectrogram_summaries( signal_names=hparams.signal_names, separated_spectrograms=separated_spectrograms, source_spectrograms=source_spectrograms, mixture_spectrograms=mixture_spectrograms) scalars = {} weights = {} # Only compute scalar summaries for nonzero reference sources. source_is_nonzero = _weights_for_nonzero_refs(source_waveforms) # Metrics for single-source examples. weights_1src = tf.logical_and( source_is_nonzero, _weights_for_num_sources(source_waveforms, 1)) scalars_1src, weights_1src = summaries.scalar_snr_metrics_weighted( hparams.signal_names, separated_waveforms, source_waveforms, mix_of_mix_waveforms, weights_1src) scalars.update({name + '_1src_ref_nonzero': value for name, value in scalars_1src.items()}) weights.update({name + '_1src_ref_nonzero': value for name, value in weights_1src.items()}) # Metrics for multi-source examples. max_sources = len(hparams.signal_names) if max_sources > 1: weights_multisource = _weights_for_num_sources(source_waveforms, 2) for num_sources in range(3, max_sources + 1): weights_multisource = tf.logical_or( weights_multisource, _weights_for_num_sources(source_waveforms, num_sources)) weights_multisource = tf.logical_and(source_is_nonzero, weights_multisource) scalars_msrc, weights_msrc = summaries.scalar_snr_metrics_weighted( hparams.signal_names, separated_waveforms, source_waveforms, mix_of_mix_waveforms, weights_multisource) scalars.update({name + '_min2src_ref_nonzero': value for name, value in scalars_msrc.items()}) weights.update({name + '_min2src_ref_nonzero': value for name, value in weights_msrc.items()}) summary_dict['scalars'] = scalars summary_util.create_summaries(sample_rate=hparams.sr, **summary_dict) metrics = {name: tf.metrics.mean(s, weights=weights.get(name, None)) for name, s in scalars.items()} logging_hook = tf.train.LoggingTensorHook({'loss': loss}, every_n_secs=10) return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=loss, eval_metric_ops=metrics, train_op=train_op, training_hooks=[logging_hook])
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "del", "labels", "hparams", "=", "params", "[", "'hparams'", "]", "mixture_waveforms", "=", "features", "[", "'receiver_audio'", "]", "batch_size", "=", "signal_util", "...
https://github.com/google-research/sound-separation/blob/0b23ae22123b041b9538295f32a92151cb77bff9/models/neurips2020_mixit/model.py#L317-L504
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/parametertree/Parameter.py
python
Parameter.clearChildren
(self)
Remove all child parameters.
Remove all child parameters.
[ "Remove", "all", "child", "parameters", "." ]
def clearChildren(self): """Remove all child parameters.""" for ch in self.childs[:]: self.removeChild(ch)
[ "def", "clearChildren", "(", "self", ")", ":", "for", "ch", "in", "self", ".", "childs", "[", ":", "]", ":", "self", ".", "removeChild", "(", "ch", ")" ]
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/parametertree/Parameter.py#L592-L595
mlrun/mlrun
4c120719d64327a34b7ee1ab08fb5e01b258b00a
mlrun/frameworks/tf_keras/mlrun_interface.py
python
TFKerasMLRunInterface.note_rank_0_callback
(self, callback_name: str)
Note an additional custom callback to be applied only on rank 0 when using horovod. :param callback_name: The name of the callback.
Note an additional custom callback to be applied only on rank 0 when using horovod.
[ "Note", "an", "additional", "custom", "callback", "to", "be", "applied", "only", "on", "rank", "0", "when", "using", "horovod", "." ]
def note_rank_0_callback(self, callback_name: str): """ Note an additional custom callback to be applied only on rank 0 when using horovod. :param callback_name: The name of the callback. """ self._RANK_0_ONLY_CALLBACKS.append(callback_name)
[ "def", "note_rank_0_callback", "(", "self", ",", "callback_name", ":", "str", ")", ":", "self", ".", "_RANK_0_ONLY_CALLBACKS", ".", "append", "(", "callback_name", ")" ]
https://github.com/mlrun/mlrun/blob/4c120719d64327a34b7ee1ab08fb5e01b258b00a/mlrun/frameworks/tf_keras/mlrun_interface.py#L232-L238
tensorwerk/hangar-py
a6deb22854a6c9e9709011b91c1c0eeda7f47bb0
src/hangar/records/commiting.py
python
_commit_ref
(stageenv: lmdb.Environment)
return res
Query and format all staged data records, and format it for ref storage. Parameters ---------- stageenv : lmdb.Environment lmdb environment where the staged record data is actually stored. Returns ------- DigestAndBytes Serialized and compressed version of all staged record data along with digest of commit refs.
Query and format all staged data records, and format it for ref storage.
[ "Query", "and", "format", "all", "staged", "data", "records", "and", "format", "it", "for", "ref", "storage", "." ]
def _commit_ref(stageenv: lmdb.Environment) -> DigestAndBytes: """Query and format all staged data records, and format it for ref storage. Parameters ---------- stageenv : lmdb.Environment lmdb environment where the staged record data is actually stored. Returns ------- DigestAndBytes Serialized and compressed version of all staged record data along with digest of commit refs. """ from .queries import RecordQuery # needed to avoid cyclic import querys = RecordQuery(dataenv=stageenv) allRecords = tuple(querys._traverse_all_records()) res = commit_ref_db_val_from_raw_val(allRecords) return res
[ "def", "_commit_ref", "(", "stageenv", ":", "lmdb", ".", "Environment", ")", "->", "DigestAndBytes", ":", "from", ".", "queries", "import", "RecordQuery", "# needed to avoid cyclic import", "querys", "=", "RecordQuery", "(", "dataenv", "=", "stageenv", ")", "allRe...
https://github.com/tensorwerk/hangar-py/blob/a6deb22854a6c9e9709011b91c1c0eeda7f47bb0/src/hangar/records/commiting.py#L457-L476
stephenmcd/mezzanine
e38ffc69f732000ce44b7ed5c9d0516d258b8af2
mezzanine/utils/email.py
python
send_mail_template
( subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, addr_bcc=None, headers=None, )
Send email rendering text and html versions for the specified template name using the context dictionary passed in.
Send email rendering text and html versions for the specified template name using the context dictionary passed in.
[ "Send", "email", "rendering", "text", "and", "html", "versions", "for", "the", "specified", "template", "name", "using", "the", "context", "dictionary", "passed", "in", "." ]
def send_mail_template( subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, addr_bcc=None, headers=None, ): """ Send email rendering text and html versions for the specified template name using the context dictionary passed in. """ if context is None: context = {} if attachments is None: attachments = [] if fail_silently is None: fail_silently = settings.EMAIL_FAIL_SILENTLY # Add template accessible settings from Mezzanine to the context # (normally added by a context processor for HTTP requests). context.update(context_settings()) # Allow for a single address to be passed in. # Python 3 strings have an __iter__ method, so the following hack # doesn't work: if not hasattr(addr_to, "__iter__"): if isinstance(addr_to, str) or isinstance(addr_to, bytes): addr_to = [addr_to] if addr_bcc is not None and ( isinstance(addr_bcc, str) or isinstance(addr_bcc, bytes) ): addr_bcc = [addr_bcc] # Loads a template passing in vars as context. render = lambda type: loader.get_template(f"{template}.{type}").render(context) # Create and send email. msg = EmailMultiAlternatives( subject, render("txt"), addr_from, addr_to, addr_bcc, headers=headers ) msg.attach_alternative(render("html"), "text/html") for attachment in attachments: msg.attach(*attachment) msg.send(fail_silently=fail_silently)
[ "def", "send_mail_template", "(", "subject", ",", "template", ",", "addr_from", ",", "addr_to", ",", "context", "=", "None", ",", "attachments", "=", "None", ",", "fail_silently", "=", "None", ",", "addr_bcc", "=", "None", ",", "headers", "=", "None", ",",...
https://github.com/stephenmcd/mezzanine/blob/e38ffc69f732000ce44b7ed5c9d0516d258b8af2/mezzanine/utils/email.py#L29-L71
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/mutagen/id3/_frames.py
python
Frame.pprint
(self)
return "%s=%s" % (type(self).__name__, self._pprint())
Return a human-readable representation of the frame.
Return a human-readable representation of the frame.
[ "Return", "a", "human", "-", "readable", "representation", "of", "the", "frame", "." ]
def pprint(self): """Return a human-readable representation of the frame.""" return "%s=%s" % (type(self).__name__, self._pprint())
[ "def", "pprint", "(", "self", ")", ":", "return", "\"%s=%s\"", "%", "(", "type", "(", "self", ")", ".", "__name__", ",", "self", ".", "_pprint", "(", ")", ")" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/mutagen/id3/_frames.py#L208-L210
wrye-bash/wrye-bash
d495c47cfdb44475befa523438a40c4419cb386f
Mopy/bash/gui/combos.py
python
DoubleListBox.left_items
(self)
return self._left_list.lb_get_str_items()
Returns a list of the items in the left list.
Returns a list of the items in the left list.
[ "Returns", "a", "list", "of", "the", "items", "in", "the", "left", "list", "." ]
def left_items(self): """Returns a list of the items in the left list.""" return self._left_list.lb_get_str_items()
[ "def", "left_items", "(", "self", ")", ":", "return", "self", ".", "_left_list", ".", "lb_get_str_items", "(", ")" ]
https://github.com/wrye-bash/wrye-bash/blob/d495c47cfdb44475befa523438a40c4419cb386f/Mopy/bash/gui/combos.py#L152-L154
zlai0/MAST
a57b043ca597b9b7ef6842b1fa965c9f1ee71526
models/resnet.py
python
resnet101
(pretrained=False, progress=True, **kwargs)
return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
r"""ResNet-101 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>'_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
r"""ResNet-101 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>'_
[ "r", "ResNet", "-", "101", "model", "from", "Deep", "Residual", "Learning", "for", "Image", "Recognition", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1512", ".", "03385", ".", "pdf", ">", "_" ]
def resnet101(pretrained=False, progress=True, **kwargs): r"""ResNet-101 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>'_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
[ "def", "resnet101", "(", "pretrained", "=", "False", ",", "progress", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "_resnet", "(", "'resnet101'", ",", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "pretrained", ...
https://github.com/zlai0/MAST/blob/a57b043ca597b9b7ef6842b1fa965c9f1ee71526/models/resnet.py#L253-L262
pyscf/pyscf
0adfb464333f5ceee07b664f291d4084801bae64
pyscf/pbc/tdscf/krhf_slow_supercell.py
python
PhysERI.eri_mknj
(self, item, pairs_row=None, pairs_column=None)
return r / len(self.model.kpts)
Retrieves the merged ERI block using 'mknj' notation with all k-indexes. Args: item (str): a 4-character string of 'mknj' letters; pairs_row (Iterable): iterator for pairs of row k-points (first index in the output matrix); pairs_column (Iterable): iterator for pairs of column k-points (second index in the output matrix); Returns: The corresponding block of ERI (phys notation).
Retrieves the merged ERI block using 'mknj' notation with all k-indexes. Args: item (str): a 4-character string of 'mknj' letters; pairs_row (Iterable): iterator for pairs of row k-points (first index in the output matrix); pairs_column (Iterable): iterator for pairs of column k-points (second index in the output matrix);
[ "Retrieves", "the", "merged", "ERI", "block", "using", "mknj", "notation", "with", "all", "k", "-", "indexes", ".", "Args", ":", "item", "(", "str", ")", ":", "a", "4", "-", "character", "string", "of", "mknj", "letters", ";", "pairs_row", "(", "Iterab...
def eri_mknj(self, item, pairs_row=None, pairs_column=None): """ Retrieves the merged ERI block using 'mknj' notation with all k-indexes. Args: item (str): a 4-character string of 'mknj' letters; pairs_row (Iterable): iterator for pairs of row k-points (first index in the output matrix); pairs_column (Iterable): iterator for pairs of column k-points (second index in the output matrix); Returns: The corresponding block of ERI (phys notation). """ if pairs_row is None: pairs_row = product(range(len(self.model.kpts)), range(len(self.model.kpts))) if pairs_column is None: pairs_column = product(range(len(self.model.kpts)), range(len(self.model.kpts))) # Second index has to support re-iterations pairs_column = tuple(pairs_column) result = [] for k1, k2 in pairs_row: result.append([]) for k3, k4 in pairs_column: result[-1].append(self.eri_mknj_k(item, (k1, k2, k3, k4))) r = numpy.block(result) return r / len(self.model.kpts)
[ "def", "eri_mknj", "(", "self", ",", "item", ",", "pairs_row", "=", "None", ",", "pairs_column", "=", "None", ")", ":", "if", "pairs_row", "is", "None", ":", "pairs_row", "=", "product", "(", "range", "(", "len", "(", "self", ".", "model", ".", "kpts...
https://github.com/pyscf/pyscf/blob/0adfb464333f5ceee07b664f291d4084801bae64/pyscf/pbc/tdscf/krhf_slow_supercell.py#L132-L156
python-telegram-bot/python-telegram-bot
ade1529986f5b6d394a65372d6a27045a70725b2
telegram/files/chatphoto.py
python
ChatPhoto.__init__
( self, small_file_id: str, small_file_unique_id: str, big_file_id: str, big_file_unique_id: str, bot: 'Bot' = None, **_kwargs: Any, )
[]
def __init__( self, small_file_id: str, small_file_unique_id: str, big_file_id: str, big_file_unique_id: str, bot: 'Bot' = None, **_kwargs: Any, ): self.small_file_id = small_file_id self.small_file_unique_id = small_file_unique_id self.big_file_id = big_file_id self.big_file_unique_id = big_file_unique_id self.bot = bot self._id_attrs = ( self.small_file_unique_id, self.big_file_unique_id, )
[ "def", "__init__", "(", "self", ",", "small_file_id", ":", "str", ",", "small_file_unique_id", ":", "str", ",", "big_file_id", ":", "str", ",", "big_file_unique_id", ":", "str", ",", "bot", ":", "'Bot'", "=", "None", ",", "*", "*", "_kwargs", ":", "Any",...
https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/telegram/files/chatphoto.py#L77-L96
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Demo/tkinter/ttk/ttkcalendar.py
python
Calendar.__place_widgets
(self)
[]
def __place_widgets(self): # header frame and its widgets hframe = ttk.Frame(self) lbtn = ttk.Button(hframe, style='L.TButton', command=self._prev_month) rbtn = ttk.Button(hframe, style='R.TButton', command=self._next_month) self._header = ttk.Label(hframe, width=15, anchor='center') # the calendar self._calendar = ttk.Treeview(show='', selectmode='none', height=7) # pack the widgets hframe.pack(in_=self, side='top', pady=4, anchor='center') lbtn.grid(in_=hframe) self._header.grid(in_=hframe, column=1, row=0, padx=12) rbtn.grid(in_=hframe, column=2, row=0) self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
[ "def", "__place_widgets", "(", "self", ")", ":", "# header frame and its widgets", "hframe", "=", "ttk", ".", "Frame", "(", "self", ")", "lbtn", "=", "ttk", ".", "Button", "(", "hframe", ",", "style", "=", "'L.TButton'", ",", "command", "=", "self", ".", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Demo/tkinter/ttk/ttkcalendar.py#L90-L104
czhu95/ternarynet
1a67251f7f5a1cdf854f87f90f841655c7c9f11c
tensorpack/train/base.py
python
Trainer._start_concurrency
(self)
Run all threads before starting training
Run all threads before starting training
[ "Run", "all", "threads", "before", "starting", "training" ]
def _start_concurrency(self): """ Run all threads before starting training """ logger.info("Starting all threads & procs ...") tf.train.start_queue_runners( sess=self.sess, coord=self.coord, daemon=True, start=True) with self.sess.as_default(): # avoid sigint get handled by other processes start_proc_mask_signal(self._extra_threads_procs)
[ "def", "_start_concurrency", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Starting all threads & procs ...\"", ")", "tf", ".", "train", ".", "start_queue_runners", "(", "sess", "=", "self", ".", "sess", ",", "coord", "=", "self", ".", "coord", ",", ...
https://github.com/czhu95/ternarynet/blob/1a67251f7f5a1cdf854f87f90f841655c7c9f11c/tensorpack/train/base.py#L147-L157
mme/vergeml
3dc30ba4e0f3d038743b6d468860cbcf3681acc6
vergeml/config.py
python
_parse_device_memory
(res, section)
Parse the memory option in the device section.
Parse the memory option in the device section.
[ "Parse", "the", "memory", "option", "in", "the", "device", "section", "." ]
def _parse_device_memory(res, section): """Parse the memory option in the device section. """ if 'memory' in section: value = section['memory'].strip() if isinstance(value, float): if value < 0. or value > 1.: raise _invalid_option('device.memory', 'device') res['memory'] = value if value != 'auto': if not re.match(r'^[0-9]+(\.[0-9]*)?%$', value): raise _invalid_option('device.memory', 'device') try: value = float(value.rstrip('%')) except ValueError: raise _invalid_option('device.memory', 'device') if value < 0. or value > 100.: raise _invalid_option('device.memory', 'device') res['memory'] = value/100
[ "def", "_parse_device_memory", "(", "res", ",", "section", ")", ":", "if", "'memory'", "in", "section", ":", "value", "=", "section", "[", "'memory'", "]", ".", "strip", "(", ")", "if", "isinstance", "(", "value", ",", "float", ")", ":", "if", "value",...
https://github.com/mme/vergeml/blob/3dc30ba4e0f3d038743b6d468860cbcf3681acc6/vergeml/config.py#L67-L93
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/gui/win32k_core.py
python
_MM_SESSION_SPACE.find_shared_info
(self)
return obj.NoneObject("Cannot find win32k!gSharedInfo")
Find this session's tagSHAREDINFO structure. This structure is embedded in win32k's .data section, (i.e. not in dynamically allocated memory). Thus we iterate over each DWORD-aligned possibility and treat it as a tagSHAREDINFO until the sanity checks are met.
Find this session's tagSHAREDINFO structure.
[ "Find", "this", "session", "s", "tagSHAREDINFO", "structure", "." ]
def find_shared_info(self): """Find this session's tagSHAREDINFO structure. This structure is embedded in win32k's .data section, (i.e. not in dynamically allocated memory). Thus we iterate over each DWORD-aligned possibility and treat it as a tagSHAREDINFO until the sanity checks are met. """ for chunk in self._section_chunks(".data"): # If the base of the value is paged if not chunk.is_valid(): continue # Treat it as a shared info struct shared_info = obj.Object("tagSHAREDINFO", offset = chunk.obj_offset, vm = self.obj_vm) # Sanity check it try: if shared_info.is_valid(): return shared_info except obj.InvalidOffsetError: pass return obj.NoneObject("Cannot find win32k!gSharedInfo")
[ "def", "find_shared_info", "(", "self", ")", ":", "for", "chunk", "in", "self", ".", "_section_chunks", "(", "\".data\"", ")", ":", "# If the base of the value is paged", "if", "not", "chunk", ".", "is_valid", "(", ")", ":", "continue", "# Treat it as a shared inf...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/gui/win32k_core.py#L150-L173
posativ/acrylamid
222e2eb7b33924138498ff8186dff9f0aeb78cea
acrylamid/views/sitemap.py
python
Sitemap.context
(self, conf, env, data)
return env
If resources are included in sitemap, create a map for each entry and its resources, so they can be include in <url>
If resources are included in sitemap, create a map for each entry and its resources, so they can be include in <url>
[ "If", "resources", "are", "included", "in", "sitemap", "create", "a", "map", "for", "each", "entry", "and", "its", "resources", "so", "they", "can", "be", "include", "in", "<url", ">" ]
def context(self, conf, env, data): """If resources are included in sitemap, create a map for each entry and its resources, so they can be include in <url>""" if self.imgext: self.mapping = dict([(entry.permalink, entry.resources) for entry in data['entrylist']]) return env
[ "def", "context", "(", "self", ",", "conf", ",", "env", ",", "data", ")", ":", "if", "self", ".", "imgext", ":", "self", ".", "mapping", "=", "dict", "(", "[", "(", "entry", ".", "permalink", ",", "entry", ".", "resources", ")", "for", "entry", "...
https://github.com/posativ/acrylamid/blob/222e2eb7b33924138498ff8186dff9f0aeb78cea/acrylamid/views/sitemap.py#L83-L91
NiaOrg/NiaPy
08f24ffc79fe324bc9c66ee7186ef98633026005
niapy/problems/sphere.py
python
Sphere.__init__
(self, dimension=4, lower=-5.12, upper=5.12, *args, **kwargs)
r"""Initialize Sphere problem.. Args: dimension (Optional[int]): Dimension of the problem. lower (Optional[Union[float, Iterable[float]]]): Lower bounds of the problem. upper (Optional[Union[float, Iterable[float]]]): Upper bounds of the problem. See Also: :func:`niapy.problems.Problem.__init__`
r"""Initialize Sphere problem..
[ "r", "Initialize", "Sphere", "problem", ".." ]
def __init__(self, dimension=4, lower=-5.12, upper=5.12, *args, **kwargs): r"""Initialize Sphere problem.. Args: dimension (Optional[int]): Dimension of the problem. lower (Optional[Union[float, Iterable[float]]]): Lower bounds of the problem. upper (Optional[Union[float, Iterable[float]]]): Upper bounds of the problem. See Also: :func:`niapy.problems.Problem.__init__` """ super().__init__(dimension, lower, upper, *args, **kwargs)
[ "def", "__init__", "(", "self", ",", "dimension", "=", "4", ",", "lower", "=", "-", "5.12", ",", "upper", "=", "5.12", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "dimension", ",", "lower", ",", ...
https://github.com/NiaOrg/NiaPy/blob/08f24ffc79fe324bc9c66ee7186ef98633026005/niapy/problems/sphere.py#L48-L60
PlasmaPy/PlasmaPy
78d63e341216475ce3318e1409296480407c9019
plasmapy/particles/particle_class.py
python
Particle.element
(self)
return self._attributes["element"]
The atomic symbol if the particle corresponds to an element, and `None` otherwise. Examples -------- >>> alpha = Particle('alpha') >>> alpha.element 'He'
The atomic symbol if the particle corresponds to an element, and `None` otherwise.
[ "The", "atomic", "symbol", "if", "the", "particle", "corresponds", "to", "an", "element", "and", "None", "otherwise", "." ]
def element(self) -> Optional[str]: """ The atomic symbol if the particle corresponds to an element, and `None` otherwise. Examples -------- >>> alpha = Particle('alpha') >>> alpha.element 'He' """ return self._attributes["element"]
[ "def", "element", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_attributes", "[", "\"element\"", "]" ]
https://github.com/PlasmaPy/PlasmaPy/blob/78d63e341216475ce3318e1409296480407c9019/plasmapy/particles/particle_class.py#L780-L791
tacnetsol/ida
faf13a13c4f5070fe8f0666c1508f928ffe40e23
plugins/shims/ida_shims.py
python
get_canon_feature
(insn)
return idaapi.cmd.get_canon_feature()
Get operands for the provided instruction. :return:
Get operands for the provided instruction.
[ "Get", "operands", "for", "the", "provided", "instruction", "." ]
def get_canon_feature(insn): ''' Get operands for the provided instruction. :return: ''' if idaapi.IDA_SDK_VERSION >= 700: return insn.get_canon_feature() return idaapi.cmd.get_canon_feature()
[ "def", "get_canon_feature", "(", "insn", ")", ":", "if", "idaapi", ".", "IDA_SDK_VERSION", ">=", "700", ":", "return", "insn", ".", "get_canon_feature", "(", ")", "return", "idaapi", ".", "cmd", ".", "get_canon_feature", "(", ")" ]
https://github.com/tacnetsol/ida/blob/faf13a13c4f5070fe8f0666c1508f928ffe40e23/plugins/shims/ida_shims.py#L558-L566
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
rpython/jit/backend/arm/assembler.py
python
AssemblerARM._check_frame_depth_debug
(self, mc)
double check the depth size. It prints the error (and potentially segfaults later)
double check the depth size. It prints the error (and potentially segfaults later)
[ "double", "check", "the", "depth", "size", ".", "It", "prints", "the", "error", "(", "and", "potentially", "segfaults", "later", ")" ]
def _check_frame_depth_debug(self, mc): """ double check the depth size. It prints the error (and potentially segfaults later) """ if not self.DEBUG_FRAME_DEPTH: return descrs = self.cpu.gc_ll_descr.getframedescrs(self.cpu) ofs = self.cpu.unpack_fielddescr(descrs.arraydescr.lendescr) mc.LDR_ri(r.ip.value, r.fp.value, imm=ofs) stack_check_cmp_ofs = mc.currpos() for _ in range(mc.get_max_size_of_gen_load_int()): mc.NOP() mc.CMP_rr(r.ip.value, r.lr.value) jg_location = mc.currpos() mc.BKPT() mc.MOV_rr(r.r0.value, r.fp.value) mc.MOV_ri(r.r1.value, r.lr.value) self.mc.BL(self.cpu.realloc_frame_crash) # patch the JG above currpos = self.mc.currpos() pmc = OverwritingBuilder(mc, jg_location, WORD) pmc.B_offs(currpos, c.GE) self.frame_depth_to_patch.append(stack_check_cmp_ofs)
[ "def", "_check_frame_depth_debug", "(", "self", ",", "mc", ")", ":", "if", "not", "self", ".", "DEBUG_FRAME_DEPTH", ":", "return", "descrs", "=", "self", ".", "cpu", ".", "gc_ll_descr", ".", "getframedescrs", "(", "self", ".", "cpu", ")", "ofs", "=", "se...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/jit/backend/arm/assembler.py#L870-L896
HonglinChu/SiamTrackers
8471660b14f970578a43f077b28207d44a27e867
SiamRPN/SiamRPN/siamrpn/transforms.py
python
RandomStretch.__call__
(self, sample)
return cv2.resize(sample, shape, cv2.INTER_LINEAR)
Args: sample(numpy array): 3 or 1 dim image
Args: sample(numpy array): 3 or 1 dim image
[ "Args", ":", "sample", "(", "numpy", "array", ")", ":", "3", "or", "1", "dim", "image" ]
def __call__(self, sample): """ Args: sample(numpy array): 3 or 1 dim image """ scale_h = 1.0 + np.random.uniform(-self.max_stretch, self.max_stretch) scale_w = 1.0 + np.random.uniform(-self.max_stretch, self.max_stretch) h, w = sample.shape[:2] shape = int(w * scale_w), int(h * scale_h) return cv2.resize(sample, shape, cv2.INTER_LINEAR)
[ "def", "__call__", "(", "self", ",", "sample", ")", ":", "scale_h", "=", "1.0", "+", "np", ".", "random", ".", "uniform", "(", "-", "self", ".", "max_stretch", ",", "self", ".", "max_stretch", ")", "scale_w", "=", "1.0", "+", "np", ".", "random", "...
https://github.com/HonglinChu/SiamTrackers/blob/8471660b14f970578a43f077b28207d44a27e867/SiamRPN/SiamRPN/siamrpn/transforms.py#L20-L29
cbfinn/maml
a7f45f1bcd7457fe97b227a21e89b8a82cc5fa49
maml.py
python
MAML.construct_conv_weights
(self)
return weights
[]
def construct_conv_weights(self): weights = {} dtype = tf.float32 conv_initializer = tf.contrib.layers.xavier_initializer_conv2d(dtype=dtype) fc_initializer = tf.contrib.layers.xavier_initializer(dtype=dtype) k = 3 weights['conv1'] = tf.get_variable('conv1', [k, k, self.channels, self.dim_hidden], initializer=conv_initializer, dtype=dtype) weights['b1'] = tf.Variable(tf.zeros([self.dim_hidden])) weights['conv2'] = tf.get_variable('conv2', [k, k, self.dim_hidden, self.dim_hidden], initializer=conv_initializer, dtype=dtype) weights['b2'] = tf.Variable(tf.zeros([self.dim_hidden])) weights['conv3'] = tf.get_variable('conv3', [k, k, self.dim_hidden, self.dim_hidden], initializer=conv_initializer, dtype=dtype) weights['b3'] = tf.Variable(tf.zeros([self.dim_hidden])) weights['conv4'] = tf.get_variable('conv4', [k, k, self.dim_hidden, self.dim_hidden], initializer=conv_initializer, dtype=dtype) weights['b4'] = tf.Variable(tf.zeros([self.dim_hidden])) if FLAGS.datasource == 'miniimagenet': # assumes max pooling weights['w5'] = tf.get_variable('w5', [self.dim_hidden*5*5, self.dim_output], initializer=fc_initializer) weights['b5'] = tf.Variable(tf.zeros([self.dim_output]), name='b5') else: weights['w5'] = tf.Variable(tf.random_normal([self.dim_hidden, self.dim_output]), name='w5') weights['b5'] = tf.Variable(tf.zeros([self.dim_output]), name='b5') return weights
[ "def", "construct_conv_weights", "(", "self", ")", ":", "weights", "=", "{", "}", "dtype", "=", "tf", ".", "float32", "conv_initializer", "=", "tf", ".", "contrib", ".", "layers", ".", "xavier_initializer_conv2d", "(", "dtype", "=", "dtype", ")", "fc_initial...
https://github.com/cbfinn/maml/blob/a7f45f1bcd7457fe97b227a21e89b8a82cc5fa49/maml.py#L185-L208
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/logging/handlers.py
python
MemoryHandler.close
(self)
Flush, set the target to None and lose the buffer.
Flush, set the target to None and lose the buffer.
[ "Flush", "set", "the", "target", "to", "None", "and", "lose", "the", "buffer", "." ]
def close(self): """ Flush, set the target to None and lose the buffer. """ self.flush() self.target = None BufferingHandler.close(self)
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "self", ".", "target", "=", "None", "BufferingHandler", ".", "close", "(", "self", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/logging/handlers.py#L1152-L1158
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/pymongo/pool.py
python
Pool.__del__
(self)
[]
def __del__(self): # Avoid ResourceWarnings in Python 3 for sock_info in self.sockets: sock_info.close()
[ "def", "__del__", "(", "self", ")", ":", "# Avoid ResourceWarnings in Python 3", "for", "sock_info", "in", "self", ".", "sockets", ":", "sock_info", ".", "close", "(", ")" ]
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/pymongo/pool.py#L635-L638
albertz/music-player
d23586f5bf657cbaea8147223be7814d117ae73d
mac/pyobjc-framework-Cocoa/Examples/AppKit/PackageManager/packman.py
python
setString
(field, value)
Set an NSTextField to the specified value. Clears the field if 'value' is None.
Set an NSTextField to the specified value. Clears the field if 'value' is None.
[ "Set", "an", "NSTextField", "to", "the", "specified", "value", ".", "Clears", "the", "field", "if", "value", "is", "None", "." ]
def setString(field, value): """ Set an NSTextField to the specified value. Clears the field if 'value' is None. """ if value is None: field.setStringValue_("") else: field.setStringValue_(value)
[ "def", "setString", "(", "field", ",", "value", ")", ":", "if", "value", "is", "None", ":", "field", ".", "setStringValue_", "(", "\"\"", ")", "else", ":", "field", ".", "setStringValue_", "(", "value", ")" ]
https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-framework-Cocoa/Examples/AppKit/PackageManager/packman.py#L40-L48
yinwenpeng/Attentive_Convolution
92461591999cd4594e025d31a223b754cbe167f9
src/word2embeddings/nn/networks.py
python
SimpleVLblNce._create_adagrad_matrices
(self)
Create AdaGrad gradient matrices for all updatable variables. New matrices are only created if they don't exist yet, i.e., if a model was loaded, the already existing matrices are not overwritten. the matrices contain the sum of squared gradients for all parameters in the model. Caution: Do not put the matrices into a dict. In that case pickling does not work.
Create AdaGrad gradient matrices for all updatable variables.
[ "Create", "AdaGrad", "gradient", "matrices", "for", "all", "updatable", "variables", "." ]
def _create_adagrad_matrices(self): """Create AdaGrad gradient matrices for all updatable variables. New matrices are only created if they don't exist yet, i.e., if a model was loaded, the already existing matrices are not overwritten. the matrices contain the sum of squared gradients for all parameters in the model. Caution: Do not put the matrices into a dict. In that case pickling does not work. """ for p in self.updatable_parameters: name = 'adagrad_matrix_' + p # Have we already created the gradient matrices? This might happen after # we loaded a model. if name in self.__dict__: continue self.__dict__[name] = \ theano.shared(np.zeros(self.__dict__[p].shape.eval(), dtype=floatX), name='adagrad_matrix_' + p)
[ "def", "_create_adagrad_matrices", "(", "self", ")", ":", "for", "p", "in", "self", ".", "updatable_parameters", ":", "name", "=", "'adagrad_matrix_'", "+", "p", "# Have we already created the gradient matrices? This might happen after", "# we loaded a model.", "if", "name"...
https://github.com/yinwenpeng/Attentive_Convolution/blob/92461591999cd4594e025d31a223b754cbe167f9/src/word2embeddings/nn/networks.py#L410-L431
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/scapy/route.py
python
Route.add
(self, *args, **kargs)
Ex: add(net="192.168.1.0/24",gw="1.2.3.4")
Ex: add(net="192.168.1.0/24",gw="1.2.3.4")
[ "Ex", ":", "add", "(", "net", "=", "192", ".", "168", ".", "1", ".", "0", "/", "24", "gw", "=", "1", ".", "2", ".", "3", ".", "4", ")" ]
def add(self, *args, **kargs): """Ex: add(net="192.168.1.0/24",gw="1.2.3.4") """ self.invalidate_cache() self.routes.append(self.make_route(*args,**kargs))
[ "def", "add", "(", "self", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "self", ".", "invalidate_cache", "(", ")", "self", ".", "routes", ".", "append", "(", "self", ".", "make_route", "(", "*", "args", ",", "*", "*", "kargs", ")", ")" ]
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/route.py#L59-L64
vslavik/bakefile
0757295c3e4ac23cd1e0767c77c14c2256ed16e1
3rdparty/antlr3/python-runtime/antlr3/streams.py
python
TokenStream.toString
(self, start=None, stop=None)
Return the text of all tokens from start to stop, inclusive. If the stream does not buffer all the tokens then it can just return "" or null; Users should not access $ruleLabel.text in an action of course in that case. Because the user is not required to use a token with an index stored in it, we must provide a means for two token objects themselves to indicate the start/end location. Most often this will just delegate to the other toString(int,int). This is also parallel with the TreeNodeStream.toString(Object,Object).
Return the text of all tokens from start to stop, inclusive. If the stream does not buffer all the tokens then it can just return "" or null; Users should not access $ruleLabel.text in an action of course in that case.
[ "Return", "the", "text", "of", "all", "tokens", "from", "start", "to", "stop", "inclusive", ".", "If", "the", "stream", "does", "not", "buffer", "all", "the", "tokens", "then", "it", "can", "just", "return", "or", "null", ";", "Users", "should", "not", ...
def toString(self, start=None, stop=None): """ Return the text of all tokens from start to stop, inclusive. If the stream does not buffer all the tokens then it can just return "" or null; Users should not access $ruleLabel.text in an action of course in that case. Because the user is not required to use a token with an index stored in it, we must provide a means for two token objects themselves to indicate the start/end location. Most often this will just delegate to the other toString(int,int). This is also parallel with the TreeNodeStream.toString(Object,Object). """ raise NotImplementedError
[ "def", "toString", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/vslavik/bakefile/blob/0757295c3e4ac23cd1e0767c77c14c2256ed16e1/3rdparty/antlr3/python-runtime/antlr3/streams.py#L298-L312
kbandla/dpkt
7a91ae53bb20563607f32e6781ef40d2efe6520d
dpkt/pcap.py
python
Reader.dispatch
(self, cnt, callback, *args)
return processed
Collect and process packets with a user callback. Return the number of packets processed, or 0 for a savefile. Arguments: cnt -- number of packets to process; or 0 to process all packets until EOF callback -- function with (timestamp, pkt, *args) prototype *args -- optional arguments passed to callback on execution
Collect and process packets with a user callback.
[ "Collect", "and", "process", "packets", "with", "a", "user", "callback", "." ]
def dispatch(self, cnt, callback, *args): """Collect and process packets with a user callback. Return the number of packets processed, or 0 for a savefile. Arguments: cnt -- number of packets to process; or 0 to process all packets until EOF callback -- function with (timestamp, pkt, *args) prototype *args -- optional arguments passed to callback on execution """ processed = 0 if cnt > 0: for _ in range(cnt): try: ts, pkt = next(iter(self)) except StopIteration: break callback(ts, pkt, *args) processed += 1 else: for ts, pkt in self: callback(ts, pkt, *args) processed += 1 return processed
[ "def", "dispatch", "(", "self", ",", "cnt", ",", "callback", ",", "*", "args", ")", ":", "processed", "=", "0", "if", "cnt", ">", "0", ":", "for", "_", "in", "range", "(", "cnt", ")", ":", "try", ":", "ts", ",", "pkt", "=", "next", "(", "iter...
https://github.com/kbandla/dpkt/blob/7a91ae53bb20563607f32e6781ef40d2efe6520d/dpkt/pcap.py#L315-L340
EricssonResearch/calvin-base
bc4645c2061c30ca305a660e48dc86e3317f5b6f
calvin/runtime/south/transports/base_transport.py
python
BaseTransport.get_coder
(self)
return self._coder
Return the current coder used or none if none set
Return the current coder used or none if none set
[ "Return", "the", "current", "coder", "used", "or", "none", "if", "none", "set" ]
def get_coder(self): """ Return the current coder used or none if none set """ return self._coder
[ "def", "get_coder", "(", "self", ")", ":", "return", "self", ".", "_coder" ]
https://github.com/EricssonResearch/calvin-base/blob/bc4645c2061c30ca305a660e48dc86e3317f5b6f/calvin/runtime/south/transports/base_transport.py#L98-L102
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/compiler/ast.py
python
UnaryAdd.getChildNodes
(self)
return self.expr,
[]
def getChildNodes(self): return self.expr,
[ "def", "getChildNodes", "(", "self", ")", ":", "return", "self", ".", "expr", "," ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/ast.py#L1333-L1334
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/backends/postgresql/client.py
python
DatabaseClient.runshell
(self)
[]
def runshell(self): DatabaseClient.runshell_db(self.connection.get_connection_params())
[ "def", "runshell", "(", "self", ")", ":", "DatabaseClient", ".", "runshell_db", "(", "self", ".", "connection", ".", "get_connection_params", "(", ")", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/backends/postgresql/client.py#L65-L66
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/pyparsing.py
python
line
( loc, strg )
Returns the line of text containing loc within a string, counting newlines as line separators.
Returns the line of text containing loc within a string, counting newlines as line separators.
[ "Returns", "the", "line", "of", "text", "containing", "loc", "within", "a", "string", "counting", "newlines", "as", "line", "separators", "." ]
def line( loc, strg ): """Returns the line of text containing loc within a string, counting newlines as line separators. """ lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR+1:nextCR] else: return strg[lastCR+1:]
[ "def", "line", "(", "loc", ",", "strg", ")", ":", "lastCR", "=", "strg", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "loc", ")", "nextCR", "=", "strg", ".", "find", "(", "\"\\n\"", ",", "loc", ")", "if", "nextCR", ">=", "0", ":", "return", "st...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pyparsing.py#L970-L978
jmcnamara/XlsxWriter
fd30f221bf4326ca7814cec0d3a87a89b9e3edd5
xlsxwriter/chart_scatter.py
python
ChartScatter.combine
(self, chart=None)
Create a combination chart with a secondary chart. Note: Override parent method to add a warning. Args: chart: The secondary chart to combine with the primary chart. Returns: Nothing.
Create a combination chart with a secondary chart.
[ "Create", "a", "combination", "chart", "with", "a", "secondary", "chart", "." ]
def combine(self, chart=None): """ Create a combination chart with a secondary chart. Note: Override parent method to add a warning. Args: chart: The secondary chart to combine with the primary chart. Returns: Nothing. """ if chart is None: return warn('Combined chart not currently supported with scatter chart ' 'as the primary chart')
[ "def", "combine", "(", "self", ",", "chart", "=", "None", ")", ":", "if", "chart", "is", "None", ":", "return", "warn", "(", "'Combined chart not currently supported with scatter chart '", "'as the primary chart'", ")" ]
https://github.com/jmcnamara/XlsxWriter/blob/fd30f221bf4326ca7814cec0d3a87a89b9e3edd5/xlsxwriter/chart_scatter.py#L59-L76
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/Utils/__init__.py
python
sliceToRange
(s)
[]
def sliceToRange(s): start = s.start if s.start is not None else 0 stop = s.stop step = s.step if s.step is not None else 1 try: return list(range(start, stop, step)) except OverflowError: raise TypeError("range() integer end argument expected, got NoneType")
[ "def", "sliceToRange", "(", "s", ")", ":", "start", "=", "s", ".", "start", "if", "s", ".", "start", "is", "not", "None", "else", "0", "stop", "=", "s", ".", "stop", "step", "=", "s", ".", "step", "if", "s", ".", "step", "is", "not", "None", ...
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/Utils/__init__.py#L39-L46
facebookresearch/detectron2
cb92ae1763cd7d3777c243f07749574cdaec6cb8
detectron2/data/common.py
python
AspectRatioGroupedDataset.__init__
(self, dataset, batch_size)
Args: dataset: an iterable. Each element must be a dict with keys "width" and "height", which will be used to batch data. batch_size (int):
Args: dataset: an iterable. Each element must be a dict with keys "width" and "height", which will be used to batch data. batch_size (int):
[ "Args", ":", "dataset", ":", "an", "iterable", ".", "Each", "element", "must", "be", "a", "dict", "with", "keys", "width", "and", "height", "which", "will", "be", "used", "to", "batch", "data", ".", "batch_size", "(", "int", ")", ":" ]
def __init__(self, dataset, batch_size): """ Args: dataset: an iterable. Each element must be a dict with keys "width" and "height", which will be used to batch data. batch_size (int): """ self.dataset = dataset self.batch_size = batch_size self._buckets = [[] for _ in range(2)]
[ "def", "__init__", "(", "self", ",", "dataset", ",", "batch_size", ")", ":", "self", ".", "dataset", "=", "dataset", "self", ".", "batch_size", "=", "batch_size", "self", ".", "_buckets", "=", "[", "[", "]", "for", "_", "in", "range", "(", "2", ")", ...
https://github.com/facebookresearch/detectron2/blob/cb92ae1763cd7d3777c243f07749574cdaec6cb8/detectron2/data/common.py#L220-L229
Ha0Tang/SelectionGAN
80aa7ad9f79f643c28633c40c621f208f3fb0121
gaugan_pix2pixhd_guided/data/pix2pix_dataset.py
python
Pix2pixDataset.postprocess
(self, input_dict)
return input_dict
[]
def postprocess(self, input_dict): return input_dict
[ "def", "postprocess", "(", "self", ",", "input_dict", ")", ":", "return", "input_dict" ]
https://github.com/Ha0Tang/SelectionGAN/blob/80aa7ad9f79f643c28633c40c621f208f3fb0121/gaugan_pix2pixhd_guided/data/pix2pix_dataset.py#L100-L101
djblets/djblets
0496e1ec49e43d43d776768c9fc5b6f8af56ec2c
djblets/util/decorators.py
python
blocktag
(*args, **kwargs)
Creates a block template tag with beginning/end tags. This does all the hard work of creating a template tag that can parse the arguments passed in and then parse all nodes between a beginning and end tag (such as myblock/endmyblock). By default, the end tag is prefixed with "end", but that can be changed by passing ``end_prefix="end_"`` or similar to @blocktag. blocktag will call the wrapped function with `context` and `nodelist` parameters, as well as any parameters passed to the tag. It will also ensure that a proper error is raised if too many or too few parameters are passed. Args: end_prefix (unicode, optional): The prefix for the end tag. This defaults to ``'end'``, but template tags using underscores in the name might want to change this to ``'end_'``. resolve_vars (bool, optional): Whether to automatically resolve all variables provided to the template tag. By default, variables are resolved. Template tags can turn this off if they want to handle variable parsing manually. Returns: callable: The resulting template tag function. Example: .. code-block:: python @register.tag @blocktag def divify(context, nodelist, div_id=None): s = "<div" if div_id: s += " id='%s'" % div_id return s + ">" + nodelist.render(context) + "</div>"
Creates a block template tag with beginning/end tags.
[ "Creates", "a", "block", "template", "tag", "with", "beginning", "/", "end", "tags", "." ]
def blocktag(*args, **kwargs): """Creates a block template tag with beginning/end tags. This does all the hard work of creating a template tag that can parse the arguments passed in and then parse all nodes between a beginning and end tag (such as myblock/endmyblock). By default, the end tag is prefixed with "end", but that can be changed by passing ``end_prefix="end_"`` or similar to @blocktag. blocktag will call the wrapped function with `context` and `nodelist` parameters, as well as any parameters passed to the tag. It will also ensure that a proper error is raised if too many or too few parameters are passed. Args: end_prefix (unicode, optional): The prefix for the end tag. This defaults to ``'end'``, but template tags using underscores in the name might want to change this to ``'end_'``. resolve_vars (bool, optional): Whether to automatically resolve all variables provided to the template tag. By default, variables are resolved. Template tags can turn this off if they want to handle variable parsing manually. Returns: callable: The resulting template tag function. Example: .. code-block:: python @register.tag @blocktag def divify(context, nodelist, div_id=None): s = "<div" if div_id: s += " id='%s'" % div_id return s + ">" + nodelist.render(context) + "</div>" """ class BlockTagNode(template.Node): def __init__(self, tag_name, tag_func, nodelist, args): self.tag_name = tag_name self.tag_func = tag_func self.nodelist = nodelist self.args = args def render(self, context): if kwargs.get('resolve_vars', True): args = [Variable(var).resolve(context) for var in self.args] else: args = self.args return self.tag_func(context, self.nodelist, *args) def _blocktag_func(tag_func): def _setup_tag(parser, token): bits = token.split_contents() tag_name = bits[0] del(bits[0]) params, varargs, xxx, defaults = getargspec(tag_func) max_args = len(params) - 2 # Ignore context and nodelist min_args = max_args - len(defaults or []) if len(bits) < min_args or (not varargs and len(bits) > max_args): if not varargs and min_args == max_args: raise TemplateSyntaxError( "%r tag takes %d arguments." % (tag_name, min_args)) else: raise TemplateSyntaxError( "%r tag takes %d to %d arguments, got %d." % (tag_name, min_args, max_args, len(bits))) nodelist = parser.parse((('%s%s' % (end_prefix, tag_name)),)) parser.delete_first_token() return BlockTagNode(tag_name, tag_func, nodelist, bits) update_wrapper(_setup_tag, tag_func) return _setup_tag end_prefix = kwargs.get('end_prefix', 'end') if len(args) == 1 and callable(args[0]): # This is being called in the @blocktag form. return _blocktag_func(args[0]) else: # This is being called in the @blocktag(...) form. return _blocktag_func
[ "def", "blocktag", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "class", "BlockTagNode", "(", "template", ".", "Node", ")", ":", "def", "__init__", "(", "self", ",", "tag_name", ",", "tag_func", ",", "nodelist", ",", "args", ")", ":", "self",...
https://github.com/djblets/djblets/blob/0496e1ec49e43d43d776768c9fc5b6f8af56ec2c/djblets/util/decorators.py#L165-L258
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/engines/pcode/behavior.py
python
OpBehaviorIntSborrow.evaluate_binary
(self, size_out: int, size_in: int, in1: BV, in2: BV)
return a
[]
def evaluate_binary(self, size_out: int, size_in: int, in1: BV, in2: BV) -> BV: res = in1 - in2 a = (in1 >> (size_in * 8 - 1)) & 1 # Grab sign bit b = (in2 >> (size_in * 8 - 1)) & 1 # Grab sign bit r = (res >> (size_in * 8 - 1)) & 1 # Grab sign bit a ^= r r ^= b r ^= 1 a &= r return a
[ "def", "evaluate_binary", "(", "self", ",", "size_out", ":", "int", ",", "size_in", ":", "int", ",", "in1", ":", "BV", ",", "in2", ":", "BV", ")", "->", "BV", ":", "res", "=", "in1", "-", "in2", "a", "=", "(", "in1", ">>", "(", "size_in", "*", ...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/engines/pcode/behavior.py#L215-L226
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/db/models/options.py
python
Options.get_all_related_objects_with_model
(self, local_only=False, include_hidden=False)
return filter(lambda t: all([p(*t) for p in predicates]), self._related_objects_cache.items())
Returns a list of (related-object, model) pairs. Similar to get_fields_with_model().
Returns a list of (related-object, model) pairs. Similar to get_fields_with_model().
[ "Returns", "a", "list", "of", "(", "related", "-", "object", "model", ")", "pairs", ".", "Similar", "to", "get_fields_with_model", "()", "." ]
def get_all_related_objects_with_model(self, local_only=False, include_hidden=False): """ Returns a list of (related-object, model) pairs. Similar to get_fields_with_model(). """ try: self._related_objects_cache except AttributeError: self._fill_related_objects_cache() predicates = [] if local_only: predicates.append(lambda k, v: not v) if not include_hidden: predicates.append(lambda k, v: not k.field.rel.is_hidden()) return filter(lambda t: all([p(*t) for p in predicates]), self._related_objects_cache.items())
[ "def", "get_all_related_objects_with_model", "(", "self", ",", "local_only", "=", "False", ",", "include_hidden", "=", "False", ")", ":", "try", ":", "self", ".", "_related_objects_cache", "except", "AttributeError", ":", "self", ".", "_fill_related_objects_cache", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/db/models/options.py#L362-L378
dropbox/securitybot
8cc4846602011db396df621d2e84e5808a6f3441
scripts/query_db.py
python
main
(args)
[]
def main(args): # type: (Any) -> None if args.blacklist: fields, matrix = blacklist(args) elif args.ignored: fields, matrix = ignored(args) else: fields, matrix = alerts(args) pretty_print(fields, matrix)
[ "def", "main", "(", "args", ")", ":", "# type: (Any) -> None", "if", "args", ".", "blacklist", ":", "fields", ",", "matrix", "=", "blacklist", "(", "args", ")", "elif", "args", ".", "ignored", ":", "fields", ",", "matrix", "=", "ignored", "(", "args", ...
https://github.com/dropbox/securitybot/blob/8cc4846602011db396df621d2e84e5808a6f3441/scripts/query_db.py#L77-L86
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/index.py
python
PackageFinder._get_pages
(self, locations, project_name)
Yields (page, page_url) from the given locations, skipping locations that have errors.
Yields (page, page_url) from the given locations, skipping locations that have errors.
[ "Yields", "(", "page", "page_url", ")", "from", "the", "given", "locations", "skipping", "locations", "that", "have", "errors", "." ]
def _get_pages(self, locations, project_name): """ Yields (page, page_url) from the given locations, skipping locations that have errors. """ seen = set() for location in locations: if location in seen: continue seen.add(location) page = self._get_page(location) if page is None: continue yield page
[ "def", "_get_pages", "(", "self", ",", "locations", ",", "project_name", ")", ":", "seen", "=", "set", "(", ")", "for", "location", "in", "locations", ":", "if", "location", "in", "seen", ":", "continue", "seen", ".", "add", "(", "location", ")", "page...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/index.py#L557-L572
treeio/treeio
bae3115f4015aad2cbc5ab45572232ceec990495
treeio/projects/views.py
python
_process_mass_form
(f)
return wrap
Pre-process request to handle mass action form for Tasks and Milestones
Pre-process request to handle mass action form for Tasks and Milestones
[ "Pre", "-", "process", "request", "to", "handle", "mass", "action", "form", "for", "Tasks", "and", "Milestones" ]
def _process_mass_form(f): "Pre-process request to handle mass action form for Tasks and Milestones" def wrap(request, *args, **kwargs): "Wrap" if 'massform' in request.POST: for key in request.POST: if 'mass-milestone' in key: try: milestone = Milestone.objects.get(pk=request.POST[key]) form = MassActionForm( request.user.profile, request.POST, instance=milestone) if form.is_valid() and request.user.profile.has_permission(milestone, mode='w'): form.save() except Exception: pass for key in request.POST: if 'mass-task' in key: try: task = Task.objects.get(pk=request.POST[key]) form = MassActionForm( request.user.profile, request.POST, instance=task) if form.is_valid() and request.user.profile.has_permission(task, mode='w'): form.save() except Exception: pass return f(request, *args, **kwargs) wrap.__doc__ = f.__doc__ wrap.__name__ = f.__name__ return wrap
[ "def", "_process_mass_form", "(", "f", ")", ":", "def", "wrap", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"Wrap\"", "if", "'massform'", "in", "request", ".", "POST", ":", "for", "key", "in", "request", ".", "POST", ":", ...
https://github.com/treeio/treeio/blob/bae3115f4015aad2cbc5ab45572232ceec990495/treeio/projects/views.py#L53-L85
yahoo/TensorFlowOnSpark
c2790b797b57acc540414c94909f4f6ec7e3895c
tensorflowonspark/pipeline.py
python
HasBatchSize.getBatchSize
(self)
return self.getOrDefault(self.batch_size)
[]
def getBatchSize(self): return self.getOrDefault(self.batch_size)
[ "def", "getBatchSize", "(", "self", ")", ":", "return", "self", ".", "getOrDefault", "(", "self", ".", "batch_size", ")" ]
https://github.com/yahoo/TensorFlowOnSpark/blob/c2790b797b57acc540414c94909f4f6ec7e3895c/tensorflowonspark/pipeline.py#L58-L59
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/xml/sax/saxutils.py
python
prepare_input_source
(source, base="")
return source
This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.
This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.
[ "This", "function", "takes", "an", "InputSource", "and", "an", "optional", "base", "URL", "and", "returns", "a", "fully", "resolved", "InputSource", "object", "ready", "for", "reading", "." ]
def prepare_input_source(source, base=""): """This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.""" if isinstance(source, os.PathLike): source = os.fspath(source) if isinstance(source, str): source = xmlreader.InputSource(source) elif hasattr(source, "read"): f = source source = xmlreader.InputSource() if isinstance(f.read(0), str): source.setCharacterStream(f) else: source.setByteStream(f) if hasattr(f, "name") and isinstance(f.name, str): source.setSystemId(f.name) if source.getCharacterStream() is None and source.getByteStream() is None: sysid = source.getSystemId() basehead = os.path.dirname(os.path.normpath(base)) sysidfilename = os.path.join(basehead, sysid) if os.path.isfile(sysidfilename): source.setSystemId(sysidfilename) f = open(sysidfilename, "rb") else: source.setSystemId(urllib.parse.urljoin(base, sysid)) f = urllib.request.urlopen(source.getSystemId()) source.setByteStream(f) return source
[ "def", "prepare_input_source", "(", "source", ",", "base", "=", "\"\"", ")", ":", "if", "isinstance", "(", "source", ",", "os", ".", "PathLike", ")", ":", "source", "=", "os", ".", "fspath", "(", "source", ")", "if", "isinstance", "(", "source", ",", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/xml/sax/saxutils.py#L338-L369
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/nltk/inference/discourse.py
python
DiscourseTester.retract_sentence
(self, sentence, verbose=True)
Remove a sentence from the current discourse. Updates ``self._input``, ``self._sentences`` and ``self._readings``. :param sentence: An input sentence :type sentence: str :param verbose: If ``True``, report on the updated list of sentences.
Remove a sentence from the current discourse.
[ "Remove", "a", "sentence", "from", "the", "current", "discourse", "." ]
def retract_sentence(self, sentence, verbose=True): """ Remove a sentence from the current discourse. Updates ``self._input``, ``self._sentences`` and ``self._readings``. :param sentence: An input sentence :type sentence: str :param verbose: If ``True``, report on the updated list of sentences. """ try: self._input.remove(sentence) except ValueError: print "Retraction failed. The sentence '%s' is not part of the current discourse:" % sentence self.sentences() return None self._sentences = dict([('s%s' % i, sent) for i, sent in enumerate(self._input)]) self.readings(verbose=False) if verbose: print "Current sentences are " self.sentences()
[ "def", "retract_sentence", "(", "self", ",", "sentence", ",", "verbose", "=", "True", ")", ":", "try", ":", "self", ".", "_input", ".", "remove", "(", "sentence", ")", "except", "ValueError", ":", "print", "\"Retraction failed. The sentence '%s' is not part of the...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/nltk/inference/discourse.py#L218-L237
aneisch/home-assistant-config
86e381fde9609cb8871c439c433c12989e4e225d
custom_components/hacs/repositories/theme.py
python
HacsThemeRepository.validate_repository
(self)
return self.validate.success
Validate.
Validate.
[ "Validate", "." ]
async def validate_repository(self): """Validate.""" # Run common validation steps. await self.common_validate() # Custom step 1: Validate content. compliant = False for treefile in self.treefiles: if treefile.startswith("themes/") and treefile.endswith(".yaml"): compliant = True break if not compliant: raise HacsException( f"Repository structure for {self.ref.replace('tags/','')} is not compliant" ) if self.data.content_in_root: self.content.path.remote = "" # Handle potential errors if self.validate.errors: for error in self.validate.errors: if not self.hacs.status.startup: self.logger.error("%s %s", self, error) return self.validate.success
[ "async", "def", "validate_repository", "(", "self", ")", ":", "# Run common validation steps.", "await", "self", ".", "common_validate", "(", ")", "# Custom step 1: Validate content.", "compliant", "=", "False", "for", "treefile", "in", "self", ".", "treefiles", ":", ...
https://github.com/aneisch/home-assistant-config/blob/86e381fde9609cb8871c439c433c12989e4e225d/custom_components/hacs/repositories/theme.py#L40-L64
tanghaibao/jcvi
5e720870c0928996f8b77a38208106ff0447ccb6
jcvi/apps/fetch.py
python
bisect
(args)
%prog bisect acc accession.fasta determine the version of the accession by querying entrez, based on a fasta file. This proceeds by a sequential search from xxxx.1 to the latest record.
%prog bisect acc accession.fasta
[ "%prog", "bisect", "acc", "accession", ".", "fasta" ]
def bisect(args): """ %prog bisect acc accession.fasta determine the version of the accession by querying entrez, based on a fasta file. This proceeds by a sequential search from xxxx.1 to the latest record. """ p = OptionParser(bisect.__doc__) p.set_email() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) acc, fastafile = args arec = get_first_rec(fastafile) valid = None for i in range(1, 100): term = "%s.%d" % (acc, i) try: query = list(batch_entrez([term], email=opts.email)) except AssertionError as e: logging.debug(f"no records found for {term}. terminating. {e}") return id, term, handle = query[0] brec = next(SeqIO.parse(handle, "fasta")) match = print_first_difference( arec, brec, ignore_case=True, ignore_N=True, rc=True ) if match: valid = term break if valid: printf() printf("[green]{} matches the sequence in `{}`".format(valid, fastafile))
[ "def", "bisect", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "bisect", ".", "__doc__", ")", "p", ".", "set_email", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ...
https://github.com/tanghaibao/jcvi/blob/5e720870c0928996f8b77a38208106ff0447ccb6/jcvi/apps/fetch.py#L481-L520
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/distutils/command/bdist_rpm.py
python
bdist_rpm._format_changelog
(self, changelog)
return new_changelog
Format the changelog correctly and convert it to a list of strings
Format the changelog correctly and convert it to a list of strings
[ "Format", "the", "changelog", "correctly", "and", "convert", "it", "to", "a", "list", "of", "strings" ]
def _format_changelog(self, changelog): """Format the changelog correctly and convert it to a list of strings """ if not changelog: return changelog new_changelog = [] for line in changelog.strip().split('\n'): line = line.strip() if line[0] == '*': new_changelog.extend(['', line]) elif line[0] == '-': new_changelog.append(line) else: new_changelog.append(' ' + line) # strip trailing newline inserted by first changelog entry if not new_changelog[0]: del new_changelog[0] return new_changelog
[ "def", "_format_changelog", "(", "self", ",", "changelog", ")", ":", "if", "not", "changelog", ":", "return", "changelog", "new_changelog", "=", "[", "]", "for", "line", "in", "changelog", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ":", "...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/distutils/command/bdist_rpm.py#L563-L582
dmlc/tensorboard
d36e8e921cdd5306c7e2535adbc0fe45be47ceed
python/tensorboard/event_file_writer.py
python
EventFileWriter.close
(self)
Flushes the event file to disk and close the file. Call this method when you do not need the summary writer anymore.
Flushes the event file to disk and close the file. Call this method when you do not need the summary writer anymore.
[ "Flushes", "the", "event", "file", "to", "disk", "and", "close", "the", "file", ".", "Call", "this", "method", "when", "you", "do", "not", "need", "the", "summary", "writer", "anymore", "." ]
def close(self): """Flushes the event file to disk and close the file. Call this method when you do not need the summary writer anymore. """ self.flush() self._ev_writer.close() self._closed = True
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "self", ".", "_ev_writer", ".", "close", "(", ")", "self", ".", "_closed", "=", "True" ]
https://github.com/dmlc/tensorboard/blob/d36e8e921cdd5306c7e2535adbc0fe45be47ceed/python/tensorboard/event_file_writer.py#L156-L162
joblib/joblib
7742f5882273889f7aaf1d483a8a1c72a97d57e3
joblib/_parallel_backends.py
python
ParallelBackendBase.terminate
(self)
Shutdown the workers and free the shared memory.
Shutdown the workers and free the shared memory.
[ "Shutdown", "the", "workers", "and", "free", "the", "shared", "memory", "." ]
def terminate(self): """Shutdown the workers and free the shared memory."""
[ "def", "terminate", "(", "self", ")", ":" ]
https://github.com/joblib/joblib/blob/7742f5882273889f7aaf1d483a8a1c72a97d57e3/joblib/_parallel_backends.py#L86-L87
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/qqbar.py
python
an_binop_expr
(a, b, op)
return ANBinaryExpr(a, b, op)
r""" Add, subtract, multiply or divide algebraic numbers represented as binary expressions. INPUT: - ``a``, ``b`` -- two elements - ``op`` -- an operator EXAMPLES:: sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3)) sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5)) sage: type(a._descr); type(b._descr) <class 'sage.rings.qqbar.ANBinaryExpr'> <class 'sage.rings.qqbar.ANBinaryExpr'> sage: from sage.rings.qqbar import an_binop_expr sage: x = an_binop_expr(a, b, operator.add); x <sage.rings.qqbar.ANBinaryExpr object at ...> sage: x.exactify() -6/7*a^7 + 2/7*a^6 + 71/7*a^5 - 26/7*a^4 - 125/7*a^3 + 72/7*a^2 + 43/7*a - 47/7 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in 3.12580...? sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3)) sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5)) sage: type(a._descr) <class 'sage.rings.qqbar.ANBinaryExpr'> sage: x = an_binop_expr(a, b, operator.mul); x <sage.rings.qqbar.ANBinaryExpr object at ...> sage: x.exactify() 2*a^7 - a^6 - 24*a^5 + 12*a^4 + 46*a^3 - 22*a^2 - 22*a + 9 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in 3.1258...?
r""" Add, subtract, multiply or divide algebraic numbers represented as binary expressions.
[ "r", "Add", "subtract", "multiply", "or", "divide", "algebraic", "numbers", "represented", "as", "binary", "expressions", "." ]
def an_binop_expr(a, b, op): r""" Add, subtract, multiply or divide algebraic numbers represented as binary expressions. INPUT: - ``a``, ``b`` -- two elements - ``op`` -- an operator EXAMPLES:: sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3)) sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5)) sage: type(a._descr); type(b._descr) <class 'sage.rings.qqbar.ANBinaryExpr'> <class 'sage.rings.qqbar.ANBinaryExpr'> sage: from sage.rings.qqbar import an_binop_expr sage: x = an_binop_expr(a, b, operator.add); x <sage.rings.qqbar.ANBinaryExpr object at ...> sage: x.exactify() -6/7*a^7 + 2/7*a^6 + 71/7*a^5 - 26/7*a^4 - 125/7*a^3 + 72/7*a^2 + 43/7*a - 47/7 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in 3.12580...? sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3)) sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5)) sage: type(a._descr) <class 'sage.rings.qqbar.ANBinaryExpr'> sage: x = an_binop_expr(a, b, operator.mul); x <sage.rings.qqbar.ANBinaryExpr object at ...> sage: x.exactify() 2*a^7 - a^6 - 24*a^5 + 12*a^4 + 46*a^3 - 22*a^2 - 22*a + 9 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in 3.1258...? """ return ANBinaryExpr(a, b, op)
[ "def", "an_binop_expr", "(", "a", ",", "b", ",", "op", ")", ":", "return", "ANBinaryExpr", "(", "a", ",", "b", ",", "op", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/qqbar.py#L8477-L8510
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/TrendMicroDeepSecurity/Integrations/TrendMicroDeepSecurity/TrendMicroDeepSecurity.py
python
Client.reset_computer_setting
(self, computer_id: int, setting_name: str, overrides: bool)
return self._http_request(method="DELETE", url_suffix=f"/computers/{computer_id}/settings/{setting_name}", params={"overrides": overrides})
Reset the setting of an existing computer inside Trend Micro. Args: computer_id (int): The computer id to obtain. setting_name (str): The name of the computer's setting. overrides (bool): Whether to get the overridden properties or not. Returns: Dict[str, Any]: The information about computer's setting.
Reset the setting of an existing computer inside Trend Micro.
[ "Reset", "the", "setting", "of", "an", "existing", "computer", "inside", "Trend", "Micro", "." ]
def reset_computer_setting(self, computer_id: int, setting_name: str, overrides: bool) -> Dict[str, Any]: """ Reset the setting of an existing computer inside Trend Micro. Args: computer_id (int): The computer id to obtain. setting_name (str): The name of the computer's setting. overrides (bool): Whether to get the overridden properties or not. Returns: Dict[str, Any]: The information about computer's setting. """ return self._http_request(method="DELETE", url_suffix=f"/computers/{computer_id}/settings/{setting_name}", params={"overrides": overrides})
[ "def", "reset_computer_setting", "(", "self", ",", "computer_id", ":", "int", ",", "setting_name", ":", "str", ",", "overrides", ":", "bool", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "self", ".", "_http_request", "(", "method", "=",...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/TrendMicroDeepSecurity/Integrations/TrendMicroDeepSecurity/TrendMicroDeepSecurity.py#L151-L164
abrignoni/iLEAPP
5376dc82b7fd0a27896088167b5b0b250a39a8be
scripts/ktx/ios_ktx2png.py
python
KTX_reader.get_uncompressed_texture_data
(self, f)
return b''
Just read the texture data which is lzfse compressed, uncompress and return it. Exceptions raised are ValueError or liblzfse.error
Just read the texture data which is lzfse compressed, uncompress and return it. Exceptions raised are ValueError or liblzfse.error
[ "Just", "read", "the", "texture", "data", "which", "is", "lzfse", "compressed", "uncompress", "and", "return", "it", ".", "Exceptions", "raised", "are", "ValueError", "or", "liblzfse", ".", "error" ]
def get_uncompressed_texture_data(self, f): '''Just read the texture data which is lzfse compressed, uncompress and return it. Exceptions raised are ValueError or liblzfse.error ''' if self.glInternalFormat == 0x93B0: if self.is_aapl_file: f.seek(self.aapl_data_pos) data = f.read(self.aapl_data_size) if self.aapl_is_compressed: decompressed = liblzfse.decompress(data) return decompressed else: return data else: f.seek(0x40) k_v_data = f.read(self.bytesOfKeyValueData) compressed = True if k_v_data.find(b'Compression_APPLE') >= 0 else False f.seek(0x40 + self.bytesOfKeyValueData) data = f.read() if compressed: if data[12:15] == b'bvx': decompressed = liblzfse.decompress(data[12:]) return decompressed else: raise ValueError('Unsupported compression, not lzfse!') else: return data[4:] # first 4 bytes is size (which is practically rest of file) else: raise ValueError('Unsupported Format') return b''
[ "def", "get_uncompressed_texture_data", "(", "self", ",", "f", ")", ":", "if", "self", ".", "glInternalFormat", "==", "0x93B0", ":", "if", "self", ".", "is_aapl_file", ":", "f", ".", "seek", "(", "self", ".", "aapl_data_pos", ")", "data", "=", "f", ".", ...
https://github.com/abrignoni/iLEAPP/blob/5376dc82b7fd0a27896088167b5b0b250a39a8be/scripts/ktx/ios_ktx2png.py#L150-L179
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py
python
Task.exc_clear
(self)
Clears any recorded exception. This also changes the "exception_raise" attribute to point to the appropriate do-nothing method.
Clears any recorded exception.
[ "Clears", "any", "recorded", "exception", "." ]
def exc_clear(self): """ Clears any recorded exception. This also changes the "exception_raise" attribute to point to the appropriate do-nothing method. """ self.exception = (None, None, None) self.exception_raise = self._no_exception_to_raise
[ "def", "exc_clear", "(", "self", ")", ":", "self", ".", "exception", "=", "(", "None", ",", "None", ",", "None", ")", "self", ".", "exception_raise", "=", "self", ".", "_no_exception_to_raise" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py#L504-L512
grow/grow
97fc21730b6a674d5d33948d94968e79447ce433
grow/translations/locales.py
python
Locales.to_message
(self)
return message
[]
def to_message(self): message = messages.LocalesMessage() message.groups = [] for group_name in self.list_groups(): group_message = messages.LocaleGroupMessage() group_message.group_name = group_name group_message.regions = self.get_regions(group_name) group_message.languages = self.get_languages(group_name) message.groups.append(group_message) return message
[ "def", "to_message", "(", "self", ")", ":", "message", "=", "messages", ".", "LocalesMessage", "(", ")", "message", ".", "groups", "=", "[", "]", "for", "group_name", "in", "self", ".", "list_groups", "(", ")", ":", "group_message", "=", "messages", ".",...
https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/translations/locales.py#L36-L45
viewfinderco/viewfinder
453845b5d64ab5b3b826c08b02546d1ca0a07c14
marketing/tornado/web.py
python
RequestHandler.set_header
(self, name, value)
Sets the given response header name and value. If a datetime is given, we automatically format it according to the HTTP specification. If the value is not a string, we convert it to a string. All header values are then encoded as UTF-8.
Sets the given response header name and value.
[ "Sets", "the", "given", "response", "header", "name", "and", "value", "." ]
def set_header(self, name, value): """Sets the given response header name and value. If a datetime is given, we automatically format it according to the HTTP specification. If the value is not a string, we convert it to a string. All header values are then encoded as UTF-8. """ self._headers[name] = self._convert_header_value(value)
[ "def", "set_header", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "_headers", "[", "name", "]", "=", "self", ".", "_convert_header_value", "(", "value", ")" ]
https://github.com/viewfinderco/viewfinder/blob/453845b5d64ab5b3b826c08b02546d1ca0a07c14/marketing/tornado/web.py#L290-L297
Autodesk/molecular-design-toolkit
5f45a47fea21d3603899a6366cb163024f0e2ec4
moldesign/utils/utils.py
python
if_not_none
(item, default)
Equivalent to `item if item is not None else default`
Equivalent to `item if item is not None else default`
[ "Equivalent", "to", "item", "if", "item", "is", "not", "None", "else", "default" ]
def if_not_none(item, default): """ Equivalent to `item if item is not None else default` """ if item is None: return default else: return item
[ "def", "if_not_none", "(", "item", ",", "default", ")", ":", "if", "item", "is", "None", ":", "return", "default", "else", ":", "return", "item" ]
https://github.com/Autodesk/molecular-design-toolkit/blob/5f45a47fea21d3603899a6366cb163024f0e2ec4/moldesign/utils/utils.py#L21-L26
vcheckzen/FODI
3bb23644938a33c3fdfb9611a622e35ed4ce6532
back-end-py/main/3rd/PIL/ImageFile.py
python
PyDecoder.setimage
(self, im, extents=None)
Called from ImageFile to set the core output image for the decoder :param im: A core image object :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle for this tile :returns: None
Called from ImageFile to set the core output image for the decoder
[ "Called", "from", "ImageFile", "to", "set", "the", "core", "output", "image", "for", "the", "decoder" ]
def setimage(self, im, extents=None): """ Called from ImageFile to set the core output image for the decoder :param im: A core image object :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle for this tile :returns: None """ # following c code self.im = im if extents: (x0, y0, x1, y1) = extents else: (x0, y0, x1, y1) = (0, 0, 0, 0) if x0 == 0 and x1 == 0: self.state.xsize, self.state.ysize = self.im.size else: self.state.xoff = x0 self.state.yoff = y0 self.state.xsize = x1 - x0 self.state.ysize = y1 - y0 if self.state.xsize <= 0 or self.state.ysize <= 0: raise ValueError("Size cannot be negative") if ( self.state.xsize + self.state.xoff > self.im.size[0] or self.state.ysize + self.state.yoff > self.im.size[1] ): raise ValueError("Tile cannot extend outside image")
[ "def", "setimage", "(", "self", ",", "im", ",", "extents", "=", "None", ")", ":", "# following c code", "self", ".", "im", "=", "im", "if", "extents", ":", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", "=", "extents", "else", ":", "(", "x0", ...
https://github.com/vcheckzen/FODI/blob/3bb23644938a33c3fdfb9611a622e35ed4ce6532/back-end-py/main/3rd/PIL/ImageFile.py#L629-L662
optuna/optuna
2c44c1a405ba059efd53f4b9c8e849d20fb95c0a
optuna/trial/_frozen.py
python
FrozenTrial.datetime_start
(self)
return self._datetime_start
[]
def datetime_start(self) -> Optional[datetime.datetime]: return self._datetime_start
[ "def", "datetime_start", "(", "self", ")", "->", "Optional", "[", "datetime", ".", "datetime", "]", ":", "return", "self", ".", "_datetime_start" ]
https://github.com/optuna/optuna/blob/2c44c1a405ba059efd53f4b9c8e849d20fb95c0a/optuna/trial/_frozen.py#L432-L434
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
ExampleBuilders/EdgeExampleBuilder.py
python
EdgeExampleBuilder.buildExamplesFromGraph
(self, sentenceGraph, outfile, goldGraph = None, structureAnalyzer=None)
return exampleIndex
Build examples for a single sentence. Returns a list of examples. See Core/ExampleUtils for example format.
Build examples for a single sentence. Returns a list of examples. See Core/ExampleUtils for example format.
[ "Build", "examples", "for", "a", "single", "sentence", ".", "Returns", "a", "list", "of", "examples", ".", "See", "Core", "/", "ExampleUtils", "for", "example", "format", "." ]
def buildExamplesFromGraph(self, sentenceGraph, outfile, goldGraph = None, structureAnalyzer=None): """ Build examples for a single sentence. Returns a list of examples. See Core/ExampleUtils for example format. """ #examples = [] exampleIndex = 0 # example directionality if self.styles["directed"] == None and self.styles["undirected"] == None: # determine directedness from corpus examplesAreDirected = structureAnalyzer.hasDirectedTargets() if structureAnalyzer != None else True elif self.styles["directed"]: assert self.styles["undirected"] in [None, False] examplesAreDirected = True elif self.styles["undirected"]: assert self.styles["directed"] in [None, False] examplesAreDirected = False if not self.styles["no_trigger_features"]: self.triggerFeatureBuilder.initSentence(sentenceGraph) if self.styles["evex"]: self.evexFeatureBuilder.initSentence(sentenceGraph) # if self.styles["sdb_merge"]: # self.determineNonOverlappingTypes(structureAnalyzer) # Filter entities, if needed sentenceGraph.mergeInteractionGraph(True) entities = sentenceGraph.mergedEntities entityToDuplicates = sentenceGraph.mergedEntityToDuplicates self.exampleStats.addValue("Duplicate entities skipped", len(sentenceGraph.entities) - len(entities)) # Connect to optional gold graph entityToGold = None if goldGraph != None: entityToGold = EvaluateInteractionXML.mapEntities(entities, goldGraph.entities) paths = None if not self.styles["no_path"]: undirected = sentenceGraph.dependencyGraph.toUndirected() paths = undirected if self.styles["filter_shortest_path"] != None: # For DDI use filter_shortest_path=conj_and paths.resetAnalyses() # just in case paths.FloydWarshall(self.filterEdge, {"edgeTypes":self.styles["filter_shortest_path"]}) # Generate examples based on interactions between entities or interactions between tokens if self.styles["token_nodes"]: loopRange = len(sentenceGraph.tokens) else: loopRange = len(entities) for i in range(loopRange-1): for j in range(i+1,loopRange): eI = None eJ = None if self.styles["token_nodes"]: tI = sentenceGraph.tokens[i] tJ = sentenceGraph.tokens[j] else: eI = entities[i] eJ = entities[j] tI = sentenceGraph.entityHeadTokenByEntity[eI] tJ = sentenceGraph.entityHeadTokenByEntity[eJ] if eI.get("type") == "neg" or eJ.get("type") == "neg": continue if self.styles["skip_extra_triggers"]: if eI.get("source") != None or eJ.get("source") != None: continue # only consider paths between entities (NOTE! entities, not only named entities) if self.styles["headsOnly"]: if (len(sentenceGraph.tokenIsEntityHead[tI]) == 0) or (len(sentenceGraph.tokenIsEntityHead[tJ]) == 0): continue examples = self.buildExamplesForPair(tI, tJ, paths, sentenceGraph, goldGraph, entityToGold, eI, eJ, structureAnalyzer, examplesAreDirected) for categoryName, features, extra in examples: # make example if self.styles["binary"]: if categoryName != "neg": category = 1 else: category = -1 extra["categoryName"] = "i" else: category = self.classSet.getId(categoryName) example = [sentenceGraph.getSentenceId()+".x"+str(exampleIndex), category, features, extra] ExampleUtils.appendExamples([example], outfile) exampleIndex += 1 return exampleIndex
[ "def", "buildExamplesFromGraph", "(", "self", ",", "sentenceGraph", ",", "outfile", ",", "goldGraph", "=", "None", ",", "structureAnalyzer", "=", "None", ")", ":", "#examples = []", "exampleIndex", "=", "0", "# example directionality", "if", "self", ".", "styles",...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/ExampleBuilders/EdgeExampleBuilder.py#L276-L361
MozillaSecurity/dharma
6b1e5119646064a80122ca18944a98238d5eadb1
dharma/core/websocket.py
python
BaseWebSocketHandler.should_close
(self)
return False
When this returns true, the message loop will exit.
When this returns true, the message loop will exit.
[ "When", "this", "returns", "true", "the", "message", "loop", "will", "exit", "." ]
def should_close(self): """When this returns true, the message loop will exit.""" return False
[ "def", "should_close", "(", "self", ")", ":", "return", "False" ]
https://github.com/MozillaSecurity/dharma/blob/6b1e5119646064a80122ca18944a98238d5eadb1/dharma/core/websocket.py#L135-L137
akanazawa/human_dynamics
0887f37464c9a079ad7d69c8358cecd0f43c4f2a
src/ops.py
python
call_hmr_ief
(phi, omega_start, scope, num_output=85, num_stage=3, is_training=True, predict_delta_keys=(), use_delta_from_pred=False, use_optcam=False)
return theta_here, deltas_predictions
Wrapper for doing HMR-style IEF. If predict_delta, then also makes num_delta_t predictions forward and backward in time, with each step of delta_t. Args: phi (Bx2048): Image features. omega_start (Bx85): Starting Omega as input to first IEF. scope (str): Name of scope for reuse. num_output (int): Size of output. num_stage (int): Number of iterations for IEF. is_training (bool): If False, don't apply dropout. predict_delta_keys (iterable): List of keys for delta_t. use_delta_from_pred (bool): If True, initializes delta prediction from current frame prediction. use_optcam (bool): If True, only outputs 82 and uses [1, 0, 0] as cam. Returns: Final theta (Bx{num_output}) Deltas predictions (List of outputs)
Wrapper for doing HMR-style IEF.
[ "Wrapper", "for", "doing", "HMR", "-", "style", "IEF", "." ]
def call_hmr_ief(phi, omega_start, scope, num_output=85, num_stage=3, is_training=True, predict_delta_keys=(), use_delta_from_pred=False, use_optcam=False): """ Wrapper for doing HMR-style IEF. If predict_delta, then also makes num_delta_t predictions forward and backward in time, with each step of delta_t. Args: phi (Bx2048): Image features. omega_start (Bx85): Starting Omega as input to first IEF. scope (str): Name of scope for reuse. num_output (int): Size of output. num_stage (int): Number of iterations for IEF. is_training (bool): If False, don't apply dropout. predict_delta_keys (iterable): List of keys for delta_t. use_delta_from_pred (bool): If True, initializes delta prediction from current frame prediction. use_optcam (bool): If True, only outputs 82 and uses [1, 0, 0] as cam. Returns: Final theta (Bx{num_output}) Deltas predictions (List of outputs) """ theta_here = hmr_ief( phi=phi, omega_start=omega_start, scope=scope, num_output=num_output, num_stage=num_stage, is_training=is_training, ) # Delta only needs to do cam/pose, no shape! if use_optcam: num_output_delta = 72 else: num_output_delta = 3 + 72 deltas_predictions = {} for delta_t in predict_delta_keys: if delta_t == 0: # This should just be the normal IEF. continue elif delta_t > 0: scope_delta = scope + '_future{}'.format(delta_t) elif delta_t < 0: scope_delta = scope + '_past{}'.format(abs(delta_t)) omega_start_delta = theta_here if use_delta_from_pred else omega_start # append this later. beta = omega_start_delta[:, -10:] if use_optcam: # trim the first 3D camera + last shpae # DEBUG! # just pose = 3:3+72 omega_start_delta = omega_start_delta[:, 3:3 + num_output_delta] else: # Uncomment this to be backwards compatible # Drop the shape. # just cam + pose = 3:3+72 omega_start_delta = omega_start_delta[:, :num_output_delta] delta_pred = hmr_ief( phi=phi, omega_start=omega_start_delta, scope=scope_delta, num_output=num_output_delta, num_stage=num_stage, is_training=is_training ) if use_optcam: # Add camera + shape scale = tf.ones([delta_pred.shape[0], 1]) trans = tf.zeros([delta_pred.shape[0], 2]) delta_pred = tf.concat([scale, trans, delta_pred, beta], 1) else: delta_pred = tf.concat([delta_pred[:, :75], beta], 1) deltas_predictions[delta_t] = delta_pred return theta_here, deltas_predictions
[ "def", "call_hmr_ief", "(", "phi", ",", "omega_start", ",", "scope", ",", "num_output", "=", "85", ",", "num_stage", "=", "3", ",", "is_training", "=", "True", ",", "predict_delta_keys", "=", "(", ")", ",", "use_delta_from_pred", "=", "False", ",", "use_op...
https://github.com/akanazawa/human_dynamics/blob/0887f37464c9a079ad7d69c8358cecd0f43c4f2a/src/ops.py#L184-L267
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/transforms/radius_graph.py
python
RadiusGraph.__repr__
(self)
return f'{self.__class__.__name__}(r={self.r})'
[]
def __repr__(self) -> str: return f'{self.__class__.__name__}(r={self.r})'
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "f'{self.__class__.__name__}(r={self.r})'" ]
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/transforms/radius_graph.py#L35-L36
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/tuya/scene.py
python
TuyaSceneEntity.name
(self)
return self.scene.name
Return Tuya scene name.
Return Tuya scene name.
[ "Return", "Tuya", "scene", "name", "." ]
def name(self) -> str | None: """Return Tuya scene name.""" return self.scene.name
[ "def", "name", "(", "self", ")", "->", "str", "|", "None", ":", "return", "self", ".", "scene", ".", "name" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/tuya/scene.py#L42-L44
Calysto/calysto_scheme
15bf81987870bcae1264e5a0a06feb9a8ee12b8b
calysto_scheme/scheme.py
python
aparse_sexps
()
[]
def aparse_sexps(): if (False if ((token_type_q(first(tokens_reg), symbol_end_marker)) is False) else True): GLOBALS['value2_reg'] = fail_reg GLOBALS['value1_reg'] = symbol_emptylist GLOBALS['pc'] = apply_cont2 else: GLOBALS['k_reg'] = make_cont4(b_cont4_9_d, senv_reg, src_reg, handler_reg, k_reg) GLOBALS['pc'] = read_sexp
[ "def", "aparse_sexps", "(", ")", ":", "if", "(", "False", "if", "(", "(", "token_type_q", "(", "first", "(", "tokens_reg", ")", ",", "symbol_end_marker", ")", ")", "is", "False", ")", "else", "True", ")", ":", "GLOBALS", "[", "'value2_reg'", "]", "=", ...
https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L7125-L7132
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/audio/spoken_digit/spoken_digit.py
python
SpokenDigit._split_generators
(self, dl_manager)
return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={"path": path}) ]
Returns Split Generators.
Returns Split Generators.
[ "Returns", "Split", "Generators", "." ]
def _split_generators(self, dl_manager): """Returns Split Generators.""" dl_path = dl_manager.download_and_extract(_DOWNLOAD_URL) extracted_dir_path = os.path.join(dl_path, "free-spoken-digit-dataset-1.0.9") path = os.path.join(extracted_dir_path, "recordings") # There is no predefined train/val/test split for this dataset. return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={"path": path}) ]
[ "def", "_split_generators", "(", "self", ",", "dl_manager", ")", ":", "dl_path", "=", "dl_manager", ".", "download_and_extract", "(", "_DOWNLOAD_URL", ")", "extracted_dir_path", "=", "os", ".", "path", ".", "join", "(", "dl_path", ",", "\"free-spoken-digit-dataset...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/audio/spoken_digit/spoken_digit.py#L67-L77
pyppeteer/pyppeteer
d55b6f46a0d1315ca176a74a1d358bbbbec7e825
pyppeteer/page.py
python
Page.title
(self)
return await frame.title()
Get page's title.
Get page's title.
[ "Get", "page", "s", "title", "." ]
async def title(self) -> str: """Get page's title.""" frame = self.mainFrame if not frame: raise PageError('no main frame.') return await frame.title()
[ "async", "def", "title", "(", "self", ")", "->", "str", ":", "frame", "=", "self", ".", "mainFrame", "if", "not", "frame", ":", "raise", "PageError", "(", "'no main frame.'", ")", "return", "await", "frame", ".", "title", "(", ")" ]
https://github.com/pyppeteer/pyppeteer/blob/d55b6f46a0d1315ca176a74a1d358bbbbec7e825/pyppeteer/page.py#L1403-L1408
FutunnOpen/py-futu-api
b8f9fb1f26f35f99630ca47863f5595b6e635533
futu/common/sys_config.py
python
SysConfig.get_init_rsa_obj
(cls)
return SysConfig.RSA_OBJ
:return: str , private key for init connect protocol
:return: str , private key for init connect protocol
[ ":", "return", ":", "str", "private", "key", "for", "init", "connect", "protocol" ]
def get_init_rsa_obj(cls): """ :return: str , private key for init connect protocol """ if not SysConfig.RSA_OBJ: SysConfig._read_rsa_keys() return SysConfig.RSA_OBJ
[ "def", "get_init_rsa_obj", "(", "cls", ")", ":", "if", "not", "SysConfig", ".", "RSA_OBJ", ":", "SysConfig", ".", "_read_rsa_keys", "(", ")", "return", "SysConfig", ".", "RSA_OBJ" ]
https://github.com/FutunnOpen/py-futu-api/blob/b8f9fb1f26f35f99630ca47863f5595b6e635533/futu/common/sys_config.py#L141-L149
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/werkzeug/serving.py
python
WSGIRequestHandler.connection_dropped
(self, error, environ=None)
Called if the connection was closed by the client. By default nothing happens.
Called if the connection was closed by the client. By default nothing happens.
[ "Called", "if", "the", "connection", "was", "closed", "by", "the", "client", ".", "By", "default", "nothing", "happens", "." ]
def connection_dropped(self, error, environ=None): """Called if the connection was closed by the client. By default nothing happens. """
[ "def", "connection_dropped", "(", "self", ",", "error", ",", "environ", "=", "None", ")", ":" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/werkzeug/serving.py#L256-L259
xiaoxu193/PyTeaser
b8792b1efe1a8642d24db84816e5281253ab2a92
goose/text.py
python
encodeValue
(value)
return value
[]
def encodeValue(value): string_org = value try: value = smart_unicode(value) except (UnicodeEncodeError, DjangoUnicodeDecodeError): value = smart_str(value) except: value = string_org return value
[ "def", "encodeValue", "(", "value", ")", ":", "string_org", "=", "value", "try", ":", "value", "=", "smart_unicode", "(", "value", ")", "except", "(", "UnicodeEncodeError", ",", "DjangoUnicodeDecodeError", ")", ":", "value", "=", "smart_str", "(", "value", "...
https://github.com/xiaoxu193/PyTeaser/blob/b8792b1efe1a8642d24db84816e5281253ab2a92/goose/text.py#L44-L52
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
cherrypy/wsgiserver/ssl_pyopenssl.py
python
pyOpenSSLAdapter.get_context
(self)
return c
Return an SSL.Context from self attributes.
Return an SSL.Context from self attributes.
[ "Return", "an", "SSL", ".", "Context", "from", "self", "attributes", "." ]
def get_context(self): """Return an SSL.Context from self attributes.""" # See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473 c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_chain) c.use_certificate_file(self.certificate) return c
[ "def", "get_context", "(", "self", ")", ":", "# See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473", "c", "=", "SSL", ".", "Context", "(", "SSL", ".", "SSLv23_METHOD", ")", "c", ".", "use_privatekey_file", "(", "self", ".", "private_key", ")", "if", ...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/cherrypy/wsgiserver/ssl_pyopenssl.py#L193-L201
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/email/header.py
python
Header.__unicode__
(self)
return UEMPTYSTRING.join(uchunks)
Helper for the built-in unicode function.
Helper for the built-in unicode function.
[ "Helper", "for", "the", "built", "-", "in", "unicode", "function", "." ]
def __unicode__(self): """Helper for the built-in unicode function.""" uchunks = [] lastcs = None for s, charset in self._chunks: # We must preserve spaces between encoded and non-encoded word # boundaries, which means for us we need to add a space when we go # from a charset to None/us-ascii, or from None/us-ascii to a # charset. Only do this for the second and subsequent chunks. nextcs = charset if uchunks: if lastcs not in (None, 'us-ascii'): if nextcs in (None, 'us-ascii'): uchunks.append(USPACE) nextcs = None elif nextcs not in (None, 'us-ascii'): uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks)
[ "def", "__unicode__", "(", "self", ")", ":", "uchunks", "=", "[", "]", "lastcs", "=", "None", "for", "s", ",", "charset", "in", "self", ".", "_chunks", ":", "# We must preserve spaces between encoded and non-encoded word", "# boundaries, which means for us we need to ad...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/email/header.py#L202-L221
spro/pytorch-seq2seq-intent-parsing
a6b89459ce83438d1105db123dfdded105d68797
data.py
python
GloVeLang.__str__
(self)
return "%s(size = %d)" % (self.__class__.__name__, self.size)
[]
def __str__(self): return "%s(size = %d)" % (self.__class__.__name__, self.size)
[ "def", "__str__", "(", "self", ")", ":", "return", "\"%s(size = %d)\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "size", ")" ]
https://github.com/spro/pytorch-seq2seq-intent-parsing/blob/a6b89459ce83438d1105db123dfdded105d68797/data.py#L247-L248
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/tasmota/light.py
python
TasmotaLight.state_updated
(self, state: bool, **kwargs: Any)
Handle state updates.
Handle state updates.
[ "Handle", "state", "updates", "." ]
def state_updated(self, state: bool, **kwargs: Any) -> None: """Handle state updates.""" self._on_off_state = state if attributes := kwargs.get("attributes"): if "brightness" in attributes: brightness = float(attributes["brightness"]) percent_bright = brightness / TASMOTA_BRIGHTNESS_MAX self._brightness = round(percent_bright * 255) if "color_hs" in attributes: self._hs = attributes["color_hs"] if "color_temp" in attributes: self._color_temp = attributes["color_temp"] if "effect" in attributes: self._effect = attributes["effect"] if "white_value" in attributes: white_value = float(attributes["white_value"]) percent_white = white_value / TASMOTA_BRIGHTNESS_MAX self._white_value = round(percent_white * 255) if self._tasmota_entity.light_type == LIGHT_TYPE_RGBW: # Tasmota does not support RGBW mode, set mode to white or hs if self._white_value == 0: self._color_mode = COLOR_MODE_HS else: self._color_mode = COLOR_MODE_WHITE elif self._tasmota_entity.light_type == LIGHT_TYPE_RGBCW: # Tasmota does not support RGBWW mode, set mode to ct or hs if self._white_value == 0: self._color_mode = COLOR_MODE_HS else: self._color_mode = COLOR_MODE_COLOR_TEMP self.async_write_ha_state()
[ "def", "state_updated", "(", "self", ",", "state", ":", "bool", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "_on_off_state", "=", "state", "if", "attributes", ":=", "kwargs", ".", "get", "(", "\"attributes\"", ")", ":", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/tasmota/light.py#L162-L193
abhi2610/ohem
1f07dd09b50c8c21716ae36aede92125fe437579
lib/transform/torch_image_transform_layer.py
python
TorchImageTransformLayer.reshape
(self, bottom, top)
Reshaping happens during the call to forward.
Reshaping happens during the call to forward.
[ "Reshaping", "happens", "during", "the", "call", "to", "forward", "." ]
def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass
[ "def", "reshape", "(", "self", ",", "bottom", ",", "top", ")", ":", "pass" ]
https://github.com/abhi2610/ohem/blob/1f07dd09b50c8c21716ae36aede92125fe437579/lib/transform/torch_image_transform_layer.py#L62-L64
alanhamlett/pip-update-requirements
ce875601ef278c8ce00ad586434a978731525561
pur/packages/pip/_vendor/pyparsing.py
python
matchOnlyAtCol
(n)
return verifyCol
Helper method for defining parse actions that require matching at a specific column in the input text.
Helper method for defining parse actions that require matching at a specific column in the input text.
[ "Helper", "method", "for", "defining", "parse", "actions", "that", "require", "matching", "at", "a", "specific", "column", "in", "the", "input", "text", "." ]
def matchOnlyAtCol(n): """Helper method for defining parse actions that require matching at a specific column in the input text. """ def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol
[ "def", "matchOnlyAtCol", "(", "n", ")", ":", "def", "verifyCol", "(", "strg", ",", "locn", ",", "toks", ")", ":", "if", "col", "(", "locn", ",", "strg", ")", "!=", "n", ":", "raise", "ParseException", "(", "strg", ",", "locn", ",", "\"matched token n...
https://github.com/alanhamlett/pip-update-requirements/blob/ce875601ef278c8ce00ad586434a978731525561/pur/packages/pip/_vendor/pyparsing.py#L5269-L5276
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/regions.py
python
endpoint_for
(service, region=None, endpoint=None, service_endpoint_template=None, endpoint_service_name=None)
return _endpoint_for(service, region, service_endpoint_template, endpoint_service_name)
Returns the base URl for a service, either in the given region or at the specified endpoint. If endpoint and region are provided, endpoint is used. If the region information is not available in the existing maps, following sources are checked in order: 1. Regions Configuration File at ~/.oci/regions-config.json 2. Region Metadata Environment variable 3. Instance Metadata Service Lookup from Instance Metadata Service is disabled by default. To enable, call enable_instance_metadata_service() The region metadata schema is: { "realmKey" : string, "realmDomainComponent" : string, "regionKey" : string, "regionIdentifier" : string } For example, for the Sydney OC1 region, the schema would be filled out as follows: { "realmKey" : "OC1", "realmDomainComponent" : "oraclecloud.com", "regionKey" : "SYD", "regionIdentifier" : "ap-sydney-1" } If the region still cannot be resolved, we fall back to OC1 realm
Returns the base URl for a service, either in the given region or at the specified endpoint.
[ "Returns", "the", "base", "URl", "for", "a", "service", "either", "in", "the", "given", "region", "or", "at", "the", "specified", "endpoint", "." ]
def endpoint_for(service, region=None, endpoint=None, service_endpoint_template=None, endpoint_service_name=None): """Returns the base URl for a service, either in the given region or at the specified endpoint. If endpoint and region are provided, endpoint is used. If the region information is not available in the existing maps, following sources are checked in order: 1. Regions Configuration File at ~/.oci/regions-config.json 2. Region Metadata Environment variable 3. Instance Metadata Service Lookup from Instance Metadata Service is disabled by default. To enable, call enable_instance_metadata_service() The region metadata schema is: { "realmKey" : string, "realmDomainComponent" : string, "regionKey" : string, "regionIdentifier" : string } For example, for the Sydney OC1 region, the schema would be filled out as follows: { "realmKey" : "OC1", "realmDomainComponent" : "oraclecloud.com", "regionKey" : "SYD", "regionIdentifier" : "ap-sydney-1" } If the region still cannot be resolved, we fall back to OC1 realm """ if not (endpoint or region): raise ValueError("Must supply either a region or an endpoint.") if endpoint: # endpoint takes priority return _format_endpoint(service, endpoint, service_endpoint_template, endpoint_service_name) region = region.lower() # If unable to find region information from existing maps, check the other sources and add if not (region in REGIONS or region in REGIONS_SHORT_NAMES): _check_and_add_region_metadata(region) return _endpoint_for(service, region, service_endpoint_template, endpoint_service_name)
[ "def", "endpoint_for", "(", "service", ",", "region", "=", "None", ",", "endpoint", "=", "None", ",", "service_endpoint_template", "=", "None", ",", "endpoint_service_name", "=", "None", ")", ":", "if", "not", "(", "endpoint", "or", "region", ")", ":", "ra...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/regions.py#L120-L161
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tiw/v20190919/models.py
python
DescribeOnlineRecordResponse.__init__
(self)
r""" :param FinishReason: 录制结束原因, - AUTO: 房间内长时间没有音视频上行及白板操作导致自动停止录制 - USER_CALL: 主动调用了停止录制接口 - EXCEPTION: 录制异常结束 - FORCE_STOP: 强制停止录制,一般是因为暂停超过90分钟或者录制总时长超过24小时。 :type FinishReason: str :param TaskId: 需要查询结果的录制任务Id :type TaskId: str :param Status: 录制任务状态 - PREPARED: 表示录制正在准备中(进房/启动录制服务等操作) - RECORDING: 表示录制已开始 - PAUSED: 表示录制已暂停 - STOPPED: 表示录制已停止,正在处理并上传视频 - FINISHED: 表示视频处理并上传完成,成功生成录制结果 :type Status: str :param RoomId: 房间号 :type RoomId: int :param GroupId: 白板的群组 Id :type GroupId: str :param RecordUserId: 录制用户Id :type RecordUserId: str :param RecordStartTime: 实际开始录制时间,Unix 时间戳,单位秒 :type RecordStartTime: int :param RecordStopTime: 实际停止录制时间,Unix 时间戳,单位秒 :type RecordStopTime: int :param TotalTime: 回放视频总时长(单位:毫秒) :type TotalTime: int :param ExceptionCnt: 录制过程中出现异常的次数 :type ExceptionCnt: int :param OmittedDurations: 拼接视频中被忽略的时间段,只有开启视频拼接功能的时候,这个参数才是有效的 :type OmittedDurations: list of OmittedDuration :param VideoInfos: 录制视频列表 :type VideoInfos: list of VideoInfo :param ReplayUrl: 回放URL,需配合信令播放器使用。此字段仅适用于`视频生成模式` 注意:此字段可能返回 null,表示取不到有效值。 :type ReplayUrl: str :param Interrupts: 视频流在录制过程中断流次数 注意:此字段可能返回 null,表示取不到有效值。 :type Interrupts: list of Interrupt :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param FinishReason: 录制结束原因, - AUTO: 房间内长时间没有音视频上行及白板操作导致自动停止录制 - USER_CALL: 主动调用了停止录制接口 - EXCEPTION: 录制异常结束 - FORCE_STOP: 强制停止录制,一般是因为暂停超过90分钟或者录制总时长超过24小时。 :type FinishReason: str :param TaskId: 需要查询结果的录制任务Id :type TaskId: str :param Status: 录制任务状态 - PREPARED: 表示录制正在准备中(进房/启动录制服务等操作) - RECORDING: 表示录制已开始 - PAUSED: 表示录制已暂停 - STOPPED: 表示录制已停止,正在处理并上传视频 - FINISHED: 表示视频处理并上传完成,成功生成录制结果 :type Status: str :param RoomId: 房间号 :type RoomId: int :param GroupId: 白板的群组 Id :type GroupId: str :param RecordUserId: 录制用户Id :type RecordUserId: str :param RecordStartTime: 实际开始录制时间,Unix 时间戳,单位秒 :type RecordStartTime: int :param RecordStopTime: 实际停止录制时间,Unix 时间戳,单位秒 :type RecordStopTime: int :param TotalTime: 回放视频总时长(单位:毫秒) :type TotalTime: int :param ExceptionCnt: 录制过程中出现异常的次数 :type ExceptionCnt: int :param OmittedDurations: 拼接视频中被忽略的时间段,只有开启视频拼接功能的时候,这个参数才是有效的 :type OmittedDurations: list of OmittedDuration :param VideoInfos: 录制视频列表 :type VideoInfos: list of VideoInfo :param ReplayUrl: 回放URL,需配合信令播放器使用。此字段仅适用于`视频生成模式` 注意:此字段可能返回 null,表示取不到有效值。 :type ReplayUrl: str :param Interrupts: 视频流在录制过程中断流次数 注意:此字段可能返回 null,表示取不到有效值。 :type Interrupts: list of Interrupt :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "FinishReason", ":", "录制结束原因,", "-", "AUTO", ":", "房间内长时间没有音视频上行及白板操作导致自动停止录制", "-", "USER_CALL", ":", "主动调用了停止录制接口", "-", "EXCEPTION", ":", "录制异常结束", "-", "FORCE_STOP", ":", "强制停止录制,一般是因为暂停超过90分钟或者录制总时长超过24小时。", ":", "type", "FinishReason", ":", ...
def __init__(self): r""" :param FinishReason: 录制结束原因, - AUTO: 房间内长时间没有音视频上行及白板操作导致自动停止录制 - USER_CALL: 主动调用了停止录制接口 - EXCEPTION: 录制异常结束 - FORCE_STOP: 强制停止录制,一般是因为暂停超过90分钟或者录制总时长超过24小时。 :type FinishReason: str :param TaskId: 需要查询结果的录制任务Id :type TaskId: str :param Status: 录制任务状态 - PREPARED: 表示录制正在准备中(进房/启动录制服务等操作) - RECORDING: 表示录制已开始 - PAUSED: 表示录制已暂停 - STOPPED: 表示录制已停止,正在处理并上传视频 - FINISHED: 表示视频处理并上传完成,成功生成录制结果 :type Status: str :param RoomId: 房间号 :type RoomId: int :param GroupId: 白板的群组 Id :type GroupId: str :param RecordUserId: 录制用户Id :type RecordUserId: str :param RecordStartTime: 实际开始录制时间,Unix 时间戳,单位秒 :type RecordStartTime: int :param RecordStopTime: 实际停止录制时间,Unix 时间戳,单位秒 :type RecordStopTime: int :param TotalTime: 回放视频总时长(单位:毫秒) :type TotalTime: int :param ExceptionCnt: 录制过程中出现异常的次数 :type ExceptionCnt: int :param OmittedDurations: 拼接视频中被忽略的时间段,只有开启视频拼接功能的时候,这个参数才是有效的 :type OmittedDurations: list of OmittedDuration :param VideoInfos: 录制视频列表 :type VideoInfos: list of VideoInfo :param ReplayUrl: 回放URL,需配合信令播放器使用。此字段仅适用于`视频生成模式` 注意:此字段可能返回 null,表示取不到有效值。 :type ReplayUrl: str :param Interrupts: 视频流在录制过程中断流次数 注意:此字段可能返回 null,表示取不到有效值。 :type Interrupts: list of Interrupt :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.FinishReason = None self.TaskId = None self.Status = None self.RoomId = None self.GroupId = None self.RecordUserId = None self.RecordStartTime = None self.RecordStopTime = None self.TotalTime = None self.ExceptionCnt = None self.OmittedDurations = None self.VideoInfos = None self.ReplayUrl = None self.Interrupts = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "FinishReason", "=", "None", "self", ".", "TaskId", "=", "None", "self", ".", "Status", "=", "None", "self", ".", "RoomId", "=", "None", "self", ".", "GroupId", "=", "None", "self", ".", "RecordU...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tiw/v20190919/models.py#L449-L507
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/ui/gui/entries.py
python
RememberingWindow.quit
(self, widget, event)
return False
Windows quit, saves the position and size. :param widget: who sent the signal. :param event: the event that happened
Windows quit, saves the position and size.
[ "Windows", "quit", "saves", "the", "position", "and", "size", "." ]
def quit(self, widget, event): """Windows quit, saves the position and size. :param widget: who sent the signal. :param event: the event that happened """ if self.onDestroy is not None: if not self.onDestroy(): return True try: self.winconfig[self.id_size] = self.get_size() self.winconfig[self.id_position] = self.get_position() except ValueError: # https://github.com/andresriancho/w3af/issues/8890 pass return False
[ "def", "quit", "(", "self", ",", "widget", ",", "event", ")", ":", "if", "self", ".", "onDestroy", "is", "not", "None", ":", "if", "not", "self", ".", "onDestroy", "(", ")", ":", "return", "True", "try", ":", "self", ".", "winconfig", "[", "self", ...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/ui/gui/entries.py#L690-L707
GoogleCloudPlatform/gsutil
5be882803e76608e2fd29cf8c504ccd1fe0a7746
gslib/sig_handling.py
python
InitializeSignalHandling
()
Initializes global signal handling. Sets up global signal handler for each signal we handle.
Initializes global signal handling.
[ "Initializes", "global", "signal", "handling", "." ]
def InitializeSignalHandling(): """Initializes global signal handling. Sets up global signal handler for each signal we handle. """ for signal_num in GetCaughtSignals(): _non_final_signal_handlers[signal_num] = [] # Make main signal handler catch the signal. signal.signal(signal_num, _SignalHandler)
[ "def", "InitializeSignalHandling", "(", ")", ":", "for", "signal_num", "in", "GetCaughtSignals", "(", ")", ":", "_non_final_signal_handlers", "[", "signal_num", "]", "=", "[", "]", "# Make main signal handler catch the signal.", "signal", ".", "signal", "(", "signal_n...
https://github.com/GoogleCloudPlatform/gsutil/blob/5be882803e76608e2fd29cf8c504ccd1fe0a7746/gslib/sig_handling.py#L95-L103
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Slack/Integrations/SlackV3/SlackV3.py
python
send_slack_request_sync
(client: slack_sdk.WebClient, method: str, http_verb: str = 'POST', file_: str = '', body: dict = None)
return response
Sends a request to slack API while handling rate limit errors. Args: client: The slack client. method: The method to use. http_verb: The HTTP method to use. file_: A file path to send. body: The request body. Returns: The slack API response.
Sends a request to slack API while handling rate limit errors.
[ "Sends", "a", "request", "to", "slack", "API", "while", "handling", "rate", "limit", "errors", "." ]
def send_slack_request_sync(client: slack_sdk.WebClient, method: str, http_verb: str = 'POST', file_: str = '', body: dict = None) -> SlackResponse: """ Sends a request to slack API while handling rate limit errors. Args: client: The slack client. method: The method to use. http_verb: The HTTP method to use. file_: A file path to send. body: The request body. Returns: The slack API response. """ if body is None: body = {} set_name_and_icon(body, method) total_try_time = 0 while True: try: demisto.debug(f'Sending slack {method} (sync). Body is: {str(body)}') if http_verb == 'POST': if file_: response = client.api_call(method, files={"file": file_}, data=body) else: response = client.api_call(method, json=body) else: response = client.api_call(method, http_verb='GET', params=body) except SlackApiError as api_error: demisto.debug(f'Got rate limit error (sync). Body is: {str(body)}\n{api_error}') response = api_error.response headers = response.headers # type: ignore if 'Retry-After' in headers: retry_after = int(headers['Retry-After']) total_try_time += retry_after if total_try_time < MAX_LIMIT_TIME: time.sleep(retry_after) continue raise break return response
[ "def", "send_slack_request_sync", "(", "client", ":", "slack_sdk", ".", "WebClient", ",", "method", ":", "str", ",", "http_verb", ":", "str", "=", "'POST'", ",", "file_", ":", "str", "=", "''", ",", "body", ":", "dict", "=", "None", ")", "->", "SlackRe...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Slack/Integrations/SlackV3/SlackV3.py#L241-L284
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/providers/bitbucket_repository_provider.py
python
BitBucketRepositoryProvider.get_renamed_packages
(self)
return {}
For API-compatibility with RepositoryProvider
For API-compatibility with RepositoryProvider
[ "For", "API", "-", "compatibility", "with", "RepositoryProvider" ]
def get_renamed_packages(self): """For API-compatibility with RepositoryProvider""" return {}
[ "def", "get_renamed_packages", "(", "self", ")", ":", "return", "{", "}" ]
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/providers/bitbucket_repository_provider.py#L182-L185
nosmokingbandit/watcher
dadacd21a5790ee609058a98a17fcc8954d24439
lib/infi/pkg_resources/__init__.py
python
ResourceManager.extraction_error
(self)
Give an error message for problems extracting file(s)
Give an error message for problems extracting file(s)
[ "Give", "an", "error", "message", "for", "problems", "extracting", "file", "(", "s", ")" ]
def extraction_error(self): """Give an error message for problems extracting file(s)""" old_exc = sys.exc_info()[1] cache_path = self.extraction_path or get_default_cache() tmpl = textwrap.dedent(""" Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: {old_exc} The Python egg cache directory is currently set to: {cache_path} Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. """).lstrip() err = ExtractionError(tmpl.format(**locals())) err.manager = self err.cache_path = cache_path err.original_error = old_exc raise err
[ "def", "extraction_error", "(", "self", ")", ":", "old_exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "cache_path", "=", "self", ".", "extraction_path", "or", "get_default_cache", "(", ")", "tmpl", "=", "textwrap", ".", "dedent", "(", "\"\"\...
https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/infi/pkg_resources/__init__.py#L1219-L1245
NeuralEnsemble/python-neo
34d4db8fb0dc950dbbc6defd7fb75e99ea877286
neo/core/baseneo.py
python
BaseNeo.merge_annotations
(self, *others)
Merge annotations from the other object into this one. Merging follows these rules: All keys that are in the either object, but not both, are kept. For keys that are present in both objects: For arrays or lists: concatenate the two arrays For dicts: merge recursively For strings: concatenate with ';' Otherwise: fail if the annotations are not equal
Merge annotations from the other object into this one.
[ "Merge", "annotations", "from", "the", "other", "object", "into", "this", "one", "." ]
def merge_annotations(self, *others): """ Merge annotations from the other object into this one. Merging follows these rules: All keys that are in the either object, but not both, are kept. For keys that are present in both objects: For arrays or lists: concatenate the two arrays For dicts: merge recursively For strings: concatenate with ';' Otherwise: fail if the annotations are not equal """ other_annotations = [other.annotations for other in others] merged_annotations = merge_annotations(self.annotations, *other_annotations) self.annotations.update(merged_annotations)
[ "def", "merge_annotations", "(", "self", ",", "*", "others", ")", ":", "other_annotations", "=", "[", "other", ".", "annotations", "for", "other", "in", "others", "]", "merged_annotations", "=", "merge_annotations", "(", "self", ".", "annotations", ",", "*", ...
https://github.com/NeuralEnsemble/python-neo/blob/34d4db8fb0dc950dbbc6defd7fb75e99ea877286/neo/core/baseneo.py#L338-L353
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/setuptools/pkg_resources/__init__.py
python
NullProvider.metadata_isdir
(self, name)
return self.egg_info and self._isdir(self._fn(self.egg_info, name))
[]
def metadata_isdir(self, name): return self.egg_info and self._isdir(self._fn(self.egg_info, name))
[ "def", "metadata_isdir", "(", "self", ",", "name", ")", ":", "return", "self", ".", "egg_info", "and", "self", ".", "_isdir", "(", "self", ".", "_fn", "(", "self", ".", "egg_info", ",", "name", ")", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/setuptools/pkg_resources/__init__.py#L1469-L1470
beetbox/beets
2fea53c34dd505ba391cb345424e0613901c8025
beets/library.py
python
DefaultTemplateFunctions.tmpl_lower
(s)
return s.lower()
Convert a string to lower case.
Convert a string to lower case.
[ "Convert", "a", "string", "to", "lower", "case", "." ]
def tmpl_lower(s): """Convert a string to lower case.""" return s.lower()
[ "def", "tmpl_lower", "(", "s", ")", ":", "return", "s", ".", "lower", "(", ")" ]
https://github.com/beetbox/beets/blob/2fea53c34dd505ba391cb345424e0613901c8025/beets/library.py#L1620-L1622
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/cryptography/hazmat/primitives/padding.py
python
ANSIX923.padder
(self)
return _ANSIX923PaddingContext(self.block_size)
[]
def padder(self): return _ANSIX923PaddingContext(self.block_size)
[ "def", "padder", "(", "self", ")", ":", "return", "_ANSIX923PaddingContext", "(", "self", ".", "block_size", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/cryptography/hazmat/primitives/padding.py#L154-L155
PixarAnimationStudios/OpenTimelineIO
990a54ccbe6488180a93753370fc87902b982962
contrib/opentimelineio_contrib/adapters/hls_playlist.py
python
Byterange.from_string
(cls, byterange_string)
return cls.from_match_dict(m.groupdict())
Construct a :class:`Byterange` given a string in HLS format. :param byterange_string: (:class:`str`) a byterange string. :return: (:class:`Byterange`) The instance for the provided string.
Construct a :class:`Byterange` given a string in HLS format.
[ "Construct", "a", ":", "class", ":", "Byterange", "given", "a", "string", "in", "HLS", "format", "." ]
def from_string(cls, byterange_string): """Construct a :class:`Byterange` given a string in HLS format. :param byterange_string: (:class:`str`) a byterange string. :return: (:class:`Byterange`) The instance for the provided string. """ m = BYTERANGE_RE.match(byterange_string) return cls.from_match_dict(m.groupdict())
[ "def", "from_string", "(", "cls", ",", "byterange_string", ")", ":", "m", "=", "BYTERANGE_RE", ".", "match", "(", "byterange_string", ")", "return", "cls", ".", "from_match_dict", "(", "m", ".", "groupdict", "(", ")", ")" ]
https://github.com/PixarAnimationStudios/OpenTimelineIO/blob/990a54ccbe6488180a93753370fc87902b982962/contrib/opentimelineio_contrib/adapters/hls_playlist.py#L360-L368
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/auth.py
python
S3HmacAuthV4Handler.presign
(self, req, expires, iso_date=None)
return '%s://%s%s?%s' % (req.protocol, req.host, req.path, urllib.parse.urlencode(req.params))
Presign a request using SigV4 query params. Takes in an HTTP request and an expiration time in seconds and returns a URL. http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
Presign a request using SigV4 query params. Takes in an HTTP request and an expiration time in seconds and returns a URL.
[ "Presign", "a", "request", "using", "SigV4", "query", "params", ".", "Takes", "in", "an", "HTTP", "request", "and", "an", "expiration", "time", "in", "seconds", "and", "returns", "a", "URL", "." ]
def presign(self, req, expires, iso_date=None): """ Presign a request using SigV4 query params. Takes in an HTTP request and an expiration time in seconds and returns a URL. http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html """ if iso_date is None: iso_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ') region = self.determine_region_name(req.host) service = self.determine_service_name(req.host) params = { 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256', 'X-Amz-Credential': '%s/%s/%s/%s/aws4_request' % ( self._provider.access_key, iso_date[:8], region, service ), 'X-Amz-Date': iso_date, 'X-Amz-Expires': expires, 'X-Amz-SignedHeaders': 'host' } if self._provider.security_token: params['X-Amz-Security-Token'] = self._provider.security_token headers_to_sign = self.headers_to_sign(req) l = sorted(['%s' % n.lower().strip() for n in headers_to_sign]) params['X-Amz-SignedHeaders'] = ';'.join(l) req.params.update(params) cr = self.canonical_request(req) # We need to replace the payload SHA with a constant cr = '\n'.join(cr.split('\n')[:-1]) + '\nUNSIGNED-PAYLOAD' # Date header is expected for string_to_sign, but unused otherwise req.headers['X-Amz-Date'] = iso_date sts = self.string_to_sign(req, cr) signature = self.signature(req, sts) # Add signature to params now that we have it req.params['X-Amz-Signature'] = signature return '%s://%s%s?%s' % (req.protocol, req.host, req.path, urllib.parse.urlencode(req.params))
[ "def", "presign", "(", "self", ",", "req", ",", "expires", ",", "iso_date", "=", "None", ")", ":", "if", "iso_date", "is", "None", ":", "iso_date", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%Y%m%dT%H%M%SZ'", ")"...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/auth.py#L765-L815
naver/sqlova
fc68af6008fd2fd5839210e4b06a352007f609b6
sqlova/utils/utils_wikisql.py
python
pred_wvi_se
(wn, s_wv)
return pr_wvi
s_wv: [B, 4, mL, 2] - predict best st-idx & ed-idx
s_wv: [B, 4, mL, 2] - predict best st-idx & ed-idx
[ "s_wv", ":", "[", "B", "4", "mL", "2", "]", "-", "predict", "best", "st", "-", "idx", "&", "ed", "-", "idx" ]
def pred_wvi_se(wn, s_wv): """ s_wv: [B, 4, mL, 2] - predict best st-idx & ed-idx """ s_wv_st, s_wv_ed = s_wv.split(1, dim=3) # [B, 4, mL, 2] -> [B, 4, mL, 1], [B, 4, mL, 1] s_wv_st = s_wv_st.squeeze(3) # [B, 4, mL, 1] -> [B, 4, mL] s_wv_ed = s_wv_ed.squeeze(3) pr_wvi_st_idx = s_wv_st.argmax(dim=2) # [B, 4, mL] -> [B, 4, 1] pr_wvi_ed_idx = s_wv_ed.argmax(dim=2) pr_wvi = [] for b, wn1 in enumerate(wn): pr_wvi1 = [] for i_wn in range(wn1): pr_wvi_st_idx11 = pr_wvi_st_idx[b][i_wn] pr_wvi_ed_idx11 = pr_wvi_ed_idx[b][i_wn] pr_wvi1.append([pr_wvi_st_idx11.item(), pr_wvi_ed_idx11.item()]) pr_wvi.append(pr_wvi1) return pr_wvi
[ "def", "pred_wvi_se", "(", "wn", ",", "s_wv", ")", ":", "s_wv_st", ",", "s_wv_ed", "=", "s_wv", ".", "split", "(", "1", ",", "dim", "=", "3", ")", "# [B, 4, mL, 2] -> [B, 4, mL, 1], [B, 4, mL, 1]", "s_wv_st", "=", "s_wv_st", ".", "squeeze", "(", "3", ")", ...
https://github.com/naver/sqlova/blob/fc68af6008fd2fd5839210e4b06a352007f609b6/sqlova/utils/utils_wikisql.py#L995-L1018
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/heatmapgl/_hoverlabel.py
python
Hoverlabel.__init__
( self, arg=None, align=None, alignsrc=None, bgcolor=None, bgcolorsrc=None, bordercolor=None, bordercolorsrc=None, font=None, namelength=None, namelengthsrc=None, **kwargs )
Construct a new Hoverlabel object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.heatmapgl.Hoverlabel` align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`. Returns ------- Hoverlabel
Construct a new Hoverlabel object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.heatmapgl.Hoverlabel` align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`.
[ "Construct", "a", "new", "Hoverlabel", "object", "Parameters", "----------", "arg", "dict", "of", "properties", "compatible", "with", "this", "constructor", "or", "an", "instance", "of", ":", "class", ":", "plotly", ".", "graph_objs", ".", "heatmapgl", ".", "H...
def __init__( self, arg=None, align=None, alignsrc=None, bgcolor=None, bgcolorsrc=None, bordercolor=None, bordercolorsrc=None, font=None, namelength=None, namelengthsrc=None, **kwargs ): """ Construct a new Hoverlabel object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.heatmapgl.Hoverlabel` align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`. Returns ------- Hoverlabel """ super(Hoverlabel, self).__init__("hoverlabel") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.heatmapgl.Hoverlabel constructor must be a dict or an instance of :class:`plotly.graph_objs.heatmapgl.Hoverlabel`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("align", None) _v = align if align is not None else _v if _v is not None: self["align"] = _v _v = arg.pop("alignsrc", None) _v = alignsrc if alignsrc is not None else _v if _v is not None: self["alignsrc"] = _v _v = arg.pop("bgcolor", None) _v = bgcolor if bgcolor is not None else _v if _v is not None: self["bgcolor"] = _v _v = arg.pop("bgcolorsrc", None) _v = bgcolorsrc if bgcolorsrc is not None else _v if _v is not None: self["bgcolorsrc"] = _v _v = arg.pop("bordercolor", None) _v = bordercolor if bordercolor is not None else _v if _v is not None: self["bordercolor"] = _v _v = arg.pop("bordercolorsrc", None) _v = bordercolorsrc if bordercolorsrc is not None else _v if _v is not None: self["bordercolorsrc"] = _v _v = arg.pop("font", None) _v = font if font is not None else _v if _v is not None: self["font"] = _v _v = arg.pop("namelength", None) _v = namelength if namelength is not None else _v if _v is not None: self["namelength"] = _v _v = arg.pop("namelengthsrc", None) _v = namelengthsrc if namelengthsrc is not None else _v if _v is not None: self["namelengthsrc"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "align", "=", "None", ",", "alignsrc", "=", "None", ",", "bgcolor", "=", "None", ",", "bgcolorsrc", "=", "None", ",", "bordercolor", "=", "None", ",", "bordercolorsrc", "=", "None", ",", "...
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/heatmapgl/_hoverlabel.py#L371-L503
google/capirca
679e3885e3a5e5e129dc2dfab204ec44d63b26a4
capirca/lib/junipermsmpc.py
python
JuniperMSMPC._BuildTokens
(self)
return supported_tokens, supported_sub_tokens
Build supported tokens for platform. Returns: tuple containing both supported tokens and sub tokens
Build supported tokens for platform.
[ "Build", "supported", "tokens", "for", "platform", "." ]
def _BuildTokens(self): """Build supported tokens for platform. Returns: tuple containing both supported tokens and sub tokens """ supported_tokens, supported_sub_tokens = super()._BuildTokens() supported_tokens |= { 'destination_prefix', 'destination_prefix_except', 'icmp_code', 'logging', 'owner', 'source_prefix', 'source_prefix_except' } supported_sub_tokens.update({ 'option': { 'established', # TODO(sneakywombat): add all options to lex. '.*', # make ArbitraryOptions work, yolo. 'tcp-established', 'inactive' } }) return supported_tokens, supported_sub_tokens
[ "def", "_BuildTokens", "(", "self", ")", ":", "supported_tokens", ",", "supported_sub_tokens", "=", "super", "(", ")", ".", "_BuildTokens", "(", ")", "supported_tokens", "|=", "{", "'destination_prefix'", ",", "'destination_prefix_except'", ",", "'icmp_code'", ",", ...
https://github.com/google/capirca/blob/679e3885e3a5e5e129dc2dfab204ec44d63b26a4/capirca/lib/junipermsmpc.py#L341-L362
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/cherrypy/process/servers.py
python
check_port
(host, port, timeout=1.0)
Raise an error if the given port is not free on the given host.
Raise an error if the given port is not free on the given host.
[ "Raise", "an", "error", "if", "the", "given", "port", "is", "not", "free", "on", "the", "given", "host", "." ]
def check_port(host, port, timeout=1.0): """Raise an error if the given port is not free on the given host.""" if not host: raise ValueError("Host values of '' or None are not allowed.") host = client_host(host) port = int(port) import socket # AF_INET or AF_INET6 socket # Get the correct address family for our host (allows IPv6 addresses) try: info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) except socket.gaierror: if ':' in host: info = [(socket.AF_INET6, socket.SOCK_STREAM, 0, "", (host, port, 0, 0))] else: info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", (host, port))] for res in info: af, socktype, proto, canonname, sa = res s = None try: s = socket.socket(af, socktype, proto) # See http://groups.google.com/group/cherrypy-users/ # browse_frm/thread/bbfe5eb39c904fe0 s.settimeout(timeout) s.connect((host, port)) s.close() raise IOError("Port %s is in use on %s; perhaps the previous " "httpserver did not shut down properly." % (repr(port), repr(host))) except socket.error: if s: s.close()
[ "def", "check_port", "(", "host", ",", "port", ",", "timeout", "=", "1.0", ")", ":", "if", "not", "host", ":", "raise", "ValueError", "(", "\"Host values of '' or None are not allowed.\"", ")", "host", "=", "client_host", "(", "host", ")", "port", "=", "int"...
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/cherrypy/process/servers.py#L351-L386
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/sndhdr.py
python
whathdr
(filename)
Recognize sound headers.
Recognize sound headers.
[ "Recognize", "sound", "headers", "." ]
def whathdr(filename): """Recognize sound headers.""" with open(filename, 'rb') as f: h = f.read(512) for tf in tests: res = tf(h, f) if res: return SndHeaders(*res) return None
[ "def", "whathdr", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "h", "=", "f", ".", "read", "(", "512", ")", "for", "tf", "in", "tests", ":", "res", "=", "tf", "(", "h", ",", "f", ")", "if", "...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/sndhdr.py#L58-L66
taokong/FoveaBox
50ce41e5af9cfba562877a318231e53c3b3ce767
tools/detectron2pytorch.py
python
convert
(src, dst, depth)
Convert keys in detectron pretrained ResNet models to pytorch style.
Convert keys in detectron pretrained ResNet models to pytorch style.
[ "Convert", "keys", "in", "detectron", "pretrained", "ResNet", "models", "to", "pytorch", "style", "." ]
def convert(src, dst, depth): """Convert keys in detectron pretrained ResNet models to pytorch style.""" # load arch_settings if depth not in arch_settings: raise ValueError('Only support ResNet-50 and ResNet-101 currently') block_nums = arch_settings[depth] # load caffe model caffe_model = mmcv.load(src, encoding='latin1') blobs = caffe_model['blobs'] if 'blobs' in caffe_model else caffe_model # convert to pytorch style state_dict = OrderedDict() converted_names = set() convert_conv_fc(blobs, state_dict, 'conv1', 'conv1', converted_names) convert_bn(blobs, state_dict, 'res_conv1_bn', 'bn1', converted_names) for i in range(1, len(block_nums) + 1): for j in range(block_nums[i - 1]): if j == 0: convert_conv_fc(blobs, state_dict, 'res{}_{}_branch1'.format(i + 1, j), 'layer{}.{}.downsample.0'.format(i, j), converted_names) convert_bn(blobs, state_dict, 'res{}_{}_branch1_bn'.format(i + 1, j), 'layer{}.{}.downsample.1'.format(i, j), converted_names) for k, letter in enumerate(['a', 'b', 'c']): convert_conv_fc(blobs, state_dict, 'res{}_{}_branch2{}'.format(i + 1, j, letter), 'layer{}.{}.conv{}'.format(i, j, k + 1), converted_names) convert_bn(blobs, state_dict, 'res{}_{}_branch2{}_bn'.format(i + 1, j, letter), 'layer{}.{}.bn{}'.format(i, j, k + 1), converted_names) # check if all layers are converted for key in blobs: if key not in converted_names: print('Not Convert: {}'.format(key)) # save checkpoint checkpoint = dict() checkpoint['state_dict'] = state_dict torch.save(checkpoint, dst)
[ "def", "convert", "(", "src", ",", "dst", ",", "depth", ")", ":", "# load arch_settings", "if", "depth", "not", "in", "arch_settings", ":", "raise", "ValueError", "(", "'Only support ResNet-50 and ResNet-101 currently'", ")", "block_nums", "=", "arch_settings", "[",...
https://github.com/taokong/FoveaBox/blob/50ce41e5af9cfba562877a318231e53c3b3ce767/tools/detectron2pytorch.py#L34-L75
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/distlib/database.py
python
Distribution.matches_requirement
(self, req)
return result
Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False.
Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False.
[ "Say", "if", "this", "instance", "matches", "(", "fulfills", ")", "a", "requirement", ".", ":", "param", "req", ":", "The", "requirement", "to", "match", ".", ":", "rtype", "req", ":", "str", ":", "return", ":", "True", "if", "it", "matches", "else", ...
def matches_requirement(self, req): """ Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False. """ # Requirement may contain extras - parse to lose those # from what's passed to the matcher r = parse_requirement(req) scheme = get_scheme(self.metadata.scheme) try: matcher = scheme.matcher(r.requirement) except UnsupportedVersionError: # XXX compat-mode if cannot read the version logger.warning('could not read version %r - using name only', req) name = req.split()[0] matcher = scheme.matcher(name) name = matcher.key # case-insensitive result = False for p in self.provides: p_name, p_ver = parse_name_and_version(p) if p_name != name: continue try: result = matcher.match(p_ver) break except UnsupportedVersionError: pass return result
[ "def", "matches_requirement", "(", "self", ",", "req", ")", ":", "# Requirement may contain extras - parse to lose those", "# from what's passed to the matcher", "r", "=", "parse_requirement", "(", "req", ")", "scheme", "=", "get_scheme", "(", "self", ".", "metadata", "...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/distlib/database.py#L399-L431
certtools/intelmq
7c1ab88b77bcbb30c7cabca5bb3525ad4aaac138
intelmq/lib/bot.py
python
Bot.check
(parameters: dict)
The bot's own check function can perform individual checks on it's parameters. `init()` is *not* called before, this is a staticmethod which does not require class initialization. Parameters: parameters: Bot's parameters, defaults and runtime merged together Returns: output: None or a list of [log_level, log_message] pairs, both strings. log_level must be a valid log level.
The bot's own check function can perform individual checks on it's parameters. `init()` is *not* called before, this is a staticmethod which does not require class initialization.
[ "The", "bot", "s", "own", "check", "function", "can", "perform", "individual", "checks", "on", "it", "s", "parameters", ".", "init", "()", "is", "*", "not", "*", "called", "before", "this", "is", "a", "staticmethod", "which", "does", "not", "require", "c...
def check(parameters: dict) -> Optional[List[List[str]]]: """ The bot's own check function can perform individual checks on it's parameters. `init()` is *not* called before, this is a staticmethod which does not require class initialization. Parameters: parameters: Bot's parameters, defaults and runtime merged together Returns: output: None or a list of [log_level, log_message] pairs, both strings. log_level must be a valid log level. """ pass
[ "def", "check", "(", "parameters", ":", "dict", ")", "->", "Optional", "[", "List", "[", "List", "[", "str", "]", "]", "]", ":", "pass" ]
https://github.com/certtools/intelmq/blob/7c1ab88b77bcbb30c7cabca5bb3525ad4aaac138/intelmq/lib/bot.py#L887-L901
xonsh/xonsh
b76d6f994f22a4078f602f8b386f4ec280c8461f
xonsh/parsers/base.py
python
BaseParser.p_op_factor
(self, p)
op_factor : times_tok factor | at_tok factor | divide_tok factor | mod_tok factor | doublediv_tok factor
op_factor : times_tok factor | at_tok factor | divide_tok factor | mod_tok factor | doublediv_tok factor
[ "op_factor", ":", "times_tok", "factor", "|", "at_tok", "factor", "|", "divide_tok", "factor", "|", "mod_tok", "factor", "|", "doublediv_tok", "factor" ]
def p_op_factor(self, p): """ op_factor : times_tok factor | at_tok factor | divide_tok factor | mod_tok factor | doublediv_tok factor """ p1 = p[1] op = self._term_binops[p1.value] if op is None: self._set_error( f"operation {p1!r} not supported", self.currloc(lineno=p.lineno, column=p.lexpos), ) p[0] = [op(lineno=p1.lineno, col_offset=p1.lexpos), p[2]]
[ "def", "p_op_factor", "(", "self", ",", "p", ")", ":", "p1", "=", "p", "[", "1", "]", "op", "=", "self", ".", "_term_binops", "[", "p1", ".", "value", "]", "if", "op", "is", "None", ":", "self", ".", "_set_error", "(", "f\"operation {p1!r} not suppor...
https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/parsers/base.py#L2142-L2157
reahl/reahl
86aac47c3a9b5b98e9f77dad4939034a02d54d46
reahl-browsertools/reahl/browsertools/browsertools.py
python
XPath.link
(cls)
return cls.any('a')
Returns an XPath to find an HTML <a>. .. versionadded:: 5.0
Returns an XPath to find an HTML <a>.
[ "Returns", "an", "XPath", "to", "find", "an", "HTML", "<a", ">", "." ]
def link(cls): """Returns an XPath to find an HTML <a>. .. versionadded:: 5.0 """ return cls.any('a')
[ "def", "link", "(", "cls", ")", ":", "return", "cls", ".", "any", "(", "'a'", ")" ]
https://github.com/reahl/reahl/blob/86aac47c3a9b5b98e9f77dad4939034a02d54d46/reahl-browsertools/reahl/browsertools/browsertools.py#L658-L663
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/hazardlib/__init__.py
python
_get_ebruptures
(fname, conv=None, ses_seed=None)
return ebrs
:param fname: path to a rupture file (XML or CSV) :param conv: RuptureConverter instanc, used for XML ruptures :param ses_seed: used for XML ruptures :returns: a list of one or more EBRuptures
:param fname: path to a rupture file (XML or CSV) :param conv: RuptureConverter instanc, used for XML ruptures :param ses_seed: used for XML ruptures :returns: a list of one or more EBRuptures
[ ":", "param", "fname", ":", "path", "to", "a", "rupture", "file", "(", "XML", "or", "CSV", ")", ":", "param", "conv", ":", "RuptureConverter", "instanc", "used", "for", "XML", "ruptures", ":", "param", "ses_seed", ":", "used", "for", "XML", "ruptures", ...
def _get_ebruptures(fname, conv=None, ses_seed=None): """ :param fname: path to a rupture file (XML or CSV) :param conv: RuptureConverter instanc, used for XML ruptures :param ses_seed: used for XML ruptures :returns: a list of one or more EBRuptures """ if fname.endswith('.xml'): [rup_node] = nrml.read(fname) rup = conv.convert_node(rup_node) rup.tectonic_region_type = '*' # no TRT for scenario ruptures rup.rup_id = ses_seed ebrs = [EBRupture(rup, 'NA', 0, id=rup.rup_id, scenario=True)] return ebrs assert fname.endswith('.csv'), fname aw = get_ruptures(fname) ebrs = [] for i, rec in enumerate(aw.array): rupture = _get_rupture(rec, aw.geoms[i], aw.trts[rec['trt_smr']]) ebr = EBRupture(rupture, rec['source_id'], rec['trt_smr'], rec['n_occ'], rec['id'], rec['e0']) ebrs.append(ebr) return ebrs
[ "def", "_get_ebruptures", "(", "fname", ",", "conv", "=", "None", ",", "ses_seed", "=", "None", ")", ":", "if", "fname", ".", "endswith", "(", "'.xml'", ")", ":", "[", "rup_node", "]", "=", "nrml", ".", "read", "(", "fname", ")", "rup", "=", "conv"...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/__init__.py#L80-L103