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
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/pip/_vendor/retrying.py
python
Retrying.fixed_sleep
(self, previous_attempt_number, delay_since_first_attempt_ms)
return self._wait_fixed
Sleep a fixed amount of time between each retry.
Sleep a fixed amount of time between each retry.
[ "Sleep", "a", "fixed", "amount", "of", "time", "between", "each", "retry", "." ]
def fixed_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """Sleep a fixed amount of time between each retry.""" return self._wait_fixed
[ "def", "fixed_sleep", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "return", "self", ".", "_wait_fixed" ]
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/pip/_vendor/retrying.py#L153-L155
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/rich/live.py
python
Live.refresh
(self)
Update the display of the Live Render.
Update the display of the Live Render.
[ "Update", "the", "display", "of", "the", "Live", "Render", "." ]
def refresh(self) -> None: """Update the display of the Live Render.""" with self._lock: self._live_render.set_renderable(self.renderable) if self.console.is_jupyter: # pragma: no cover try: from IPython.display import display from ipywidgets import Output except ImportError: import warnings warnings.warn('install "ipywidgets" for Jupyter support') else: if self.ipy_widget is None: self.ipy_widget = Output() display(self.ipy_widget) with self.ipy_widget: self.ipy_widget.clear_output(wait=True) self.console.print(self._live_render.renderable) elif self.console.is_terminal and not self.console.is_dumb_terminal: with self.console: self.console.print(Control()) elif ( not self._started and not self.transient ): # if it is finished allow files or dumb-terminals to see final result with self.console: self.console.print(Control())
[ "def", "refresh", "(", "self", ")", "->", "None", ":", "with", "self", ".", "_lock", ":", "self", ".", "_live_render", ".", "set_renderable", "(", "self", ".", "renderable", ")", "if", "self", ".", "console", ".", "is_jupyter", ":", "# pragma: no cover", ...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/rich/live.py#L216-L243
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/subprocess.py
python
check_output
(*popenargs, **kwargs)
return output
r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n'
r"""Run command with arguments and return its output as a byte string.
[ "r", "Run", "command", "with", "arguments", "and", "return", "its", "output", "as", "a", "byte", "string", "." ]
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n' """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd, output=output) return output
[ "def", "check_output", "(", "*", "popenargs", ",", "*", "*", "kwargs", ")", ":", "if", "'stdout'", "in", "kwargs", ":", "raise", "ValueError", "(", "'stdout argument not allowed, it will be overridden.'", ")", "process", "=", "Popen", "(", "stdout", "=", "PIPE",...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/subprocess.py#L545-L575
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_swat_modelinstance/receivers.py
python
_process_metadata_update_create
(**kwargs)
[]
def _process_metadata_update_create(**kwargs): element_name = kwargs['element_name'].lower() request = kwargs['request'] if element_name == "modeloutput": element_form = ModelOutputValidationForm(request.POST) elif element_name == 'executedby': element_form = ExecutedByValidationForm(request.POST) elif element_name == 'modelobjective': element_form = ModelObjectiveValidationForm(request.POST) elif element_name == 'simulationtype': element_form = SimulationTypeValidationForm(request.POST) elif element_name == 'modelmethod': element_form = ModelMethodValidationForm(request.POST) elif element_name == 'modelparameter': element_form = ModelParameterValidationForm(request.POST) elif element_name == 'modelinput': element_form = ModelInputValidationForm(request.POST) if element_form.is_valid(): return {'is_valid': True, 'element_data_dict': element_form.cleaned_data} else: return {'is_valid': False, 'element_data_dict': None, "errors": element_form.errors}
[ "def", "_process_metadata_update_create", "(", "*", "*", "kwargs", ")", ":", "element_name", "=", "kwargs", "[", "'element_name'", "]", ".", "lower", "(", ")", "request", "=", "kwargs", "[", "'request'", "]", "if", "element_name", "==", "\"modeloutput\"", ":",...
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_swat_modelinstance/receivers.py#L46-L68
21dotco/two1-python
4e833300fd5a58363e3104ed4c097631e5d296d3
two1/channels/database.py
python
DatabaseBase.create
(self, model)
Create a new payment channel in the database. Args: model (PaymentChannelModel): Payment channel state model.
Create a new payment channel in the database.
[ "Create", "a", "new", "payment", "channel", "in", "the", "database", "." ]
def create(self, model): """Create a new payment channel in the database. Args: model (PaymentChannelModel): Payment channel state model. """ raise NotImplementedError()
[ "def", "create", "(", "self", ",", "model", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/21dotco/two1-python/blob/4e833300fd5a58363e3104ed4c097631e5d296d3/two1/channels/database.py#L15-L22
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distlib/database.py
python
_Cache.clear
(self)
Clear the cache, setting it to its initial state.
Clear the cache, setting it to its initial state.
[ "Clear", "the", "cache", "setting", "it", "to", "its", "initial", "state", "." ]
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
[ "def", "clear", "(", "self", ")", ":", "self", ".", "name", ".", "clear", "(", ")", "self", ".", "path", ".", "clear", "(", ")", "self", ".", "generated", "=", "False" ]
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distlib/database.py#L56-L62
google/capirca
679e3885e3a5e5e129dc2dfab204ec44d63b26a4
capirca/lib/nacaddr.py
python
_InNetList
(adders, ip)
return False
Returns True if ip is contained in adders.
Returns True if ip is contained in adders.
[ "Returns", "True", "if", "ip", "is", "contained", "in", "adders", "." ]
def _InNetList(adders, ip): """Returns True if ip is contained in adders.""" for addr in adders: if ip.subnet_of(addr): return True return False
[ "def", "_InNetList", "(", "adders", ",", "ip", ")", ":", "for", "addr", "in", "adders", ":", "if", "ip", ".", "subnet_of", "(", "addr", ")", ":", "return", "True", "return", "False" ]
https://github.com/google/capirca/blob/679e3885e3a5e5e129dc2dfab204ec44d63b26a4/capirca/lib/nacaddr.py#L227-L232
awesto/django-shop
13d9a77aff7eede74a5f363c1d540e005d88dbcd
shop/money/money_maker.py
python
AbstractMoney.__radd__
(self, other, context=None)
return self.__add__(other, context)
[]
def __radd__(self, other, context=None): return self.__add__(other, context)
[ "def", "__radd__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "return", "self", ".", "__add__", "(", "other", ",", "context", ")" ]
https://github.com/awesto/django-shop/blob/13d9a77aff7eede74a5f363c1d540e005d88dbcd/shop/money/money_maker.py#L96-L97
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/core/brine.py
python
_load_none
(stream)
return None
[]
def _load_none(stream): return None
[ "def", "_load_none", "(", "stream", ")", ":", "return", "None" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/core/brine.py#L208-L209
mgedmin/check-manifest
19f0a43ba00ecc536832f93801cf4446ea42e9b4
check_manifest.py
python
_get_ignore_from_manifest_lines
(lines, ui)
return ignore
Gather the various ignore patterns from a MANIFEST.in. 'lines' should be a list of strings with comments removed and continuation lines joined. Returns an IgnoreList instance.
Gather the various ignore patterns from a MANIFEST.in.
[ "Gather", "the", "various", "ignore", "patterns", "from", "a", "MANIFEST", ".", "in", "." ]
def _get_ignore_from_manifest_lines(lines, ui): """Gather the various ignore patterns from a MANIFEST.in. 'lines' should be a list of strings with comments removed and continuation lines joined. Returns an IgnoreList instance. """ ignore = IgnoreList() for line in lines: try: cmd, rest = line.split(None, 1) except ValueError: # no whitespace, so not interesting continue for part in rest.split(): # distutils enforces these warnings on Windows only if part.startswith('/'): ui.warning("ERROR: Leading slashes are not allowed in MANIFEST.in on Windows: %s" % part) if part.endswith('/'): ui.warning("ERROR: Trailing slashes are not allowed in MANIFEST.in on Windows: %s" % part) if cmd == 'exclude': ignore.exclude(*rest.split()) elif cmd == 'global-exclude': ignore.global_exclude(*rest.split()) elif cmd == 'recursive-exclude': try: dirname, patterns = rest.split(None, 1) except ValueError: # Wrong MANIFEST.in line. ui.warning( "You have a wrong line in MANIFEST.in: %r\n" "'recursive-exclude' expects <dir> <pattern1> <pattern2>..." % line ) continue ignore.recursive_exclude(dirname, *patterns.split()) elif cmd == 'prune': ignore.prune(rest) # XXX: This ignores all 'include'/'global-include'/'recusive-include'/'graft' commands, # which is wrong! Quoting the documentation: # # The order of commands in the manifest template matters: initially, # we have the list of default files as described above, and each # command in the template adds to or removes from that list of # files. # -- https://docs.python.org/3.8/distutils/sourcedist.html#specifying-the-files-to-distribute return ignore
[ "def", "_get_ignore_from_manifest_lines", "(", "lines", ",", "ui", ")", ":", "ignore", "=", "IgnoreList", "(", ")", "for", "line", "in", "lines", ":", "try", ":", "cmd", ",", "rest", "=", "line", ".", "split", "(", "None", ",", "1", ")", "except", "V...
https://github.com/mgedmin/check-manifest/blob/19f0a43ba00ecc536832f93801cf4446ea42e9b4/check_manifest.py#L774-L821
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/numerical/ga/moga.py
python
MOGA.code_decoded
(self, decoded_pop)
return binary_pop
Returns a binary coded population from a decoded population Parameters ---------- decoded_pop: dict The decoded population dictionary to be coded Returns ------- binary_pop: dict The binary population dictionary.
Returns a binary coded population from a decoded population
[ "Returns", "a", "binary", "coded", "population", "from", "a", "decoded", "population" ]
def code_decoded(self, decoded_pop): """Returns a binary coded population from a decoded population Parameters ---------- decoded_pop: dict The decoded population dictionary to be coded Returns ------- binary_pop: dict The binary population dictionary. """ binary_pop = [[[]] * self.num_var for i in range(self.num_pop)] for i in range(len(decoded_pop)): binary_pop[i] = {} for j in range(self.num_var): bin_list = [] temp_bin = bin(decoded_pop[i][j])[2:] temp_bin = temp_bin[::-1] digit_dif = self.num_bin_dig[j] - len(temp_bin) for h in range(digit_dif): temp_bin = temp_bin + '0' for k in range(self.num_bin_dig[j]): bin_list.append(int(temp_bin[k])) binary_pop[i][j] = bin_list return binary_pop
[ "def", "code_decoded", "(", "self", ",", "decoded_pop", ")", ":", "binary_pop", "=", "[", "[", "[", "]", "]", "*", "self", ".", "num_var", "for", "i", "in", "range", "(", "self", ".", "num_pop", ")", "]", "for", "i", "in", "range", "(", "len", "(...
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/numerical/ga/moga.py#L829-L855
IntelLabs/coach
dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d
rl_coach/architectures/tensorflow_components/architecture.py
python
TensorFlowArchitecture.apply_gradients
(self, gradients, scaler=1., additional_inputs=None)
Applies the given gradients to the network weights :param gradients: The gradients to use for the update :param scaler: A scaling factor that allows rescaling the gradients before applying them. The gradients will be MULTIPLIED by this factor :param additional_inputs: optional additional inputs required for when applying the gradients (e.g. batchnorm's update ops also requires the inputs)
Applies the given gradients to the network weights :param gradients: The gradients to use for the update :param scaler: A scaling factor that allows rescaling the gradients before applying them. The gradients will be MULTIPLIED by this factor :param additional_inputs: optional additional inputs required for when applying the gradients (e.g. batchnorm's update ops also requires the inputs)
[ "Applies", "the", "given", "gradients", "to", "the", "network", "weights", ":", "param", "gradients", ":", "The", "gradients", "to", "use", "for", "the", "update", ":", "param", "scaler", ":", "A", "scaling", "factor", "that", "allows", "rescaling", "the", ...
def apply_gradients(self, gradients, scaler=1., additional_inputs=None): """ Applies the given gradients to the network weights :param gradients: The gradients to use for the update :param scaler: A scaling factor that allows rescaling the gradients before applying them. The gradients will be MULTIPLIED by this factor :param additional_inputs: optional additional inputs required for when applying the gradients (e.g. batchnorm's update ops also requires the inputs) """ if self.network_parameters.async_training or not isinstance(self.ap.task_parameters, DistributedTaskParameters): if hasattr(self, 'global_step') and not self.network_is_local: self.sess.run(self.inc_step) if self.optimizer_type != 'LBFGS': if self.distributed_training and not self.network_parameters.async_training: # rescale the gradients so that they average out with the gradients from the other workers if self.network_parameters.scale_down_gradients_by_number_of_workers_for_sync_training: scaler /= float(self.ap.task_parameters.num_training_tasks) # rescale the gradients if scaler != 1.: for gradient in gradients: gradient *= scaler # apply the gradients feed_dict = dict(zip(self.weights_placeholders, gradients)) if self.distributed_training and self.network_parameters.shared_optimizer \ and not self.network_parameters.async_training: # synchronous distributed training with shared optimizer: # - each worker adds its gradients to the shared gradients accumulators # - we wait for all the workers to add their gradients # - the chief worker (worker with task index = 0) applies the gradients once and resets the accumulators self.sess.run(self.accumulate_shared_gradients, feed_dict=feed_dict) self.wait_for_all_workers_barrier(include_only_training_workers=True) if self.is_chief: self.sess.run(self.update_weights_from_shared_gradients) self.sess.run(self.init_shared_accumulated_gradients) else: # async distributed training / distributed training with independent optimizer # / non-distributed training - just apply the gradients feed_dict = dict(zip(self.weights_placeholders, gradients)) if additional_inputs is not None: feed_dict = {**feed_dict, **self.create_feed_dict(additional_inputs)} self.sess.run(self.update_weights_from_batch_gradients, feed_dict=feed_dict) # release barrier if self.distributed_training and not self.network_parameters.async_training: self.wait_for_all_workers_barrier(include_only_training_workers=True)
[ "def", "apply_gradients", "(", "self", ",", "gradients", ",", "scaler", "=", "1.", ",", "additional_inputs", "=", "None", ")", ":", "if", "self", ".", "network_parameters", ".", "async_training", "or", "not", "isinstance", "(", "self", ".", "ap", ".", "tas...
https://github.com/IntelLabs/coach/blob/dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d/rl_coach/architectures/tensorflow_components/architecture.py#L469-L521
openstack/taskflow
38b9011094dbcfdd00e6446393816201e8256d38
taskflow/engines/action_engine/compiler.py
python
_overlap_occurrence_detector
(to_graph, from_graph)
return iter_utils.count(node for node in from_graph.nodes if node in to_graph)
Returns how many nodes in 'from' graph are in 'to' graph (if any).
Returns how many nodes in 'from' graph are in 'to' graph (if any).
[ "Returns", "how", "many", "nodes", "in", "from", "graph", "are", "in", "to", "graph", "(", "if", "any", ")", "." ]
def _overlap_occurrence_detector(to_graph, from_graph): """Returns how many nodes in 'from' graph are in 'to' graph (if any).""" return iter_utils.count(node for node in from_graph.nodes if node in to_graph)
[ "def", "_overlap_occurrence_detector", "(", "to_graph", ",", "from_graph", ")", ":", "return", "iter_utils", ".", "count", "(", "node", "for", "node", "in", "from_graph", ".", "nodes", "if", "node", "in", "to_graph", ")" ]
https://github.com/openstack/taskflow/blob/38b9011094dbcfdd00e6446393816201e8256d38/taskflow/engines/action_engine/compiler.py#L108-L111
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/dialects/sybase/base.py
python
SybaseSQLCompiler.delete_extra_from_clause
(self, delete_stmt, from_table, extra_froms, from_hints, **kw)
return "FROM " + ', '.join( t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw) for t in [from_table] + extra_froms)
Render the DELETE .. FROM clause specific to Sybase.
Render the DELETE .. FROM clause specific to Sybase.
[ "Render", "the", "DELETE", "..", "FROM", "clause", "specific", "to", "Sybase", "." ]
def delete_extra_from_clause(self, delete_stmt, from_table, extra_froms, from_hints, **kw): """Render the DELETE .. FROM clause specific to Sybase.""" return "FROM " + ', '.join( t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw) for t in [from_table] + extra_froms)
[ "def", "delete_extra_from_clause", "(", "self", ",", "delete_stmt", ",", "from_table", ",", "extra_froms", ",", "from_hints", ",", "*", "*", "kw", ")", ":", "return", "\"FROM \"", "+", "', '", ".", "join", "(", "t", ".", "_compiler_dispatch", "(", "self", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/dialects/sybase/base.py#L382-L388
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
K8/Web-Exp/sqlmap/lib/core/common.py
python
showHttpErrorCodes
()
Shows all HTTP error codes raised till now
Shows all HTTP error codes raised till now
[ "Shows", "all", "HTTP", "error", "codes", "raised", "till", "now" ]
def showHttpErrorCodes(): """ Shows all HTTP error codes raised till now """ if kb.httpErrorCodes: warnMsg = "HTTP error codes detected during run:\n" warnMsg += ", ".join("%d (%s) - %d times" % (code, httplib.responses[code] \ if code in httplib.responses else '?', count) \ for code, count in kb.httpErrorCodes.items()) logger.warn(warnMsg) if any((str(_).startswith('4') or str(_).startswith('5')) and _ != httplib.INTERNAL_SERVER_ERROR and _ != kb.originalCode for _ in kb.httpErrorCodes.keys()): msg = "too many 4xx and/or 5xx HTTP error codes " msg += "could mean that some kind of protection is involved (e.g. WAF)" logger.debug(msg)
[ "def", "showHttpErrorCodes", "(", ")", ":", "if", "kb", ".", "httpErrorCodes", ":", "warnMsg", "=", "\"HTTP error codes detected during run:\\n\"", "warnMsg", "+=", "\", \"", ".", "join", "(", "\"%d (%s) - %d times\"", "%", "(", "code", ",", "httplib", ".", "respo...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/K8/Web-Exp/sqlmap/lib/core/common.py#L2905-L2919
zhangxiaosong18/FreeAnchor
afad43a7c48034301d981d831fa61e42d9b6ddad
maskrcnn_benchmark/modeling/roi_heads/box_head/loss.py
python
FastRCNNLossComputation.__init__
(self, proposal_matcher, fg_bg_sampler, box_coder)
Arguments: proposal_matcher (Matcher) fg_bg_sampler (BalancedPositiveNegativeSampler) box_coder (BoxCoder)
Arguments: proposal_matcher (Matcher) fg_bg_sampler (BalancedPositiveNegativeSampler) box_coder (BoxCoder)
[ "Arguments", ":", "proposal_matcher", "(", "Matcher", ")", "fg_bg_sampler", "(", "BalancedPositiveNegativeSampler", ")", "box_coder", "(", "BoxCoder", ")" ]
def __init__(self, proposal_matcher, fg_bg_sampler, box_coder): """ Arguments: proposal_matcher (Matcher) fg_bg_sampler (BalancedPositiveNegativeSampler) box_coder (BoxCoder) """ self.proposal_matcher = proposal_matcher self.fg_bg_sampler = fg_bg_sampler self.box_coder = box_coder
[ "def", "__init__", "(", "self", ",", "proposal_matcher", ",", "fg_bg_sampler", ",", "box_coder", ")", ":", "self", ".", "proposal_matcher", "=", "proposal_matcher", "self", ".", "fg_bg_sampler", "=", "fg_bg_sampler", "self", ".", "box_coder", "=", "box_coder" ]
https://github.com/zhangxiaosong18/FreeAnchor/blob/afad43a7c48034301d981d831fa61e42d9b6ddad/maskrcnn_benchmark/modeling/roi_heads/box_head/loss.py#L21-L30
williballenthin/python-registry
11e857623469dd28ed14519a08d2db7c8228ca0c
samples/copyclean.py
python
Copy.pack_dword
(self, offset, *data)
write little-endian DWORDs (4 bytes) to the relative offset. Arguments: - `offset`: The relative offset from the start of the block. - `data`: The data to be written, can be multiple
write little-endian DWORDs (4 bytes) to the relative offset. Arguments: - `offset`: The relative offset from the start of the block. - `data`: The data to be written, can be multiple
[ "write", "little", "-", "endian", "DWORDs", "(", "4", "bytes", ")", "to", "the", "relative", "offset", ".", "Arguments", ":", "-", "offset", ":", "The", "relative", "offset", "from", "the", "start", "of", "the", "block", ".", "-", "data", ":", "The", ...
def pack_dword(self, offset, *data): """ write little-endian DWORDs (4 bytes) to the relative offset. Arguments: - `offset`: The relative offset from the start of the block. - `data`: The data to be written, can be multiple """ g_logger.debug("write dword 0x%08x at offset 0x%08x" % (data[0], self._offset + offset)) #return struct.pack_into(str("<I"), self._writer, self._offset + offset, *data) self._writer.seek(offset) self._writer.write(struct.pack(str("<I"), *data))
[ "def", "pack_dword", "(", "self", ",", "offset", ",", "*", "data", ")", ":", "g_logger", ".", "debug", "(", "\"write dword 0x%08x at offset 0x%08x\"", "%", "(", "data", "[", "0", "]", ",", "self", ".", "_offset", "+", "offset", ")", ")", "#return struct.pa...
https://github.com/williballenthin/python-registry/blob/11e857623469dd28ed14519a08d2db7c8228ca0c/samples/copyclean.py#L56-L66
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo.create_ustar_header
(self, info, encoding, errors)
return self._create_header(info, USTAR_FORMAT, encoding, errors)
Return the object as a ustar header block.
Return the object as a ustar header block.
[ "Return", "the", "object", "as", "a", "ustar", "header", "block", "." ]
def create_ustar_header(self, info, encoding, errors): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"]) > LENGTH_LINK: raise ValueError("linkname is too long") if len(info["name"]) > LENGTH_NAME: info["prefix"], info["name"] = self._posix_split_name(info["name"]) return self._create_header(info, USTAR_FORMAT, encoding, errors)
[ "def", "create_ustar_header", "(", "self", ",", "info", ",", "encoding", ",", "errors", ")", ":", "info", "[", "\"magic\"", "]", "=", "POSIX_MAGIC", "if", "len", "(", "info", "[", "\"linkname\"", "]", ")", ">", "LENGTH_LINK", ":", "raise", "ValueError", ...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1016-L1027
brendano/tweetmotif
1b0b1e3a941745cd5a26eba01f554688b7c4b27e
everything_else/djfrontend/django-1.0.2/contrib/gis/gdal/geometries.py
python
GeometryCollection.__len__
(self)
return self.geom_count
The number of geometries in this Geometry Collection.
The number of geometries in this Geometry Collection.
[ "The", "number", "of", "geometries", "in", "this", "Geometry", "Collection", "." ]
def __len__(self): "The number of geometries in this Geometry Collection." return self.geom_count
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "geom_count" ]
https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/contrib/gis/gdal/geometries.py#L599-L601
openstack/python-keystoneclient
100253d52e0c62dffffddb6f046ad660a9bce1a9
keystoneclient/v3/access_rules.py
python
AccessRuleManager.get
(self, access_rule, user=None)
return super(AccessRuleManager, self).get( access_rule_id=base.getid(access_rule))
Retrieve an access rule. :param access_rule: the access rule to be retrieved from the server :type access_rule: str or :class:`keystoneclient.v3.access_rules.AccessRule` :param string user: User ID :returns: the specified access rule :rtype: :class:`keystoneclient.v3.access_rules.AccessRule`
Retrieve an access rule.
[ "Retrieve", "an", "access", "rule", "." ]
def get(self, access_rule, user=None): """Retrieve an access rule. :param access_rule: the access rule to be retrieved from the server :type access_rule: str or :class:`keystoneclient.v3.access_rules.AccessRule` :param string user: User ID :returns: the specified access rule :rtype: :class:`keystoneclient.v3.access_rules.AccessRule` """ user = user or self.client.user_id self.base_url = '/users/%(user)s' % {'user': user} return super(AccessRuleManager, self).get( access_rule_id=base.getid(access_rule))
[ "def", "get", "(", "self", ",", "access_rule", ",", "user", "=", "None", ")", ":", "user", "=", "user", "or", "self", ".", "client", ".", "user_id", "self", ".", "base_url", "=", "'/users/%(user)s'", "%", "{", "'user'", ":", "user", "}", "return", "s...
https://github.com/openstack/python-keystoneclient/blob/100253d52e0c62dffffddb6f046ad660a9bce1a9/keystoneclient/v3/access_rules.py#L44-L62
blue-oil/blueoil
0c9160b524b17482d59ae48a0c11384f1d26dccc
blueoil/networks/object_detection/yolo_v1.py
python
YoloV1.offset_boxes
(self)
return offset_x, offset_y
Return yolo space offset of x and y. Return: offset_x: shape is [batch_size, cell_size, cell_size, boxes_per_cell] offset_y: shape is [batch_size, cell_size, cell_size, boxes_per_cell]
Return yolo space offset of x and y.
[ "Return", "yolo", "space", "offset", "of", "x", "and", "y", "." ]
def offset_boxes(self): """Return yolo space offset of x and y. Return: offset_x: shape is [batch_size, cell_size, cell_size, boxes_per_cell] offset_y: shape is [batch_size, cell_size, cell_size, boxes_per_cell] """ offset_y = np.arange(self.cell_size) offset_y = np.reshape(offset_y, (1, self.cell_size, 1, 1)) offset_y = np.tile(offset_y, [self.batch_size, 1, self.cell_size, self.boxes_per_cell]) offset_x = np.transpose(offset_y, (0, 2, 1, 3)) return offset_x, offset_y
[ "def", "offset_boxes", "(", "self", ")", ":", "offset_y", "=", "np", ".", "arange", "(", "self", ".", "cell_size", ")", "offset_y", "=", "np", ".", "reshape", "(", "offset_y", ",", "(", "1", ",", "self", ".", "cell_size", ",", "1", ",", "1", ")", ...
https://github.com/blue-oil/blueoil/blob/0c9160b524b17482d59ae48a0c11384f1d26dccc/blueoil/networks/object_detection/yolo_v1.py#L163-L175
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/externals/tqdm/_tqdm/std.py
python
tqdm.format_dict
(self)
return dict( n=self.n, total=self.total, elapsed=self._time() - self.start_t if hasattr(self, 'start_t') else 0, ncols=self.dynamic_ncols(self.fp) if self.dynamic_ncols else self.ncols, prefix=self.desc, ascii=self.ascii, unit=self.unit, unit_scale=self.unit_scale, rate=1 / self.avg_time if self.avg_time else None, bar_format=self.bar_format, postfix=self.postfix, unit_divisor=self.unit_divisor)
Public API for read-only member access.
Public API for read-only member access.
[ "Public", "API", "for", "read", "-", "only", "member", "access", "." ]
def format_dict(self): """Public API for read-only member access.""" return dict( n=self.n, total=self.total, elapsed=self._time() - self.start_t if hasattr(self, 'start_t') else 0, ncols=self.dynamic_ncols(self.fp) if self.dynamic_ncols else self.ncols, prefix=self.desc, ascii=self.ascii, unit=self.unit, unit_scale=self.unit_scale, rate=1 / self.avg_time if self.avg_time else None, bar_format=self.bar_format, postfix=self.postfix, unit_divisor=self.unit_divisor)
[ "def", "format_dict", "(", "self", ")", ":", "return", "dict", "(", "n", "=", "self", ".", "n", ",", "total", "=", "self", ".", "total", ",", "elapsed", "=", "self", ".", "_time", "(", ")", "-", "self", ".", "start_t", "if", "hasattr", "(", "self...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/externals/tqdm/_tqdm/std.py#L1401-L1413
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/RepositoryKey.py
python
RepositoryKey.title
(self)
return self._title.value
:type: string
:type: string
[ ":", "type", ":", "string" ]
def title(self): """ :type: string """ self._completeIfNotSet(self._title) return self._title.value
[ "def", "title", "(", "self", ")", ":", "self", ".", "_completeIfNotSet", "(", "self", ".", "_title", ")", "return", "self", ".", "_title", ".", "value" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/RepositoryKey.py#L76-L81
ntoll/drogulus
d74b78d0bf0220b91f075dbd3f9a06c2663b474e
drogulus/dht/storage.py
python
DictDataStore.keys
(self)
return self._dict.keys()
Return a view object of the keys in this data store.
Return a view object of the keys in this data store.
[ "Return", "a", "view", "object", "of", "the", "keys", "in", "this", "data", "store", "." ]
def keys(self): """ Return a view object of the keys in this data store. """ return self._dict.keys()
[ "def", "keys", "(", "self", ")", ":", "return", "self", ".", "_dict", ".", "keys", "(", ")" ]
https://github.com/ntoll/drogulus/blob/d74b78d0bf0220b91f075dbd3f9a06c2663b474e/drogulus/dht/storage.py#L164-L168
nipy/nipy
d16d268938dcd5c15748ca051532c21f57cf8a22
nipy/algorithms/statistics/models/model.py
python
LikelihoodModelResults.Fcontrast
(self, matrix, dispersion=None, invcov=None)
return FContrastResults( effect=ctheta, covariance=self.vcov( matrix=matrix, dispersion=dispersion[np.newaxis]), F=F, df_den=self.df_resid, df_num=invcov.shape[0])
Compute an Fcontrast for a contrast matrix `matrix`. Here, `matrix` M is assumed to be non-singular. More precisely .. math:: M pX pX' M' is assumed invertible. Here, :math:`pX` is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. See the contrast module to see how to specify contrasts. In particular, the matrices from these contrasts will always be non-singular in the sense above. Parameters ---------- matrix : 1D array-like contrast matrix dispersion : None or float, optional If None, use ``self.dispersion`` invcov : None or array, optional Known inverse of variance covariance matrix. If None, calculate this matrix. Returns ------- f_res : ``FContrastResults`` instance with attributes F, df_den, df_num Notes ----- For F contrasts, we now specify an effect and covariance
Compute an Fcontrast for a contrast matrix `matrix`.
[ "Compute", "an", "Fcontrast", "for", "a", "contrast", "matrix", "matrix", "." ]
def Fcontrast(self, matrix, dispersion=None, invcov=None): """ Compute an Fcontrast for a contrast matrix `matrix`. Here, `matrix` M is assumed to be non-singular. More precisely .. math:: M pX pX' M' is assumed invertible. Here, :math:`pX` is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. See the contrast module to see how to specify contrasts. In particular, the matrices from these contrasts will always be non-singular in the sense above. Parameters ---------- matrix : 1D array-like contrast matrix dispersion : None or float, optional If None, use ``self.dispersion`` invcov : None or array, optional Known inverse of variance covariance matrix. If None, calculate this matrix. Returns ------- f_res : ``FContrastResults`` instance with attributes F, df_den, df_num Notes ----- For F contrasts, we now specify an effect and covariance """ matrix = np.asarray(matrix) # 1D vectors assumed to be row vector if matrix.ndim == 1: matrix = matrix[None] if matrix.shape[1] != self.theta.shape[0]: raise ValueError("F contrasts should have shape[1] P=%d, " "but this has shape[1] %d" % (self.theta.shape[0], matrix.shape[1])) ctheta = np.dot(matrix, self.theta) if matrix.ndim == 1: matrix = matrix.reshape((1, matrix.shape[0])) if dispersion is None: dispersion = self.dispersion q = matrix.shape[0] if invcov is None: invcov = inv(self.vcov(matrix=matrix, dispersion=1.0)) F = np.add.reduce(np.dot(invcov, ctheta) * ctheta, 0) *\ pos_recipr((q * dispersion)) F = np.squeeze(F) return FContrastResults( effect=ctheta, covariance=self.vcov( matrix=matrix, dispersion=dispersion[np.newaxis]), F=F, df_den=self.df_resid, df_num=invcov.shape[0])
[ "def", "Fcontrast", "(", "self", ",", "matrix", ",", "dispersion", "=", "None", ",", "invcov", "=", "None", ")", ":", "matrix", "=", "np", ".", "asarray", "(", "matrix", ")", "# 1D vectors assumed to be row vector", "if", "matrix", ".", "ndim", "==", "1", ...
https://github.com/nipy/nipy/blob/d16d268938dcd5c15748ca051532c21f57cf8a22/nipy/algorithms/statistics/models/model.py#L264-L322
SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions
014c4ca27a70b5907a183e942228004c989dcbe4
selim_sef/generate_polygons.py
python
_remove_interiors
(line)
return line
[]
def _remove_interiors(line): if "), (" in line: line_prefix = line.split('), (')[0] line_terminate = line.split('))",')[-1] line = ( line_prefix + '))",' + line_terminate ) return line
[ "def", "_remove_interiors", "(", "line", ")", ":", "if", "\"), (\"", "in", "line", ":", "line_prefix", "=", "line", ".", "split", "(", "'), ('", ")", "[", "0", "]", "line_terminate", "=", "line", ".", "split", "(", "'))\",'", ")", "[", "-", "1", "]",...
https://github.com/SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions/blob/014c4ca27a70b5907a183e942228004c989dcbe4/selim_sef/generate_polygons.py#L114-L123
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/pep425tags.py
python
get_config_var
(var)
[]
def get_config_var(var): try: return sysconfig.get_config_var(var) except IOError as e: # Issue #1074 warnings.warn("{0}".format(e), RuntimeWarning) return None
[ "def", "get_config_var", "(", "var", ")", ":", "try", ":", "return", "sysconfig", ".", "get_config_var", "(", "var", ")", "except", "IOError", "as", "e", ":", "# Issue #1074", "warnings", ".", "warn", "(", "\"{0}\"", ".", "format", "(", "e", ")", ",", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/pep425tags.py#L25-L30
ppizarror/pygame-menu
da5827a1ad0686e8ff2aa536b74bbfba73967bcf
pygame_menu/widgets/core/widget.py
python
Widget.get_frame_depth
(self)
return depth
Get frame depth (If frame is packed within another frame). :return: Frame depth
Get frame depth (If frame is packed within another frame).
[ "Get", "frame", "depth", "(", "If", "frame", "is", "packed", "within", "another", "frame", ")", "." ]
def get_frame_depth(self) -> int: """ Get frame depth (If frame is packed within another frame). :return: Frame depth """ frame = self._frame depth = 0 if frame is not None: while True: if frame is None: break depth += 1 frame = frame._frame return depth
[ "def", "get_frame_depth", "(", "self", ")", "->", "int", ":", "frame", "=", "self", ".", "_frame", "depth", "=", "0", "if", "frame", "is", "not", "None", ":", "while", "True", ":", "if", "frame", "is", "None", ":", "break", "depth", "+=", "1", "fra...
https://github.com/ppizarror/pygame-menu/blob/da5827a1ad0686e8ff2aa536b74bbfba73967bcf/pygame_menu/widgets/core/widget.py#L3055-L3069
astorfi/speechpy
7ffaa4d6909eef0afeef2741a8cd0cd0a42c4a67
speechpy/processing.py
python
cmvn
(vec, variance_normalization=False)
return output
This function is aimed to perform global cepstral mean and variance normalization (CMVN) on input feature vector "vec". The code assumes that there is one observation per row. Args: vec (array): input feature matrix (size:(num_observation,num_features)) variance_normalization (bool): If the variance normilization should be performed or not. Return: array: The mean(or mean+variance) normalized feature vector.
This function is aimed to perform global cepstral mean and variance normalization (CMVN) on input feature vector "vec". The code assumes that there is one observation per row.
[ "This", "function", "is", "aimed", "to", "perform", "global", "cepstral", "mean", "and", "variance", "normalization", "(", "CMVN", ")", "on", "input", "feature", "vector", "vec", ".", "The", "code", "assumes", "that", "there", "is", "one", "observation", "pe...
def cmvn(vec, variance_normalization=False): """ This function is aimed to perform global cepstral mean and variance normalization (CMVN) on input feature vector "vec". The code assumes that there is one observation per row. Args: vec (array): input feature matrix (size:(num_observation,num_features)) variance_normalization (bool): If the variance normilization should be performed or not. Return: array: The mean(or mean+variance) normalized feature vector. """ eps = 2**-30 rows, cols = vec.shape # Mean calculation norm = np.mean(vec, axis=0) norm_vec = np.tile(norm, (rows, 1)) # Mean subtraction mean_subtracted = vec - norm_vec # Variance normalization if variance_normalization: stdev = np.std(mean_subtracted, axis=0) stdev_vec = np.tile(stdev, (rows, 1)) output = mean_subtracted / (stdev_vec + eps) else: output = mean_subtracted return output
[ "def", "cmvn", "(", "vec", ",", "variance_normalization", "=", "False", ")", ":", "eps", "=", "2", "**", "-", "30", "rows", ",", "cols", "=", "vec", ".", "shape", "# Mean calculation", "norm", "=", "np", ".", "mean", "(", "vec", ",", "axis", "=", "...
https://github.com/astorfi/speechpy/blob/7ffaa4d6909eef0afeef2741a8cd0cd0a42c4a67/speechpy/processing.py#L239-L271
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/asn1crypto/_errors.py
python
unwrap
(string, *params)
return output
Takes a multi-line string and does the following: - dedents - converts newlines with text before and after into a single line - strips leading and trailing whitespace :param string: The string to format :param *params: Params to interpolate into the string :return: The formatted string
Takes a multi-line string and does the following:
[ "Takes", "a", "multi", "-", "line", "string", "and", "does", "the", "following", ":" ]
def unwrap(string, *params): """ Takes a multi-line string and does the following: - dedents - converts newlines with text before and after into a single line - strips leading and trailing whitespace :param string: The string to format :param *params: Params to interpolate into the string :return: The formatted string """ output = textwrap.dedent(string) # Unwrap lines, taking into account bulleted lists, ordered lists and # underlines consisting of = signs if output.find('\n') != -1: output = re.sub('(?<=\\S)\n(?=[^ \n\t\\d\\*\\-=])', ' ', output) if params: output = output % params output = output.strip() return output
[ "def", "unwrap", "(", "string", ",", "*", "params", ")", ":", "output", "=", "textwrap", ".", "dedent", "(", "string", ")", "# Unwrap lines, taking into account bulleted lists, ordered lists and", "# underlines consisting of = signs", "if", "output", ".", "find", "(", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/asn1crypto/_errors.py#L15-L45
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pip/req/req_file.py
python
break_args_options
(line)
return ' '.join(args), ' '.join(options)
Break up the line into an args and options string. We only want to shlex (and then optparse) the options, not the args. args can contain markers which are corrupted by shlex.
Break up the line into an args and options string. We only want to shlex (and then optparse) the options, not the args. args can contain markers which are corrupted by shlex.
[ "Break", "up", "the", "line", "into", "an", "args", "and", "options", "string", ".", "We", "only", "want", "to", "shlex", "(", "and", "then", "optparse", ")", "the", "options", "not", "the", "args", ".", "args", "can", "contain", "markers", "which", "a...
def break_args_options(line): """Break up the line into an args and options string. We only want to shlex (and then optparse) the options, not the args. args can contain markers which are corrupted by shlex. """ tokens = line.split(' ') args = [] options = tokens[:] for token in tokens: if token.startswith('-') or token.startswith('--'): break else: args.append(token) options.pop(0) return ' '.join(args), ' '.join(options)
[ "def", "break_args_options", "(", "line", ")", ":", "tokens", "=", "line", ".", "split", "(", "' '", ")", "args", "=", "[", "]", "options", "=", "tokens", "[", ":", "]", "for", "token", "in", "tokens", ":", "if", "token", ".", "startswith", "(", "'...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/req/req_file.py#L253-L267
sokolovstas/SublimeWebInspector
e808d12956f115ea2b37bdf46fbfdb20b4e5ec13
swi.py
python
SwiDebugCommand.command_selected
(self, index)
Called by Sublime when a quick panel entry is selected
Called by Sublime when a quick panel entry is selected
[ "Called", "by", "Sublime", "when", "a", "quick", "panel", "entry", "is", "selected" ]
def command_selected(self, index): """ Called by Sublime when a quick panel entry is selected """ utils.assert_main_thread() if index == -1: return command = self.cmds[index] if command == 'swi_dump_file_mappings': # we wrap this command so we can use the correct view print(command) v = views.find_or_create_view('mapping') v.run_command('swi_dump_file_mappings_internal') return self.window.run_command(command)
[ "def", "command_selected", "(", "self", ",", "index", ")", ":", "utils", ".", "assert_main_thread", "(", ")", "if", "index", "==", "-", "1", ":", "return", "command", "=", "self", ".", "cmds", "[", "index", "]", "if", "command", "==", "'swi_dump_file_map...
https://github.com/sokolovstas/SublimeWebInspector/blob/e808d12956f115ea2b37bdf46fbfdb20b4e5ec13/swi.py#L119-L134
awslabs/gluon-ts
066ec3b7f47aa4ee4c061a28f35db7edbad05a98
src/gluonts/nursery/SCott/pts/model/forecast.py
python
DistributionForecast.mean_ts
(self)
return pd.Series(data=self.mean, index=self.index)
Forecast mean, as a pandas.Series object.
Forecast mean, as a pandas.Series object.
[ "Forecast", "mean", "as", "a", "pandas", ".", "Series", "object", "." ]
def mean_ts(self) -> pd.Series: """ Forecast mean, as a pandas.Series object. """ return pd.Series(data=self.mean, index=self.index)
[ "def", "mean_ts", "(", "self", ")", "->", "pd", ".", "Series", ":", "return", "pd", ".", "Series", "(", "data", "=", "self", ".", "mean", ",", "index", "=", "self", ".", "index", ")" ]
https://github.com/awslabs/gluon-ts/blob/066ec3b7f47aa4ee4c061a28f35db7edbad05a98/src/gluonts/nursery/SCott/pts/model/forecast.py#L544-L548
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/olefile/olefile.py
python
OleDirectoryEntry.dump
(self, tab = 0)
Dump this entry, and all its subentries (for debug purposes only)
Dump this entry, and all its subentries (for debug purposes only)
[ "Dump", "this", "entry", "and", "all", "its", "subentries", "(", "for", "debug", "purposes", "only", ")" ]
def dump(self, tab = 0): "Dump this entry, and all its subentries (for debug purposes only)" TYPES = ["(invalid)", "(storage)", "(stream)", "(lockbytes)", "(property)", "(root)"] print(" "*tab + repr(self.name), TYPES[self.entry_type], end=' ') if self.entry_type in (STGTY_STREAM, STGTY_ROOT): print(self.size, "bytes", end=' ') print() if self.entry_type in (STGTY_STORAGE, STGTY_ROOT) and self.clsid: print(" "*tab + "{%s}" % self.clsid) for kid in self.kids: kid.dump(tab + 2)
[ "def", "dump", "(", "self", ",", "tab", "=", "0", ")", ":", "TYPES", "=", "[", "\"(invalid)\"", ",", "\"(storage)\"", ",", "\"(stream)\"", ",", "\"(lockbytes)\"", ",", "\"(property)\"", ",", "\"(root)\"", "]", "print", "(", "\" \"", "*", "tab", "+", "rep...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/olefile/olefile.py#L1095-L1107
0xInfection/XSRFProbe
ce0411174fa2e438bea0712bdd2acf74f7f62d9a
xsrfprobe/modules/Debugger.py
python
getAllForms
(soup)
return soup.findAll('form', method=re.compile("post", re.IGNORECASE))
[]
def getAllForms(soup): # get all forms return soup.findAll('form', method=re.compile("post", re.IGNORECASE))
[ "def", "getAllForms", "(", "soup", ")", ":", "# get all forms", "return", "soup", ".", "findAll", "(", "'form'", ",", "method", "=", "re", ".", "compile", "(", "\"post\"", ",", "re", ".", "IGNORECASE", ")", ")" ]
https://github.com/0xInfection/XSRFProbe/blob/ce0411174fa2e438bea0712bdd2acf74f7f62d9a/xsrfprobe/modules/Debugger.py#L150-L151
bit4woo/teemo
b7c1bca65c9e9e6b00f362284e74665e20cbf707
searchengine/search_shodan.py
python
search_shodan.do_search
(self)
[]
def do_search(self): try: api = shodan.Shodan(self.apikey) self.results = api.search(self.word) self.totalresults +=str(self.results) return True except shodan.APIError, e: logger.error("Error in {0}: {1}".format(__file__.split('/')[-1],e)) return False
[ "def", "do_search", "(", "self", ")", ":", "try", ":", "api", "=", "shodan", ".", "Shodan", "(", "self", ".", "apikey", ")", "self", ".", "results", "=", "api", ".", "search", "(", "self", ".", "word", ")", "self", ".", "totalresults", "+=", "str",...
https://github.com/bit4woo/teemo/blob/b7c1bca65c9e9e6b00f362284e74665e20cbf707/searchengine/search_shodan.py#L36-L44
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/base64.py
python
urlsafe_b64encode
(s)
return b64encode(s, '-_')
Encode a string using a url-safe Base64 alphabet. s is the string to encode. The encoded string is returned. The alphabet uses '-' instead of '+' and '_' instead of '/'.
Encode a string using a url-safe Base64 alphabet.
[ "Encode", "a", "string", "using", "a", "url", "-", "safe", "Base64", "alphabet", "." ]
def urlsafe_b64encode(s): """Encode a string using a url-safe Base64 alphabet. s is the string to encode. The encoded string is returned. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ return b64encode(s, '-_')
[ "def", "urlsafe_b64encode", "(", "s", ")", ":", "return", "b64encode", "(", "s", ",", "'-_'", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/base64.py#L95-L101
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/decision_tree.py
python
DecisionTree.print_leafs
(self)
[]
def print_leafs(self): LOGGER.debug('printing tree') if len(self.tree_node) == 0: LOGGER.debug('this tree is empty') else: for node in self.tree_node: LOGGER.debug(node)
[ "def", "print_leafs", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'printing tree'", ")", "if", "len", "(", "self", ".", "tree_node", ")", "==", "0", ":", "LOGGER", ".", "debug", "(", "'this tree is empty'", ")", "else", ":", "for", "node", "in...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/decision_tree.py#L453-L459
jaheyns/CfdOF
97fab2347e421eaad7cb549006329425112b9e21
CfdTools.py
python
convertMesh
(case, mesh_file, scale)
Convert gmsh created UNV mesh to FOAM. A scaling of 1e-3 is prescribed as the CAD is always in mm while FOAM uses SI units (m).
Convert gmsh created UNV mesh to FOAM. A scaling of 1e-3 is prescribed as the CAD is always in mm while FOAM uses SI units (m).
[ "Convert", "gmsh", "created", "UNV", "mesh", "to", "FOAM", ".", "A", "scaling", "of", "1e", "-", "3", "is", "prescribed", "as", "the", "CAD", "is", "always", "in", "mm", "while", "FOAM", "uses", "SI", "units", "(", "m", ")", "." ]
def convertMesh(case, mesh_file, scale): """ Convert gmsh created UNV mesh to FOAM. A scaling of 1e-3 is prescribed as the CAD is always in mm while FOAM uses SI units (m). """ if mesh_file.find(".unv") > 0: mesh_file = translatePath(mesh_file) cmdline = ['ideasUnvToFoam', '"{}"'.format(mesh_file)] runFoamApplication(cmdline, case) # changeBoundaryType(case, 'defaultFaces', 'wall') # rename default boundary type to wall # Set in the correct patch types cmdline = ['changeDictionary'] runFoamApplication(cmdline, case) else: raise Exception("Error: Only supporting unv mesh files.") if scale and isinstance(scale, numbers.Number): cmdline = ['transformPoints', '-scale', '"({} {} {})"'.format(scale, scale, scale)] runFoamApplication(cmdline, case) else: print("Error: mesh scaling ratio is must be a float or integer\n")
[ "def", "convertMesh", "(", "case", ",", "mesh_file", ",", "scale", ")", ":", "if", "mesh_file", ".", "find", "(", "\".unv\"", ")", ">", "0", ":", "mesh_file", "=", "translatePath", "(", "mesh_file", ")", "cmdline", "=", "[", "'ideasUnvToFoam'", ",", "'\"...
https://github.com/jaheyns/CfdOF/blob/97fab2347e421eaad7cb549006329425112b9e21/CfdTools.py#L804-L823
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/utils/utils.py
python
LimitedSizeOrderedDict.__init__
(self, *args, **kwargs)
Limited-size ordered dict. Keyword Args: size_limit (int): Use this to limit the number of elements alloweds to be in this list. By default the overshooting elements will be removed in FIFO order. fifo (bool, optional): Defaults to `True`. Remove overshooting elements in FIFO order. If `False`, remove in FILO order.
Limited-size ordered dict.
[ "Limited", "-", "size", "ordered", "dict", "." ]
def __init__(self, *args, **kwargs): """ Limited-size ordered dict. Keyword Args: size_limit (int): Use this to limit the number of elements alloweds to be in this list. By default the overshooting elements will be removed in FIFO order. fifo (bool, optional): Defaults to `True`. Remove overshooting elements in FIFO order. If `False`, remove in FILO order. """ super().__init__() self.size_limit = kwargs.get("size_limit", None) self.filo = not kwargs.get("fifo", True) # FIFO inverse of FILO self._check_size()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "size_limit", "=", "kwargs", ".", "get", "(", "\"size_limit\"", ",", "None", ")", "self", ".", "filo", ...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/utils/utils.py#L1969-L1984
EasonLiao/CudaTree
fcd9c7f4dbac00c105bbfbff9f55db1d29747fc7
cudatree/util.py
python
compile_module
(module_file, params)
[]
def compile_module(module_file, params): module_file = kernels_dir + module_file key = (module_file, params) if key in _module_cache: return _module_cache[key] with open(module_file) as code_file: start_timer("compile module") code = code_file.read() src = code % params mod = SourceModule(src, include_dirs = [kernels_dir]) _module_cache[key] = mod end_timer("compile module") return mod
[ "def", "compile_module", "(", "module_file", ",", "params", ")", ":", "module_file", "=", "kernels_dir", "+", "module_file", "key", "=", "(", "module_file", ",", "params", ")", "if", "key", "in", "_module_cache", ":", "return", "_module_cache", "[", "key", "...
https://github.com/EasonLiao/CudaTree/blob/fcd9c7f4dbac00c105bbfbff9f55db1d29747fc7/cudatree/util.py#L24-L37
ivre/ivre
5728855b51c0ae2e59450a1c3a782febcad2128b
ivre/db/mongo.py
python
MongoDBFlow.flt_from_query
(cls, query)
return flt
Returns a MongoDB filter from the given query object.
Returns a MongoDB filter from the given query object.
[ "Returns", "a", "MongoDB", "filter", "from", "the", "given", "query", "object", "." ]
def flt_from_query(cls, query): """ Returns a MongoDB filter from the given query object. """ clauses = query.clauses flt = {} and_clauses = [] for and_clause in clauses: or_clauses = [] for or_clause in and_clause: or_clauses.append(cls.flt_from_clause(or_clause)) if len(or_clauses) > 1: and_clauses.append({"$or": or_clauses}) elif len(or_clauses) == 1: and_clauses.append(or_clauses[0]) if len(and_clauses) > 1: flt = {"$and": and_clauses} elif len(and_clauses) == 1: flt = and_clauses[0] return flt
[ "def", "flt_from_query", "(", "cls", ",", "query", ")", ":", "clauses", "=", "query", ".", "clauses", "flt", "=", "{", "}", "and_clauses", "=", "[", "]", "for", "and_clause", "in", "clauses", ":", "or_clauses", "=", "[", "]", "for", "or_clause", "in", ...
https://github.com/ivre/ivre/blob/5728855b51c0ae2e59450a1c3a782febcad2128b/ivre/db/mongo.py#L6011-L6030
openstack/openstacksdk
58384268487fa854f21c470b101641ab382c9897
openstack/compute/v2/_proxy.py
python
Proxy.backup_server
(self, server, name, backup_type, rotation)
Backup a server :param server: Either the ID of a server or a :class:`~openstack.compute.v2.server.Server` instance. :param name: The name of the backup image. :param backup_type: The type of the backup, for example, daily. :param rotation: The rotation of the back up image, the oldest image will be removed when image count exceed the rotation count. :returns: None
Backup a server
[ "Backup", "a", "server" ]
def backup_server(self, server, name, backup_type, rotation): """Backup a server :param server: Either the ID of a server or a :class:`~openstack.compute.v2.server.Server` instance. :param name: The name of the backup image. :param backup_type: The type of the backup, for example, daily. :param rotation: The rotation of the back up image, the oldest image will be removed when image count exceed the rotation count. :returns: None """ server = self._get_resource(_server.Server, server) server.backup(self, name, backup_type, rotation)
[ "def", "backup_server", "(", "self", ",", "server", ",", "name", ",", "backup_type", ",", "rotation", ")", ":", "server", "=", "self", ".", "_get_resource", "(", "_server", ".", "Server", ",", "server", ")", "server", ".", "backup", "(", "self", ",", "...
https://github.com/openstack/openstacksdk/blob/58384268487fa854f21c470b101641ab382c9897/openstack/compute/v2/_proxy.py#L916-L930
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/analysis/ESP/NanoHiveUtils.py
python
NH_Connection.sendCommand
(self, command)
Sends a command to the N-H instance and returns the response. Parameters: command The command to send to the N-H instance Returns: success indicator A one if the command was successfully sent and a response was received response or error message If all was successful, the encoded N-H instance response, or a description of the error if unsuccessful. The encoded response can be decoded with the Nano-Hive/data/local/en_resultCodes.txt file
Sends a command to the N-H instance and returns the response.
[ "Sends", "a", "command", "to", "the", "N", "-", "H", "instance", "and", "returns", "the", "response", "." ]
def sendCommand(self, command): """ Sends a command to the N-H instance and returns the response. Parameters: command The command to send to the N-H instance Returns: success indicator A one if the command was successfully sent and a response was received response or error message If all was successful, the encoded N-H instance response, or a description of the error if unsuccessful. The encoded response can be decoded with the Nano-Hive/data/local/en_resultCodes.txt file """ # Send command success = 1 try: self.connectionHandle.send(command) except socket.error, errorMessage: success = 0 # Read response length if success: try: responseLengthChars = self.connectionHandle.recv(4) except socket.error, errorMessage: success = 0 if success: responseLength = ord(responseLengthChars[0]) responseLength |= ord(responseLengthChars[1]) << 8 responseLength |= ord(responseLengthChars[2]) << 16 responseLength |= ord(responseLengthChars[3]) << 24; # Read response try: response = self.connectionHandle.recv(responseLength) except socket.error, errorMessage: success = 0 if success: return 1, response else: return 0, errorMessage
[ "def", "sendCommand", "(", "self", ",", "command", ")", ":", "# Send command", "success", "=", "1", "try", ":", "self", ".", "connectionHandle", ".", "send", "(", "command", ")", "except", "socket", ".", "error", ",", "errorMessage", ":", "success", "=", ...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/analysis/ESP/NanoHiveUtils.py#L457-L507
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/poplib.py
python
POP3.rpop
(self, user)
return self._shortcmd('RPOP %s' % user)
Not sure what this does.
Not sure what this does.
[ "Not", "sure", "what", "this", "does", "." ]
def rpop(self, user): """Not sure what this does.""" return self._shortcmd('RPOP %s' % user)
[ "def", "rpop", "(", "self", ",", "user", ")", ":", "return", "self", ".", "_shortcmd", "(", "'RPOP %s'", "%", "user", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/poplib.py#L272-L274
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models/albert/tokenization.py
python
FullTokenizer.tokenize
(self, text)
return split_tokens
[]
def tokenize(self, text): split_tokens = [] for token in self.basic_tokenizer.tokenize(text): for sub_token in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) return split_tokens
[ "def", "tokenize", "(", "self", ",", "text", ")", ":", "split_tokens", "=", "[", "]", "for", "token", "in", "self", ".", "basic_tokenizer", ".", "tokenize", "(", "text", ")", ":", "for", "sub_token", "in", "self", ".", "wordpiece_tokenizer", ".", "tokeni...
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models/albert/tokenization.py#L172-L178
hqqasw/person-search-PPCC
3ce82bffff3646291b9a631534e295a6aa749c4d
utils/metric.py
python
affmat2retdict
(affmat, pid_list)
return ret_dict
parse affinity matrix to resutl dict ret_dict: key: target person id value: list of candidates
parse affinity matrix to resutl dict ret_dict: key: target person id value: list of candidates
[ "parse", "affinity", "matrix", "to", "resutl", "dict", "ret_dict", ":", "key", ":", "target", "person", "id", "value", ":", "list", "of", "candidates" ]
def affmat2retdict(affmat, pid_list): """ parse affinity matrix to resutl dict ret_dict: key: target person id value: list of candidates """ num_cast = affmat.shape[0] num_instance = affmat.shape[1] index = np.argsort(-affmat, axis=1) ret_dict = {} for i in range(num_cast): ret_dict[pid_list[i]] = index[i].tolist() return ret_dict
[ "def", "affmat2retdict", "(", "affmat", ",", "pid_list", ")", ":", "num_cast", "=", "affmat", ".", "shape", "[", "0", "]", "num_instance", "=", "affmat", ".", "shape", "[", "1", "]", "index", "=", "np", ".", "argsort", "(", "-", "affmat", ",", "axis"...
https://github.com/hqqasw/person-search-PPCC/blob/3ce82bffff3646291b9a631534e295a6aa749c4d/utils/metric.py#L48-L61
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/interpreter/mesonmain.py
python
MesonMain.get_external_property_method
(self, args: T.Tuple[str, T.Optional[object]], kwargs: 'NativeKW')
return self.__get_external_property_impl(propname, fallback, kwargs['native'])
[]
def get_external_property_method(self, args: T.Tuple[str, T.Optional[object]], kwargs: 'NativeKW') -> object: propname, fallback = args return self.__get_external_property_impl(propname, fallback, kwargs['native'])
[ "def", "get_external_property_method", "(", "self", ",", "args", ":", "T", ".", "Tuple", "[", "str", ",", "T", ".", "Optional", "[", "object", "]", "]", ",", "kwargs", ":", "'NativeKW'", ")", "->", "object", ":", "propname", ",", "fallback", "=", "args...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/interpreter/mesonmain.py#L429-L431
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/wtforms/fields/core.py
python
StringField.process_formdata
(self, valuelist)
[]
def process_formdata(self, valuelist): if valuelist: self.data = valuelist[0] else: self.data = ''
[ "def", "process_formdata", "(", "self", ",", "valuelist", ")", ":", "if", "valuelist", ":", "self", ".", "data", "=", "valuelist", "[", "0", "]", "else", ":", "self", ".", "data", "=", "''" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/wtforms/fields/core.py#L526-L530
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/requests/utils.py
python
should_bypass_proxies
(url, no_proxy)
return False
Returns whether we should bypass proxies or not. :rtype: bool
Returns whether we should bypass proxies or not.
[ "Returns", "whether", "we", "should", "bypass", "proxies", "or", "not", "." ]
def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy('no_proxy') parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = ( host for host in no_proxy.replace(' ', '').split(',') if host ) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += ':{}'.format(parsed.port) for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ('no_proxy', no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False
[ "def", "should_bypass_proxies", "(", "url", ",", "no_proxy", ")", ":", "# Prioritize lowercase environment variables over uppercase", "# to keep a consistent behaviour with other http projects (curl, wget).", "get_proxy", "=", "lambda", "k", ":", "os", ".", "environ", ".", "get...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/requests/utils.py#L734-L792
otto-torino/django-baton
8ae3b2ea1b875cf38031ee4a58a88e9478447193
baton/views.py
python
GetAppListJsonView.get_default_voices
(self)
return voices
When no custom menu is defined in settings Retrieves a js menu ready dict from the django admin app list
When no custom menu is defined in settings Retrieves a js menu ready dict from the django admin app list
[ "When", "no", "custom", "menu", "is", "defined", "in", "settings", "Retrieves", "a", "js", "menu", "ready", "dict", "from", "the", "django", "admin", "app", "list" ]
def get_default_voices(self): """ When no custom menu is defined in settings Retrieves a js menu ready dict from the django admin app list """ voices = [] for app in self.app_list: children = [] for model in app.get('models', []): child = { 'type': 'model', 'label': model.get('name', ''), 'url': model.get('admin_url', '') } children.append(child) voice = { 'type': 'app', 'label': app.get('name', ''), 'url': app.get('app_url', ''), 'children': children } voices.append(voice) return voices
[ "def", "get_default_voices", "(", "self", ")", ":", "voices", "=", "[", "]", "for", "app", "in", "self", ".", "app_list", ":", "children", "=", "[", "]", "for", "model", "in", "app", ".", "get", "(", "'models'", ",", "[", "]", ")", ":", "child", ...
https://github.com/otto-torino/django-baton/blob/8ae3b2ea1b875cf38031ee4a58a88e9478447193/baton/views.py#L218-L240
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_volume.py
python
Yedit.update
(self, path, value, index=None, curr_value=None)
return (False, self.yaml_dict)
put path, value into a dict
put path, value into a dict
[ "put", "path", "value", "into", "a", "dict" ]
def update(self, path, value, index=None, curr_value=None): ''' put path, value into a dict ''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if isinstance(entry, dict): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member if not isinstance(value, dict): raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' + 'value=[{}] type=[{}]'.format(value, type(value))) entry.update(value) return (True, self.yaml_dict) elif isinstance(entry, list): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member ind = None if curr_value: try: ind = entry.index(curr_value) except ValueError: return (False, self.yaml_dict) elif index is not None: ind = index if ind is not None and entry[ind] != value: entry[ind] = value return (True, self.yaml_dict) # see if it exists in the list try: ind = entry.index(value) except ValueError: # doesn't exist, append it entry.append(value) return (True, self.yaml_dict) # already exists, return if ind is not None: return (False, self.yaml_dict) return (False, self.yaml_dict)
[ "def", "update", "(", "self", ",", "path", ",", "value", ",", "index", "=", "None", ",", "curr_value", "=", "None", ")", ":", "try", ":", "entry", "=", "Yedit", ".", "get_entry", "(", "self", ".", "yaml_dict", ",", "path", ",", "self", ".", "separa...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_volume.py#L590-L635
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_group.py
python
OpenShiftCLIConfig.to_option_list
(self, ascommalist='')
return self.stringify(ascommalist)
return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs
return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs
[ "return", "all", "options", "as", "a", "string", "if", "ascommalist", "is", "set", "to", "the", "name", "of", "a", "key", "and", "the", "value", "of", "that", "key", "is", "a", "dict", "format", "the", "dict", "as", "a", "list", "of", "comma", "delim...
def to_option_list(self, ascommalist=''): '''return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs''' return self.stringify(ascommalist)
[ "def", "to_option_list", "(", "self", ",", "ascommalist", "=", "''", ")", ":", "return", "self", ".", "stringify", "(", "ascommalist", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_group.py#L1419-L1424
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/asn1crypto/util.py
python
extended_date.isoformat
(self)
return self.strftime('0000-%m-%d')
Formats the date as %Y-%m-%d :return: The date formatted to %Y-%m-%d as a unicode string in Python 3 and a byte string in Python 2
Formats the date as %Y-%m-%d
[ "Formats", "the", "date", "as", "%Y", "-", "%m", "-", "%d" ]
def isoformat(self): """ Formats the date as %Y-%m-%d :return: The date formatted to %Y-%m-%d as a unicode string in Python 3 and a byte string in Python 2 """ return self.strftime('0000-%m-%d')
[ "def", "isoformat", "(", "self", ")", ":", "return", "self", ".", "strftime", "(", "'0000-%m-%d'", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/asn1crypto/util.py#L267-L276
heineman/python-algorithms
b8a0061b52ff15cbf4a390854cb537a3fa7e309e
6. DepthFirstSearch/graph.py
python
DepthFirstTraversal.dfs_visit
(self, u)
Recursive traversal of graph using DFS
Recursive traversal of graph using DFS
[ "Recursive", "traversal", "of", "graph", "using", "DFS" ]
def dfs_visit(self, u): """Recursive traversal of graph using DFS""" self.color[u] = Gray for v in self.graph.edges[u]: if self.color[v] is White: self.pred[v] = u self.dfs_visit(v) self.color[u] = Black
[ "def", "dfs_visit", "(", "self", ",", "u", ")", ":", "self", ".", "color", "[", "u", "]", "=", "Gray", "for", "v", "in", "self", ".", "graph", ".", "edges", "[", "u", "]", ":", "if", "self", ".", "color", "[", "v", "]", "is", "White", ":", ...
https://github.com/heineman/python-algorithms/blob/b8a0061b52ff15cbf4a390854cb537a3fa7e309e/6. DepthFirstSearch/graph.py#L76-L86
codelv/enaml-native
04c3a015bcd649f374c5ecd98fcddba5e4fbdbdc
src/enamlnative/core/hotswap/core.py
python
Hotswapper.find_best_matching_node
(self, new, old_nodes)
return matches[0] if matches else None
Find the node that best matches the new node given the old nodes. If no good match exists return `None`.
Find the node that best matches the new node given the old nodes. If no good match exists return `None`.
[ "Find", "the", "node", "that", "best", "matches", "the", "new", "node", "given", "the", "old", "nodes", ".", "If", "no", "good", "match", "exists", "return", "None", "." ]
def find_best_matching_node(self, new, old_nodes): """ Find the node that best matches the new node given the old nodes. If no good match exists return `None`. """ name = new.__class__.__name__ #: TODO: We should pick the BEST one from this list #: based on some "matching" criteria (such as matching ref name or params) matches = [c for c in old_nodes if name == c.__class__.__name__] if self.debug: print("Found matches for {}: {} ".format(new, matches)) return matches[0] if matches else None
[ "def", "find_best_matching_node", "(", "self", ",", "new", ",", "old_nodes", ")", ":", "name", "=", "new", ".", "__class__", ".", "__name__", "#: TODO: We should pick the BEST one from this list", "#: based on some \"matching\" criteria (such as matching ref name or params)", "...
https://github.com/codelv/enaml-native/blob/04c3a015bcd649f374c5ecd98fcddba5e4fbdbdc/src/enamlnative/core/hotswap/core.py#L161-L172
OpenMDAO/OpenMDAO
f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd
openmdao/utils/indexer.py
python
ShapedSliceIndexer._check_bounds
(self)
Check that indices are within the bounds of the source shape.
Check that indices are within the bounds of the source shape.
[ "Check", "that", "indices", "are", "within", "the", "bounds", "of", "the", "source", "shape", "." ]
def _check_bounds(self): """ Check that indices are within the bounds of the source shape. """ # a slice with start or stop outside of the source range is allowed in numpy arrays # and just results in an empty array, but in OpenMDAO that behavior would probably be # unintended, so for now make it an error. if self._src_shape is not None: start = self._slice.start stop = self._slice.stop sz = np.product(self._dist_shape) if (start is not None and (start >= sz or start < -sz) or (stop is not None and (stop > sz or stop < -sz))): raise IndexError(f"{self._slice} is out of bounds of the source shape " f"{self._dist_shape}.")
[ "def", "_check_bounds", "(", "self", ")", ":", "# a slice with start or stop outside of the source range is allowed in numpy arrays", "# and just results in an empty array, but in OpenMDAO that behavior would probably be", "# unintended, so for now make it an error.", "if", "self", ".", "_sr...
https://github.com/OpenMDAO/OpenMDAO/blob/f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd/openmdao/utils/indexer.py#L585-L599
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/venv/lib/python2.7/site-packages/setuptools/msvc.py
python
SystemInfo._find_dot_net_versions
(self, bits=32)
return frameworkver
Find Microsoft .NET Framework versions. Parameters ---------- bits: int Platform number of bits: 32 or 64.
Find Microsoft .NET Framework versions.
[ "Find", "Microsoft", ".", "NET", "Framework", "versions", "." ]
def _find_dot_net_versions(self, bits=32): """ Find Microsoft .NET Framework versions. Parameters ---------- bits: int Platform number of bits: 32 or 64. """ # Find actual .NET version ver = self.ri.lookup(self.ri.vc, 'frameworkver%d' % bits) or '' # Set .NET versions for specified MSVC++ version if self.vc_ver >= 12.0: frameworkver = (ver, 'v4.0') elif self.vc_ver >= 10.0: frameworkver = ('v4.0.30319' if ver.lower()[:2] != 'v4' else ver, 'v3.5') elif self.vc_ver == 9.0: frameworkver = ('v3.5', 'v2.0.50727') if self.vc_ver == 8.0: frameworkver = ('v3.0', 'v2.0.50727') return frameworkver
[ "def", "_find_dot_net_versions", "(", "self", ",", "bits", "=", "32", ")", ":", "# Find actual .NET version", "ver", "=", "self", ".", "ri", ".", "lookup", "(", "self", ".", "ri", ".", "vc", ",", "'frameworkver%d'", "%", "bits", ")", "or", "''", "# Set ....
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/setuptools/msvc.py#L719-L741
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/lib-tk/tkSimpleDialog.py
python
Dialog.body
(self, master)
create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method.
create dialog body.
[ "create", "dialog", "body", "." ]
def body(self, master): '''create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method. ''' pass
[ "def", "body", "(", "self", ",", "master", ")", ":", "pass" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/lib-tk/tkSimpleDialog.py#L96-L103
vivisect/vivisect
37b0b655d8dedfcf322e86b0f144b096e48d547e
vtrace/breakpoints.py
python
Breakpoint.notify
(self, event, trace)
Breakpoints may also extend and implement "notify" which will be called whenever they are hit. If you want to continue the ability for this breakpoint to have bpcode, you must call this method from your override.
Breakpoints may also extend and implement "notify" which will be called whenever they are hit. If you want to continue the ability for this breakpoint to have bpcode, you must call this method from your override.
[ "Breakpoints", "may", "also", "extend", "and", "implement", "notify", "which", "will", "be", "called", "whenever", "they", "are", "hit", ".", "If", "you", "want", "to", "continue", "the", "ability", "for", "this", "breakpoint", "to", "have", "bpcode", "you",...
def notify(self, event, trace): """ Breakpoints may also extend and implement "notify" which will be called whenever they are hit. If you want to continue the ability for this breakpoint to have bpcode, you must call this method from your override. """ if self.bpcode is not None: cobj = Breakpoint.bpcodeobj.get(self.id, None) if cobj is None: fname = "BP:%d (0x%.8x)" % (self.id, self.address) cobj = compile(self.bpcode, fname, "exec") Breakpoint.bpcodeobj[self.id] = cobj d = vtrace.VtraceExpressionLocals(trace) d['bp'] = self exec(cobj, None, d)
[ "def", "notify", "(", "self", ",", "event", ",", "trace", ")", ":", "if", "self", ".", "bpcode", "is", "not", "None", ":", "cobj", "=", "Breakpoint", ".", "bpcodeobj", ".", "get", "(", "self", ".", "id", ",", "None", ")", "if", "cobj", "is", "Non...
https://github.com/vivisect/vivisect/blob/37b0b655d8dedfcf322e86b0f144b096e48d547e/vtrace/breakpoints.py#L141-L157
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/djangoapps/content_libraries/auth.py
python
LtiAuthenticationBackend.authenticate
(self, request, iss=None, aud=None, sub=None, **kwargs)
return None
Authenticate if the user in the request has an LTI profile.
Authenticate if the user in the request has an LTI profile.
[ "Authenticate", "if", "the", "user", "in", "the", "request", "has", "an", "LTI", "profile", "." ]
def authenticate(self, request, iss=None, aud=None, sub=None, **kwargs): """ Authenticate if the user in the request has an LTI profile. """ log.info('LTI 1.3 authentication: iss=%s, sub=%s', iss, sub) try: lti_profile = LtiProfile.objects.get_from_claims( iss=iss, aud=aud, sub=sub) except LtiProfile.DoesNotExist: return None user = lti_profile.user log.info('LTI 1.3 authentication profile: profile=%s user=%s', lti_profile, user) if user and self.user_can_authenticate(user): return user return None
[ "def", "authenticate", "(", "self", ",", "request", ",", "iss", "=", "None", ",", "aud", "=", "None", ",", "sub", "=", "None", ",", "*", "*", "kwargs", ")", ":", "log", ".", "info", "(", "'LTI 1.3 authentication: iss=%s, sub=%s'", ",", "iss", ",", "sub...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/djangoapps/content_libraries/auth.py#L28-L43
IntelLabs/nlp-architect
60afd0dd1bfd74f01b4ac8f613cb484777b80284
nlp_architect/data/sequential_tagging.py
python
SequentialTaggingDataset.char_vocab
(self)
return self.vocabs["char"]
characters vocabulary
characters vocabulary
[ "characters", "vocabulary" ]
def char_vocab(self): """characters vocabulary""" return self.vocabs["char"]
[ "def", "char_vocab", "(", "self", ")", ":", "return", "self", ".", "vocabs", "[", "\"char\"", "]" ]
https://github.com/IntelLabs/nlp-architect/blob/60afd0dd1bfd74f01b4ac8f613cb484777b80284/nlp_architect/data/sequential_tagging.py#L98-L100
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/datasets/retina.py
python
RetinaCodingViewConverter.design_mat_to_topo_view
(self, X)
return self.decoder.perform(X)
.. todo:: WRITEME
.. todo::
[ "..", "todo", "::" ]
def design_mat_to_topo_view(self, X): """ .. todo:: WRITEME """ return self.decoder.perform(X)
[ "def", "design_mat_to_topo_view", "(", "self", ",", "X", ")", ":", "return", "self", ".", "decoder", ".", "perform", "(", "X", ")" ]
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/datasets/retina.py#L466-L472
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/contextlib.py
python
AbstractContextManager.__exit__
(self, exc_type, exc_value, traceback)
return None
Raise any exception triggered within the runtime context.
Raise any exception triggered within the runtime context.
[ "Raise", "any", "exception", "triggered", "within", "the", "runtime", "context", "." ]
def __exit__(self, exc_type, exc_value, traceback): """Raise any exception triggered within the runtime context.""" return None
[ "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_value", ",", "traceback", ")", ":", "return", "None" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/contextlib.py#L23-L25
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/models/research/autoencoders.py
python
autoencoder_discrete_pong_range
(rhp)
Narrow tuning grid.
Narrow tuning grid.
[ "Narrow", "tuning", "grid", "." ]
def autoencoder_discrete_pong_range(rhp): """Narrow tuning grid.""" rhp.set_float("dropout", 0.0, 0.2) rhp.set_discrete("max_hidden_size", [1024, 2048])
[ "def", "autoencoder_discrete_pong_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.0", ",", "0.2", ")", "rhp", ".", "set_discrete", "(", "\"max_hidden_size\"", ",", "[", "1024", ",", "2048", "]", ")" ]
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/research/autoencoders.py#L1315-L1318
dragonfly/dragonfly
a579b5eadf452e23b07d4caf27b402703b0012b7
dragonfly/utils/graph_utils.py
python
apsp_dijkstra
(A)
return np.array(vertex_dists)
Runs Dijkstra's on all nodes to compute the all pairs shortest paths.
Runs Dijkstra's on all nodes to compute the all pairs shortest paths.
[ "Runs", "Dijkstra", "s", "on", "all", "nodes", "to", "compute", "the", "all", "pairs", "shortest", "paths", "." ]
def apsp_dijkstra(A): """ Runs Dijkstra's on all nodes to compute the all pairs shortest paths. """ vertex_dists = [] for vertex in range(A.shape[0]): curr_vertex_dists = dijkstra(A, vertex) vertex_dists.append(curr_vertex_dists) return np.array(vertex_dists)
[ "def", "apsp_dijkstra", "(", "A", ")", ":", "vertex_dists", "=", "[", "]", "for", "vertex", "in", "range", "(", "A", ".", "shape", "[", "0", "]", ")", ":", "curr_vertex_dists", "=", "dijkstra", "(", "A", ",", "vertex", ")", "vertex_dists", ".", "appe...
https://github.com/dragonfly/dragonfly/blob/a579b5eadf452e23b07d4caf27b402703b0012b7/dragonfly/utils/graph_utils.py#L122-L128
google/python-fire
ed44d8b801fc24e40729abef11b2dcbf6588d361
fire/console/console_pager.py
python
Pager._Help
(self)
Print command help and wait for any character to continue.
Print command help and wait for any character to continue.
[ "Print", "command", "help", "and", "wait", "for", "any", "character", "to", "continue", "." ]
def _Help(self): """Print command help and wait for any character to continue.""" clear = self._height - (len(self.HELP_TEXT) - len(self.HELP_TEXT.replace('\n', ''))) if clear > 0: self._Write('\n' * clear) self._Write(self.HELP_TEXT) self._attr.GetRawKey() self._Write('\n')
[ "def", "_Help", "(", "self", ")", ":", "clear", "=", "self", ".", "_height", "-", "(", "len", "(", "self", ".", "HELP_TEXT", ")", "-", "len", "(", "self", ".", "HELP_TEXT", ".", "replace", "(", "'\\n'", ",", "''", ")", ")", ")", "if", "clear", ...
https://github.com/google/python-fire/blob/ed44d8b801fc24e40729abef11b2dcbf6588d361/fire/console/console_pager.py#L159-L167
Abjad/abjad
d0646dfbe83db3dc5ab268f76a0950712b87b7fd
abjad/score.py
python
Container.__delitem__
(self, i)
r""" Deletes components(s) at index ``i`` in container. .. container:: example Deletes first tuplet in voice: >>> voice = abjad.Voice() >>> voice.append(abjad.Tuplet((4, 6), "c'4 d'4 e'4")) >>> voice.append(abjad.Tuplet((2, 3), "e'4 d'4 c'4")) >>> leaves = abjad.select(voice).leaves() >>> abjad.slur(leaves) >>> abjad.show(voice) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(voice) >>> print(string) \new Voice { \times 4/6 { c'4 ( d'4 e'4 } \times 2/3 { e'4 d'4 c'4 ) } } >>> tuplet_1 = voice[0] >>> del(voice[0]) >>> start_slur = abjad.StartSlur() >>> leaf = abjad.select(voice).leaf(0) >>> abjad.attach(start_slur, leaf) First tuplet no longer appears in voice: >>> abjad.show(voice) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(voice) >>> print(string) \new Voice { \times 2/3 { e'4 ( d'4 c'4 ) } } >>> abjad.wf.wellformed(voice) True First tuplet must have start slur removed: >>> abjad.detach(abjad.StartSlur, tuplet_1[0]) (StartSlur(),) >>> abjad.show(tuplet_1) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(tuplet_1) >>> print(string) \times 4/6 { c'4 d'4 e'4 } >>> abjad.wf.wellformed(tuplet_1) True Returns none.
r""" Deletes components(s) at index ``i`` in container.
[ "r", "Deletes", "components", "(", "s", ")", "at", "index", "i", "in", "container", "." ]
def __delitem__(self, i): r""" Deletes components(s) at index ``i`` in container. .. container:: example Deletes first tuplet in voice: >>> voice = abjad.Voice() >>> voice.append(abjad.Tuplet((4, 6), "c'4 d'4 e'4")) >>> voice.append(abjad.Tuplet((2, 3), "e'4 d'4 c'4")) >>> leaves = abjad.select(voice).leaves() >>> abjad.slur(leaves) >>> abjad.show(voice) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(voice) >>> print(string) \new Voice { \times 4/6 { c'4 ( d'4 e'4 } \times 2/3 { e'4 d'4 c'4 ) } } >>> tuplet_1 = voice[0] >>> del(voice[0]) >>> start_slur = abjad.StartSlur() >>> leaf = abjad.select(voice).leaf(0) >>> abjad.attach(start_slur, leaf) First tuplet no longer appears in voice: >>> abjad.show(voice) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(voice) >>> print(string) \new Voice { \times 2/3 { e'4 ( d'4 c'4 ) } } >>> abjad.wf.wellformed(voice) True First tuplet must have start slur removed: >>> abjad.detach(abjad.StartSlur, tuplet_1[0]) (StartSlur(),) >>> abjad.show(tuplet_1) # doctest: +SKIP .. docs:: >>> string = abjad.lilypond(tuplet_1) >>> print(string) \times 4/6 { c'4 d'4 e'4 } >>> abjad.wf.wellformed(tuplet_1) True Returns none. """ result = self[i] if isinstance(result, Component): result._set_parent(None) return for component in result: component._set_parent(None)
[ "def", "__delitem__", "(", "self", ",", "i", ")", ":", "result", "=", "self", "[", "i", "]", "if", "isinstance", "(", "result", ",", "Component", ")", ":", "result", ".", "_set_parent", "(", "None", ")", "return", "for", "component", "in", "result", ...
https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/score.py#L956-L1050
brainiak/brainiak
ee093597c6c11597b0a59e95b48d2118e40394a5
brainiak/hyperparamopt/hpo.py
python
gmm_1d_distribution.__call__
(self, x)
Return the GMM likelihood for given point(s). See :eq:`gmm-likelihood`. Arguments --------- x : scalar (or) 1D array of reals Point(s) at which likelihood needs to be computed Returns ------- scalar (or) 1D array Likelihood values at the given point(s)
Return the GMM likelihood for given point(s).
[ "Return", "the", "GMM", "likelihood", "for", "given", "point", "(", "s", ")", "." ]
def __call__(self, x): """Return the GMM likelihood for given point(s). See :eq:`gmm-likelihood`. Arguments --------- x : scalar (or) 1D array of reals Point(s) at which likelihood needs to be computed Returns ------- scalar (or) 1D array Likelihood values at the given point(s) """ if np.isscalar(x): return self.get_gmm_pdf(x) else: return np.array([self.get_gmm_pdf(t) for t in x])
[ "def", "__call__", "(", "self", ",", "x", ")", ":", "if", "np", ".", "isscalar", "(", "x", ")", ":", "return", "self", ".", "get_gmm_pdf", "(", "x", ")", "else", ":", "return", "np", ".", "array", "(", "[", "self", ".", "get_gmm_pdf", "(", "t", ...
https://github.com/brainiak/brainiak/blob/ee093597c6c11597b0a59e95b48d2118e40394a5/brainiak/hyperparamopt/hpo.py#L160-L179
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/google_ads_service/client.py
python
GoogleAdsServiceClient.gender_view_path
( customer_id: str, ad_group_id: str, criterion_id: str, )
return "customers/{customer_id}/genderViews/{ad_group_id}~{criterion_id}".format( customer_id=customer_id, ad_group_id=ad_group_id, criterion_id=criterion_id, )
Return a fully-qualified gender_view string.
Return a fully-qualified gender_view string.
[ "Return", "a", "fully", "-", "qualified", "gender_view", "string", "." ]
def gender_view_path( customer_id: str, ad_group_id: str, criterion_id: str, ) -> str: """Return a fully-qualified gender_view string.""" return "customers/{customer_id}/genderViews/{ad_group_id}~{criterion_id}".format( customer_id=customer_id, ad_group_id=ad_group_id, criterion_id=criterion_id, )
[ "def", "gender_view_path", "(", "customer_id", ":", "str", ",", "ad_group_id", ":", "str", ",", "criterion_id", ":", "str", ",", ")", "->", "str", ":", "return", "\"customers/{customer_id}/genderViews/{ad_group_id}~{criterion_id}\"", ".", "format", "(", "customer_id",...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/google_ads_service/client.py#L1627-L1635
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/zmq/auth/base.py
python
Authenticator._send_zap_reply
(self, request_id, status_code, status_text, user_id='user')
Send a ZAP reply to finish the authentication.
Send a ZAP reply to finish the authentication.
[ "Send", "a", "ZAP", "reply", "to", "finish", "the", "authentication", "." ]
def _send_zap_reply(self, request_id, status_code, status_text, user_id='user'): """Send a ZAP reply to finish the authentication.""" user_id = user_id if status_code == b'200' else b'' if isinstance(user_id, unicode): user_id = user_id.encode(self.encoding, 'replace') metadata = b'' # not currently used self.log.debug("ZAP reply code=%s text=%s", status_code, status_text) reply = [VERSION, request_id, status_code, status_text, user_id, metadata] self.zap_socket.send_multipart(reply)
[ "def", "_send_zap_reply", "(", "self", ",", "request_id", ",", "status_code", ",", "status_text", ",", "user_id", "=", "'user'", ")", ":", "user_id", "=", "user_id", "if", "status_code", "==", "b'200'", "else", "b''", "if", "isinstance", "(", "user_id", ",",...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/zmq/auth/base.py#L262-L270
fizyr/keras-maskrcnn
5c4b3610775d2a32beb9ed9c0d04eb6b16b114f2
keras_maskrcnn/preprocessing/generator.py
python
Generator.preprocess_group_entry
(self, image, annotations)
return image, annotations
Preprocess image and its annotations.
Preprocess image and its annotations.
[ "Preprocess", "image", "and", "its", "annotations", "." ]
def preprocess_group_entry(self, image, annotations): """ Preprocess image and its annotations. """ # preprocess the image image = self.preprocess_image(image) # randomly transform image and annotations image, annotations = self.random_transform_group_entry(image, annotations) # resize image image, image_scale = self.resize_image(image) # resize masks for i in range(len(annotations['masks'])): annotations['masks'][i], _ = self.resize_image(annotations['masks'][i]) # apply resizing to annotations too annotations['bboxes'] *= image_scale # convert to the wanted keras floatx image = keras.backend.cast_to_floatx(image) return image, annotations
[ "def", "preprocess_group_entry", "(", "self", ",", "image", ",", "annotations", ")", ":", "# preprocess the image", "image", "=", "self", ".", "preprocess_image", "(", "image", ")", "# randomly transform image and annotations", "image", ",", "annotations", "=", "self"...
https://github.com/fizyr/keras-maskrcnn/blob/5c4b3610775d2a32beb9ed9c0d04eb6b16b114f2/keras_maskrcnn/preprocessing/generator.py#L162-L184
504ensicsLabs/DAMM
60e7ec7dacd6087cd6320b3615becca9b4cf9b24
volatility/dwarf.py
python
DWARFParser.resolve
(self, memb)
Lookup anonymous member and replace it with a well known one.
Lookup anonymous member and replace it with a well known one.
[ "Lookup", "anonymous", "member", "and", "replace", "it", "with", "a", "well", "known", "one", "." ]
def resolve(self, memb): """Lookup anonymous member and replace it with a well known one.""" # Reference to another type if isinstance(memb, str) and memb.startswith('<'): if memb[1:3] == "0x": memb = "<0x" + memb[3:].lstrip('0') resolved = self.id_to_name[memb[1:]] return self.resolve(resolved) elif isinstance(memb, list): return [self.resolve(r) for r in memb] else: # Literal return memb
[ "def", "resolve", "(", "self", ",", "memb", ")", ":", "# Reference to another type", "if", "isinstance", "(", "memb", ",", "str", ")", "and", "memb", ".", "startswith", "(", "'<'", ")", ":", "if", "memb", "[", "1", ":", "3", "]", "==", "\"0x\"", ":",...
https://github.com/504ensicsLabs/DAMM/blob/60e7ec7dacd6087cd6320b3615becca9b4cf9b24/volatility/dwarf.py#L73-L88
NTMC-Community/MatchZoo
8a487ee5a574356fc91e4f48e219253dc11bcff2
matchzoo/layers/matching_layer.py
python
MatchingLayer.call
(self, inputs: list, **kwargs)
The computation logic of MatchingLayer. :param inputs: two input tensors.
The computation logic of MatchingLayer.
[ "The", "computation", "logic", "of", "MatchingLayer", "." ]
def call(self, inputs: list, **kwargs) -> typing.Any: """ The computation logic of MatchingLayer. :param inputs: two input tensors. """ x1 = inputs[0] x2 = inputs[1] if self._matching_type == 'dot': if self._normalize: x1 = tf.math.l2_normalize(x1, axis=2) x2 = tf.math.l2_normalize(x2, axis=2) return tf.expand_dims(tf.einsum('abd,acd->abc', x1, x2), 3) else: if self._matching_type == 'mul': def func(x, y): return x * y elif self._matching_type == 'plus': def func(x, y): return x + y elif self._matching_type == 'minus': def func(x, y): return x - y elif self._matching_type == 'concat': def func(x, y): return tf.concat([x, y], axis=3) else: raise ValueError(f"Invalid matching type." f"{self._matching_type} received." f"Mut be in `dot`, `mul`, `plus`, " f"`minus` and `concat`.") x1_exp = tf.stack([x1] * self._shape2[1], 2) x2_exp = tf.stack([x2] * self._shape1[1], 1) return func(x1_exp, x2_exp)
[ "def", "call", "(", "self", ",", "inputs", ":", "list", ",", "*", "*", "kwargs", ")", "->", "typing", ".", "Any", ":", "x1", "=", "inputs", "[", "0", "]", "x2", "=", "inputs", "[", "1", "]", "if", "self", ".", "_matching_type", "==", "'dot'", "...
https://github.com/NTMC-Community/MatchZoo/blob/8a487ee5a574356fc91e4f48e219253dc11bcff2/matchzoo/layers/matching_layer.py#L67-L100
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3model.py
python
S3Model.model
(self)
return None
Defines all tables in this model, to be implemented by subclasses
Defines all tables in this model, to be implemented by subclasses
[ "Defines", "all", "tables", "in", "this", "model", "to", "be", "implemented", "by", "subclasses" ]
def model(self): """ Defines all tables in this model, to be implemented by subclasses """ return None
[ "def", "model", "(", "self", ")", ":", "return", "None" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3model.py#L196-L201
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/mail/imap4.py
python
IMAP4Client.registerAuthenticator
(self, auth)
Register a new form of authentication When invoking the authenticate() method of IMAP4Client, the first matching authentication scheme found will be used. The ordering is that in which the server lists support authentication schemes. @type auth: Implementor of C{IClientAuthentication} @param auth: The object to use to perform the client side of this authentication scheme.
Register a new form of authentication
[ "Register", "a", "new", "form", "of", "authentication" ]
def registerAuthenticator(self, auth): """Register a new form of authentication When invoking the authenticate() method of IMAP4Client, the first matching authentication scheme found will be used. The ordering is that in which the server lists support authentication schemes. @type auth: Implementor of C{IClientAuthentication} @param auth: The object to use to perform the client side of this authentication scheme. """ self.authenticators[auth.getName().upper()] = auth
[ "def", "registerAuthenticator", "(", "self", ",", "auth", ")", ":", "self", ".", "authenticators", "[", "auth", ".", "getName", "(", ")", ".", "upper", "(", ")", "]", "=", "auth" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/mail/imap4.py#L2248-L2259
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/images/__init__.py
python
vertical_flip_async
(image_data, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None)
return image.execute_transforms_async(output_encoding=output_encoding, quality=quality, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb)
Flip the image vertically - async version. Args: image_data: str, source image data. output_encoding: a value from OUTPUT_ENCODING_TYPES. quality: A value between 1 and 100 to specify the quality of the encoding. This value is only used for JPEG quality control. correct_orientation: one of ORIENTATION_CORRECTION_TYPE, to indicate if orientation correction should be performed during the transformation. rpc: An Optional UserRPC object transparent_substition_rgb: When transparent pixels are not support in the destination image format then transparent pixels will be substituted for the specified color, which must be 32 bit rgb format. Returns: A UserRPC object, call get_result to complete the RPC and obtain the crop result. Raises: Error when something went wrong with the call. See Image.ExecuteTransforms for more details.
Flip the image vertically - async version.
[ "Flip", "the", "image", "vertically", "-", "async", "version", "." ]
def vertical_flip_async(image_data, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): """Flip the image vertically - async version. Args: image_data: str, source image data. output_encoding: a value from OUTPUT_ENCODING_TYPES. quality: A value between 1 and 100 to specify the quality of the encoding. This value is only used for JPEG quality control. correct_orientation: one of ORIENTATION_CORRECTION_TYPE, to indicate if orientation correction should be performed during the transformation. rpc: An Optional UserRPC object transparent_substition_rgb: When transparent pixels are not support in the destination image format then transparent pixels will be substituted for the specified color, which must be 32 bit rgb format. Returns: A UserRPC object, call get_result to complete the RPC and obtain the crop result. Raises: Error when something went wrong with the call. See Image.ExecuteTransforms for more details. """ image = Image(image_data) image.vertical_flip() image.set_correct_orientation(correct_orientation) return image.execute_transforms_async(output_encoding=output_encoding, quality=quality, rpc=rpc, transparent_substitution_rgb=transparent_substitution_rgb)
[ "def", "vertical_flip_async", "(", "image_data", ",", "output_encoding", "=", "PNG", ",", "quality", "=", "None", ",", "correct_orientation", "=", "UNCHANGED_ORIENTATION", ",", "rpc", "=", "None", ",", "transparent_substitution_rgb", "=", "None", ")", ":", "image"...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/images/__init__.py#L1324-L1355
datamllab/rlcard
c21ea82519c453a42e3bdc6848bd3356e9b6ac43
rlcard/games/nolimitholdem/game.py
python
NolimitholdemGame.step
(self, action)
return state, self.game_pointer
Get the next state Args: action (str): a specific action. (call, raise, fold, or check) Returns: (tuple): Tuple containing: (dict): next player's state (int): next player id
Get the next state
[ "Get", "the", "next", "state" ]
def step(self, action): """ Get the next state Args: action (str): a specific action. (call, raise, fold, or check) Returns: (tuple): Tuple containing: (dict): next player's state (int): next player id """ if action not in self.get_legal_actions(): print(action, self.get_legal_actions()) print(self.get_state(self.game_pointer)) raise Exception('Action not allowed') if self.allow_step_back: # First snapshot the current state r = deepcopy(self.round) b = self.game_pointer r_c = self.round_counter d = deepcopy(self.dealer) p = deepcopy(self.public_cards) ps = deepcopy(self.players) self.history.append((r, b, r_c, d, p, ps)) # Then we proceed to the next round self.game_pointer = self.round.proceed_round(self.players, action) players_in_bypass = [1 if player.status in (PlayerStatus.FOLDED, PlayerStatus.ALLIN) else 0 for player in self.players] if self.num_players - sum(players_in_bypass) == 1: last_player = players_in_bypass.index(0) if self.round.raised[last_player] >= max(self.round.raised): # If the last player has put enough chips, he is also bypassed players_in_bypass[last_player] = 1 # If a round is over, we deal more public cards if self.round.is_over(): # Game pointer goes to the first player not in bypass after the dealer, if there is one self.game_pointer = (self.dealer_id + 1) % self.num_players if sum(players_in_bypass) < self.num_players: while players_in_bypass[self.game_pointer]: self.game_pointer = (self.game_pointer + 1) % self.num_players # For the first round, we deal 3 cards if self.round_counter == 0: self.stage = Stage.FLOP self.public_cards.append(self.dealer.deal_card()) self.public_cards.append(self.dealer.deal_card()) self.public_cards.append(self.dealer.deal_card()) if len(self.players) == np.sum(players_in_bypass): self.round_counter += 1 # For the following rounds, we deal only 1 card if self.round_counter == 1: self.stage = Stage.TURN self.public_cards.append(self.dealer.deal_card()) if len(self.players) == np.sum(players_in_bypass): self.round_counter += 1 if self.round_counter == 2: self.stage = Stage.RIVER self.public_cards.append(self.dealer.deal_card()) if len(self.players) == np.sum(players_in_bypass): self.round_counter += 1 self.round_counter += 1 self.round.start_new_round(self.game_pointer) state = self.get_state(self.game_pointer) return state, self.game_pointer
[ "def", "step", "(", "self", ",", "action", ")", ":", "if", "action", "not", "in", "self", ".", "get_legal_actions", "(", ")", ":", "print", "(", "action", ",", "self", ".", "get_legal_actions", "(", ")", ")", "print", "(", "self", ".", "get_state", "...
https://github.com/datamllab/rlcard/blob/c21ea82519c453a42e3bdc6848bd3356e9b6ac43/rlcard/games/nolimitholdem/game.py#L116-L188
jobovy/galpy
8e6a230bbe24ce16938db10053f92eb17fe4bb52
galpy/actionAngle/actionAngleInverse.py
python
actionAngleInverse.__call__
(self,*args,**kwargs)
NAME: evaluate the phase-space coordinates (x,v) for a number of angles on a single torus INPUT: jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) angler - radial angle (array [N]) anglephi - azimuthal angle (array [N]) anglez - vertical angle (array [N]) Some sub-classes (like actionAngleTorus) have additional parameters: actionAngleTorus: tol= (object-wide value) goal for |dJ|/|J| along the torus OUTPUT: [R,vR,vT,z,vz,phi] HISTORY: 2017-11-14 - Written - Bovy (UofT)
NAME:
[ "NAME", ":" ]
def __call__(self,*args,**kwargs): """ NAME: evaluate the phase-space coordinates (x,v) for a number of angles on a single torus INPUT: jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) angler - radial angle (array [N]) anglephi - azimuthal angle (array [N]) anglez - vertical angle (array [N]) Some sub-classes (like actionAngleTorus) have additional parameters: actionAngleTorus: tol= (object-wide value) goal for |dJ|/|J| along the torus OUTPUT: [R,vR,vT,z,vz,phi] HISTORY: 2017-11-14 - Written - Bovy (UofT) """ try: return self._evaluate(*args,**kwargs) except AttributeError: #pragma: no cover raise NotImplementedError("'__call__' method not implemented for this actionAngle module")
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "_evaluate", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "AttributeError", ":", "#pragma: no cover", "raise", "NotImpl...
https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/actionAngle/actionAngleInverse.py#L16-L54
panchunguang/ccks_baidu_entity_link
f6eb5298620b460f2f1222a3b182d15c938c4ea2
code/entity_vec_extract.py
python
extract
(max_len=512)
:param max_len: 文本最大长度 :return: 字典形式,key: kb_id value: kb_id对应描述文本形成的向量
:param max_len: 文本最大长度 :return: 字典形式,key: kb_id value: kb_id对应描述文本形成的向量
[ ":", "param", "max_len", ":", "文本最大长度", ":", "return", ":", "字典形式,key", ":", "kb_id", "value", ":", "kb_id对应描述文本形成的向量" ]
def extract(max_len=512): ''' :param max_len: 文本最大长度 :return: 字典形式,key: kb_id value: kb_id对应描述文本形成的向量 ''' model = get_model(max_len) token_dict = get_token_dict() tokenizer = Tokenizer(token_dict) id_text=pd.read_pickle('data/id_text.pkl') id_embedding={} for id in id_text: if int(id)%10000==0: print(id) text=id_text[id] indices, segments = tokenizer.encode(first=text,max_len=512) predicts = model.predict([[indices], [segments]], verbose=2) id_embedding[id]=predicts[0] pd.to_pickle(id_embedding,'data/id_embedding.pkl')
[ "def", "extract", "(", "max_len", "=", "512", ")", ":", "model", "=", "get_model", "(", "max_len", ")", "token_dict", "=", "get_token_dict", "(", ")", "tokenizer", "=", "Tokenizer", "(", "token_dict", ")", "id_text", "=", "pd", ".", "read_pickle", "(", "...
https://github.com/panchunguang/ccks_baidu_entity_link/blob/f6eb5298620b460f2f1222a3b182d15c938c4ea2/code/entity_vec_extract.py#L30-L47
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/colorama/ansi.py
python
clear_line
(mode=2)
return CSI + str(mode) + 'K'
[]
def clear_line(mode=2): return CSI + str(mode) + 'K'
[ "def", "clear_line", "(", "mode", "=", "2", ")", ":", "return", "CSI", "+", "str", "(", "mode", ")", "+", "'K'" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/colorama/ansi.py#L21-L22
bowenbaker/metaqnn
a25847f635e9545455f83405453e740646038f7a
libs/misc/clear_trained_models.py
python
clear_redundant_logs_caffe
(ckpt_dir, replay)
Deletes uneeded log files and model saves: args: replay - with standard replay dic columns. Deletes only model saves that aren't for the first iteration, the best iteration, and the last iteration ckpt_dir - where the models are saved, it must have a filemap
Deletes uneeded log files and model saves: args: replay - with standard replay dic columns. Deletes only model saves that aren't for the first iteration, the best iteration, and the last iteration ckpt_dir - where the models are saved, it must have a filemap
[ "Deletes", "uneeded", "log", "files", "and", "model", "saves", ":", "args", ":", "replay", "-", "with", "standard", "replay", "dic", "columns", ".", "Deletes", "only", "model", "saves", "that", "aren", "t", "for", "the", "first", "iteration", "the", "best"...
def clear_redundant_logs_caffe(ckpt_dir, replay): ''' Deletes uneeded log files and model saves: args: replay - with standard replay dic columns. Deletes only model saves that aren't for the first iteration, the best iteration, and the last iteration ckpt_dir - where the models are saved, it must have a filemap ''' file_map = pd.read_csv(os.path.join(ckpt_dir, 'file_map.csv')) for i in range(len(file_map)): net = file_map.net.values[i] # First check that the model was run on this computer if net not in replay.net.values: continue else: folder_path = os.path.join(ckpt_dir, str(int(file_map[file_map.net == net].file_number.values[0]))) if not os.path.isdir(folder_path): continue best_iter = replay[replay.net == net].iter_best_val.values[0] last_iter = replay[replay.net == net].iter_last_val.values[0] model_saves = [f for f in os.listdir(folder_path) if f.find('modelsave_iter') >= 0] #make sure that the model actual ran if not model_saves: continue first_iter = min([int(re.split('_|\.', f)[2]) for f in model_saves]) model_saves_to_keep = ['modelsave_iter_%i.solverstate' % iteration for iteration in [best_iter, last_iter, first_iter]] + \ ['modelsave_iter_%i.caffemodel' % iteration for iteration in [best_iter, last_iter, first_iter]] # make sure all of the files are there if not np.all([os.path.isfile(os.path.join(folder_path, savefile)) for savefile in model_saves_to_keep]): continue # Delete extraneous files for f in model_saves: if f not in model_saves_to_keep: os.remove(os.path.join(folder_path, f))
[ "def", "clear_redundant_logs_caffe", "(", "ckpt_dir", ",", "replay", ")", ":", "file_map", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "ckpt_dir", ",", "'file_map.csv'", ")", ")", "for", "i", "in", "range", "(", "len", "(", "f...
https://github.com/bowenbaker/metaqnn/blob/a25847f635e9545455f83405453e740646038f7a/libs/misc/clear_trained_models.py#L8-L45
JosephLai241/URS
9f8cf3a3adb9aa5079dfc7bfd7832b53358ee40f
urs/utils/Tools.py
python
Run.__init__
(self, reddit)
Initialize variables used in instance methods: self._reddit: Reddit instance self._args: argparse Namespace object self._parser: argparse ArgumentParser object Calls a private method: self._introduce_then_args() Parameters ---------- reddit: PRAW Reddit object Returns ------- None
Initialize variables used in instance methods:
[ "Initialize", "variables", "used", "in", "instance", "methods", ":" ]
def __init__(self, reddit): """ Initialize variables used in instance methods: self._reddit: Reddit instance self._args: argparse Namespace object self._parser: argparse ArgumentParser object Calls a private method: self._introduce_then_args() Parameters ---------- reddit: PRAW Reddit object Returns ------- None """ self._reddit = reddit self._args, self._parser = self._introduce_then_args()
[ "def", "__init__", "(", "self", ",", "reddit", ")", ":", "self", ".", "_reddit", "=", "reddit", "self", ".", "_args", ",", "self", ".", "_parser", "=", "self", ".", "_introduce_then_args", "(", ")" ]
https://github.com/JosephLai241/URS/blob/9f8cf3a3adb9aa5079dfc7bfd7832b53358ee40f/urs/utils/Tools.py#L34-L56
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/string.py
python
Template.__init__
(self, template)
[]
def __init__(self, template): self.template = template
[ "def", "__init__", "(", "self", ",", "template", ")", ":", "self", ".", "template", "=", "template" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/string.py#L80-L81
awesto/django-shop
13d9a77aff7eede74a5f363c1d540e005d88dbcd
shop/models/customer.py
python
CustomerManager.create
(self, *args, **kwargs)
return customer
[]
def create(self, *args, **kwargs): if 'user' in kwargs and kwargs['user'].is_authenticated: kwargs.setdefault('recognized', CustomerState.REGISTERED) customer = super().create(*args, **kwargs) return customer
[ "def", "create", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'user'", "in", "kwargs", "and", "kwargs", "[", "'user'", "]", ".", "is_authenticated", ":", "kwargs", ".", "setdefault", "(", "'recognized'", ",", "CustomerState", ...
https://github.com/awesto/django-shop/blob/13d9a77aff7eede74a5f363c1d540e005d88dbcd/shop/models/customer.py#L114-L118
hasegaw/IkaLog
bd476da541fcc296f792d4db76a6b9174c4777ad
ikalog/scenes/game/ranked_battle_events.py
python
GameRankedBattleEvents.on_game_start
(self, context)
[]
def on_game_start(self, context): rule_id = context['game']['rule'] masks_active = self._masks_ranked.copy() if rule_id == 'area': masks_active.update(self._masks_splatzone) elif rule_id == 'hoko': masks_active.update(self._masks_rainmaker) elif rule_id == 'yagura': masks_active.update(self._masks_towercontrol) else: masks_active = {} self._masks_active = masks_active # Initialize Multi-Class IkaMatcher self._masks_active2 = MultiClassIkaMatcher() for mask in masks_active.keys(): self._masks_active2.add_mask(mask)
[ "def", "on_game_start", "(", "self", ",", "context", ")", ":", "rule_id", "=", "context", "[", "'game'", "]", "[", "'rule'", "]", "masks_active", "=", "self", ".", "_masks_ranked", ".", "copy", "(", ")", "if", "rule_id", "==", "'area'", ":", "masks_activ...
https://github.com/hasegaw/IkaLog/blob/bd476da541fcc296f792d4db76a6b9174c4777ad/ikalog/scenes/game/ranked_battle_events.py#L45-L65
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/metagoofil/hachoir_parser/image/tiff.py
python
TiffFile.validate
(self)
return True
[]
def validate(self): endian = self.stream.readBytes(0, 2) if endian not in ("MM", "II"): return "Invalid endian (%r)" % endian if self["version"].value != 42: return "Unknown TIFF version" return True
[ "def", "validate", "(", "self", ")", ":", "endian", "=", "self", ".", "stream", ".", "readBytes", "(", "0", ",", "2", ")", "if", "endian", "not", "in", "(", "\"MM\"", ",", "\"II\"", ")", ":", "return", "\"Invalid endian (%r)\"", "%", "endian", "if", ...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_parser/image/tiff.py#L185-L191
cleverhans-lab/cleverhans
e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d
cleverhans/tf2/attacks/carlini_wagner_l2.py
python
CarliniWagnerL2.__init__
( self, model_fn, y=None, targeted=False, batch_size=128, clip_min=0.0, clip_max=1.0, binary_search_steps=5, max_iterations=1_000, abort_early=True, confidence=0.0, initial_const=1e-2, learning_rate=5e-3, )
This attack was originally proposed by Carlini and Wagner. It is an iterative attack that finds adversarial examples on many defenses that are robust to other attacks. Paper link: https://arxiv.org/abs/1608.04644 At a high level, this attack is an iterative attack using Adam and a specially-chosen loss function to find adversarial examples with lower distortion than other attacks. This comes at the cost of speed, as this attack is often much slower than others. :param model_fn: a callable that takes an input tensor and returns the model logits. :param y: (optional) Tensor with target labels. :param targeted: (optional) Targeted attack? :param batch_size (optional): Number of attacks to run simultaneously. :param clip_min: (optional) float. Minimum float values for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param binary_search_steps (optional): The number of times we perform binary search to find the optimal tradeoff- constant between norm of the purturbation and confidence of the classification. :param max_iterations (optional): The maximum number of iterations. Setting this to a larger value will produce lower distortion results. Using only a few iterations requires a larger learning rate, and will produce larger distortion results. :param abort_early (optional): If true, allows early aborts if gradient descent is unable to make progress (i.e., gets stuck in a local minimum). :param confidence (optional): Confidence of adversarial examples: higher produces examples with larger l2 distortion, but more strongly classified as adversarial. :param initial_const (optional): The initial tradeoff-constant used to tune the relative importance of the size of the perturbation and confidence of classification. If binary_search_steps is large, the initial constant is not important. A smaller value of this constant gives lower distortion results. :param learning_rate (optional): The learning rate for the attack algorithm. Smaller values produce better results but are slower to converge.
This attack was originally proposed by Carlini and Wagner. It is an iterative attack that finds adversarial examples on many defenses that are robust to other attacks. Paper link: https://arxiv.org/abs/1608.04644 At a high level, this attack is an iterative attack using Adam and a specially-chosen loss function to find adversarial examples with lower distortion than other attacks. This comes at the cost of speed, as this attack is often much slower than others.
[ "This", "attack", "was", "originally", "proposed", "by", "Carlini", "and", "Wagner", ".", "It", "is", "an", "iterative", "attack", "that", "finds", "adversarial", "examples", "on", "many", "defenses", "that", "are", "robust", "to", "other", "attacks", ".", "...
def __init__( self, model_fn, y=None, targeted=False, batch_size=128, clip_min=0.0, clip_max=1.0, binary_search_steps=5, max_iterations=1_000, abort_early=True, confidence=0.0, initial_const=1e-2, learning_rate=5e-3, ): """ This attack was originally proposed by Carlini and Wagner. It is an iterative attack that finds adversarial examples on many defenses that are robust to other attacks. Paper link: https://arxiv.org/abs/1608.04644 At a high level, this attack is an iterative attack using Adam and a specially-chosen loss function to find adversarial examples with lower distortion than other attacks. This comes at the cost of speed, as this attack is often much slower than others. :param model_fn: a callable that takes an input tensor and returns the model logits. :param y: (optional) Tensor with target labels. :param targeted: (optional) Targeted attack? :param batch_size (optional): Number of attacks to run simultaneously. :param clip_min: (optional) float. Minimum float values for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param binary_search_steps (optional): The number of times we perform binary search to find the optimal tradeoff- constant between norm of the purturbation and confidence of the classification. :param max_iterations (optional): The maximum number of iterations. Setting this to a larger value will produce lower distortion results. Using only a few iterations requires a larger learning rate, and will produce larger distortion results. :param abort_early (optional): If true, allows early aborts if gradient descent is unable to make progress (i.e., gets stuck in a local minimum). :param confidence (optional): Confidence of adversarial examples: higher produces examples with larger l2 distortion, but more strongly classified as adversarial. :param initial_const (optional): The initial tradeoff-constant used to tune the relative importance of the size of the perturbation and confidence of classification. If binary_search_steps is large, the initial constant is not important. A smaller value of this constant gives lower distortion results. :param learning_rate (optional): The learning rate for the attack algorithm. Smaller values produce better results but are slower to converge. """ self.model_fn = model_fn self.batch_size = batch_size self.y = y self.targeted = y is not None self.clip_min = clip_min self.clip_max = clip_max self.binary_search_steps = binary_search_steps self.max_iterations = max_iterations self.abort_early = abort_early self.learning_rate = learning_rate self.confidence = confidence self.initial_const = initial_const # the optimizer self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) super(CarliniWagnerL2, self).__init__()
[ "def", "__init__", "(", "self", ",", "model_fn", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "batch_size", "=", "128", ",", "clip_min", "=", "0.0", ",", "clip_max", "=", "1.0", ",", "binary_search_steps", "=", "5", ",", "max_iterations", ...
https://github.com/cleverhans-lab/cleverhans/blob/e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d/cleverhans/tf2/attacks/carlini_wagner_l2.py#L21-L98
ProjectQ-Framework/ProjectQ
0d32c1610ba4e9aefd7f19eb52dadb4fbe5f9005
projectq/ops/_gates.py
python
TGate.__str__
(self)
return "T"
Return a string representation of the object.
Return a string representation of the object.
[ "Return", "a", "string", "representation", "of", "the", "object", "." ]
def __str__(self): """Return a string representation of the object.""" return "T"
[ "def", "__str__", "(", "self", ")", ":", "return", "\"T\"" ]
https://github.com/ProjectQ-Framework/ProjectQ/blob/0d32c1610ba4e9aefd7f19eb52dadb4fbe5f9005/projectq/ops/_gates.py#L158-L160
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/datasets/elliptic.py
python
EllipticBitcoinDataset.download
(self)
[]
def download(self): download_url('https://tinyurl.com/9b7f8efe', self.raw_dir) os.rename(osp.join(self.raw_dir, '9b7f8efe'), self.raw_paths[0]) download_url('https://tinyurl.com/mr3v9d3f', self.raw_dir) os.rename(osp.join(self.raw_dir, 'mr3v9d3f'), self.raw_paths[1]) download_url('https://tinyurl.com/2p8up25z', self.raw_dir) os.rename(osp.join(self.raw_dir, '2p8up25z'), self.raw_paths[2])
[ "def", "download", "(", "self", ")", ":", "download_url", "(", "'https://tinyurl.com/9b7f8efe'", ",", "self", ".", "raw_dir", ")", "os", ".", "rename", "(", "osp", ".", "join", "(", "self", ".", "raw_dir", ",", "'9b7f8efe'", ")", ",", "self", ".", "raw_p...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/datasets/elliptic.py#L69-L75
galaxyproject/galaxy
4c03520f05062e0f4a1b3655dc0b7452fda69943
lib/galaxy/web/framework/helpers/grids.py
python
DateTimeColumn.sort
(self, trans, query, ascending, column_name=None)
return GridColumn.sort(self, trans, query, ascending, column_name=column_name)
Sort query using this column.
Sort query using this column.
[ "Sort", "query", "using", "this", "column", "." ]
def sort(self, trans, query, ascending, column_name=None): """Sort query using this column.""" return GridColumn.sort(self, trans, query, ascending, column_name=column_name)
[ "def", "sort", "(", "self", ",", "trans", ",", "query", ",", "ascending", ",", "column_name", "=", "None", ")", ":", "return", "GridColumn", ".", "sort", "(", "self", ",", "trans", ",", "query", ",", "ascending", ",", "column_name", "=", "column_name", ...
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/galaxy/web/framework/helpers/grids.py#L143-L145
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet/nets/chainer_backend/rnn/encoders.py
python
encoder_for
(args, idim, subsample)
return Encoder( args.etype, idim, args.elayers, args.eunits, args.eprojs, subsample, args.dropout_rate, )
Return the Encoder module. Args: idim (int): Dimension of input array. subsample (numpy.array): Subsample number. egs).1_2_2_2_1 Return chainer.nn.Module: Encoder module.
Return the Encoder module.
[ "Return", "the", "Encoder", "module", "." ]
def encoder_for(args, idim, subsample): """Return the Encoder module. Args: idim (int): Dimension of input array. subsample (numpy.array): Subsample number. egs).1_2_2_2_1 Return chainer.nn.Module: Encoder module. """ return Encoder( args.etype, idim, args.elayers, args.eunits, args.eprojs, subsample, args.dropout_rate, )
[ "def", "encoder_for", "(", "args", ",", "idim", ",", "subsample", ")", ":", "return", "Encoder", "(", "args", ".", "etype", ",", "idim", ",", "args", ".", "elayers", ",", "args", ".", "eunits", ",", "args", ".", "eprojs", ",", "subsample", ",", "args...
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/nets/chainer_backend/rnn/encoders.py#L310-L329
PyTorchLightning/pytorch-lightning
5914fb748fb53d826ab337fc2484feab9883a104
pytorch_lightning/callbacks/prediction_writer.py
python
BasePredictionWriter.write_on_batch_end
( self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", prediction: Any, batch_indices: Optional[Sequence[int]], batch: Any, batch_idx: int, dataloader_idx: int, )
Override with the logic to write a single batch.
Override with the logic to write a single batch.
[ "Override", "with", "the", "logic", "to", "write", "a", "single", "batch", "." ]
def write_on_batch_end( self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", prediction: Any, batch_indices: Optional[Sequence[int]], batch: Any, batch_idx: int, dataloader_idx: int, ) -> None: """Override with the logic to write a single batch.""" raise NotImplementedError()
[ "def", "write_on_batch_end", "(", "self", ",", "trainer", ":", "\"pl.Trainer\"", ",", "pl_module", ":", "\"pl.LightningModule\"", ",", "prediction", ":", "Any", ",", "batch_indices", ":", "Optional", "[", "Sequence", "[", "int", "]", "]", ",", "batch", ":", ...
https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/callbacks/prediction_writer.py#L76-L87
pyrocko/pyrocko
b6baefb7540fb7fce6ed9b856ec0c413961a4320
src/obspy_compat/base.py
python
to_obspy_stream
(pile)
return stream
Convert Pyrocko pile to ObsPy stream. :param pile: :py:class:`pyrocko.pile.Pile` object :returns: :py:class:`obspy.Stream <obspy.core.stream.Stream>` object
Convert Pyrocko pile to ObsPy stream.
[ "Convert", "Pyrocko", "pile", "to", "ObsPy", "stream", "." ]
def to_obspy_stream(pile): ''' Convert Pyrocko pile to ObsPy stream. :param pile: :py:class:`pyrocko.pile.Pile` object :returns: :py:class:`obspy.Stream <obspy.core.stream.Stream>` object ''' pyrocko_pile = pile import obspy stream = obspy.Stream() stream.extend([to_obspy_trace(tr) for tr in pyrocko_pile.iter_all()]) return stream
[ "def", "to_obspy_stream", "(", "pile", ")", ":", "pyrocko_pile", "=", "pile", "import", "obspy", "stream", "=", "obspy", ".", "Stream", "(", ")", "stream", ".", "extend", "(", "[", "to_obspy_trace", "(", "tr", ")", "for", "tr", "in", "pyrocko_pile", ".",...
https://github.com/pyrocko/pyrocko/blob/b6baefb7540fb7fce6ed9b856ec0c413961a4320/src/obspy_compat/base.py#L150-L165
mjpost/sacrebleu
65a8a9eeccd8c0c7875e875e12edf10db33ab0ba
sacrebleu/tokenizers/tokenizer_re.py
python
TokenizerRegexp.__call__
(self, line)
return ' '.join(line.split())
Common post-processing tokenizer for `13a` and `zh` tokenizers. :param line: a segment to tokenize :return: the tokenized line
Common post-processing tokenizer for `13a` and `zh` tokenizers.
[ "Common", "post", "-", "processing", "tokenizer", "for", "13a", "and", "zh", "tokenizers", "." ]
def __call__(self, line): """Common post-processing tokenizer for `13a` and `zh` tokenizers. :param line: a segment to tokenize :return: the tokenized line """ for (_re, repl) in self._re: line = _re.sub(repl, line) # no leading or trailing spaces, single space within words return ' '.join(line.split())
[ "def", "__call__", "(", "self", ",", "line", ")", ":", "for", "(", "_re", ",", "repl", ")", "in", "self", ".", "_re", ":", "line", "=", "_re", ".", "sub", "(", "repl", ",", "line", ")", "# no leading or trailing spaces, single space within words", "return"...
https://github.com/mjpost/sacrebleu/blob/65a8a9eeccd8c0c7875e875e12edf10db33ab0ba/sacrebleu/tokenizers/tokenizer_re.py#L28-L38
SavinaRoja/PyUserInput
8a93a4e32430fd9da68590897e06e0be9a2ad26e
reference_materials/virtual_keystroke_example.py
python
press
(*args)
one press, one release. accepts as many arguments as you want. e.g. press('left_arrow', 'a','b').
one press, one release. accepts as many arguments as you want. e.g. press('left_arrow', 'a','b').
[ "one", "press", "one", "release", ".", "accepts", "as", "many", "arguments", "as", "you", "want", ".", "e", ".", "g", ".", "press", "(", "left_arrow", "a", "b", ")", "." ]
def press(*args): ''' one press, one release. accepts as many arguments as you want. e.g. press('left_arrow', 'a','b'). ''' for i in args: win32api.keybd_event(VK_CODE[i], 0,0,0) time.sleep(.05) win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)
[ "def", "press", "(", "*", "args", ")", ":", "for", "i", "in", "args", ":", "win32api", ".", "keybd_event", "(", "VK_CODE", "[", "i", "]", ",", "0", ",", "0", ",", "0", ")", "time", ".", "sleep", "(", ".05", ")", "win32api", ".", "keybd_event", ...
https://github.com/SavinaRoja/PyUserInput/blob/8a93a4e32430fd9da68590897e06e0be9a2ad26e/reference_materials/virtual_keystroke_example.py#L149-L157
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/redis_model/models/base.py
python
Model.save
(self,pfields=None,new = False)
return True
Saves the instance to the datastore Redis! params : pfields for partial fields save pfields = ("username","gender") param: pfields:object the default is None new:True or False return: True or False
Saves the instance to the datastore Redis! params : pfields for partial fields save pfields = ("username","gender") param: pfields:object the default is None new:True or False return: True or False
[ "Saves", "the", "instance", "to", "the", "datastore", "Redis!", "params", ":", "pfields", "for", "partial", "fields", "save", "pfields", "=", "(", "username", "gender", ")", "param", ":", "pfields", ":", "object", "the", "default", "is", "None", "new", ":"...
def save(self,pfields=None,new = False): n = datetime.now() """ Saves the instance to the datastore Redis! params : pfields for partial fields save pfields = ("username","gender") param: pfields:object the default is None new:True or False return: True or False """ #清空错误列表 self._errors = [] #检查字段的有效性 if pfields: if not isinstance(pfields,tuple): self._errors.append("params must tuple list!") return False for p in pfields: if not self.attributes.has_key(p): self._errors.append("%s field not exists!" % p) return False #检查每个字段的有效性 if not self.is_valid(): return False #这个如果不是New 要生成一个ID if new: _new = True else: _new = self.is_new() if _new and not new and not self.id: self._initialize_id() #这里可以应用到分布式 #with Mutex(self): self._write(_new,pfields) logger.info("save type:%s, id:%s ,use: %s" % (self.__class__.__name__,self.id,datetime.now() - n)) return True
[ "def", "save", "(", "self", ",", "pfields", "=", "None", ",", "new", "=", "False", ")", ":", "n", "=", "datetime", ".", "now", "(", ")", "#清空错误列表", "self", ".", "_errors", "=", "[", "]", "#检查字段的有效性", "if", "pfields", ":", "if", "not", "isinstance",...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/redis_model/models/base.py#L202-L244
riffnshred/nhl-led-scoreboard
14baa7f0691ca507e4c6f7f2ec02e50ccd1ed9e1
src/sbio/motionsensor.py
python
Motion.run
(self)
[]
def run(self): if self.ms_run: pause() # wait forever else: pass
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "ms_run", ":", "pause", "(", ")", "# wait forever", "else", ":", "pass" ]
https://github.com/riffnshred/nhl-led-scoreboard/blob/14baa7f0691ca507e4c6f7f2ec02e50ccd1ed9e1/src/sbio/motionsensor.py#L57-L61
hyperspy/hyperspy
1ffb3fab33e607045a37f30c1463350b72617e10
hyperspy/io_plugins/_hierarchical.py
python
HierarchicalReader.get_format_version
(self)
return Version(version)
Return the format version.
Return the format version.
[ "Return", "the", "format", "version", "." ]
def get_format_version(self): """Return the format version.""" if "file_format_version" in self.file.attrs: version = self.file.attrs["file_format_version"] if isinstance(version, bytes): version = version.decode() if isinstance(version, float): version = str(round(version, 2)) elif "Experiments" in self.file: # Chances are that this is a HSpy hdf5 file version 1.0 version = "1.0" elif "Analysis" in self.file: # Starting version 2.0 we have "Analysis" field as well version = "2.0" else: raise IOError(not_valid_format) return Version(version)
[ "def", "get_format_version", "(", "self", ")", ":", "if", "\"file_format_version\"", "in", "self", ".", "file", ".", "attrs", ":", "version", "=", "self", ".", "file", ".", "attrs", "[", "\"file_format_version\"", "]", "if", "isinstance", "(", "version", ","...
https://github.com/hyperspy/hyperspy/blob/1ffb3fab33e607045a37f30c1463350b72617e10/hyperspy/io_plugins/_hierarchical.py#L100-L117
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/lore/tree.py
python
getHeaders
(document)
return domhelpers.findElements( document, lambda n, m=re.compile('h[23]$').match: m(n.nodeName))
Return all H2 and H3 nodes in the given document. @type document: A DOM Node or Document @rtype: C{list}
Return all H2 and H3 nodes in the given document.
[ "Return", "all", "H2", "and", "H3", "nodes", "in", "the", "given", "document", "." ]
def getHeaders(document): """ Return all H2 and H3 nodes in the given document. @type document: A DOM Node or Document @rtype: C{list} """ return domhelpers.findElements( document, lambda n, m=re.compile('h[23]$').match: m(n.nodeName))
[ "def", "getHeaders", "(", "document", ")", ":", "return", "domhelpers", ".", "findElements", "(", "document", ",", "lambda", "n", ",", "m", "=", "re", ".", "compile", "(", "'h[23]$'", ")", ".", "match", ":", "m", "(", "n", ".", "nodeName", ")", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/lore/tree.py#L308-L318