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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/concurrent/concurrent/futures/_base.py | python | Future.done | (self) | Return True of the future was cancelled or finished executing. | Return True of the future was cancelled or finished executing. | [
"Return",
"True",
"of",
"the",
"future",
"was",
"cancelled",
"or",
"finished",
"executing",
"."
] | def done(self):
"""Return True of the future was cancelled or finished executing."""
with self._condition:
return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED] | [
"def",
"done",
"(",
"self",
")",
":",
"with",
"self",
".",
"_condition",
":",
"return",
"self",
".",
"_state",
"in",
"[",
"CANCELLED",
",",
"CANCELLED_AND_NOTIFIED",
",",
"FINISHED",
"]"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/concurrent/concurrent/futures/_base.py#L349-L352 | ||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/packages/source-python/__init__.py | python | setup_data_update | () | Setup data update. | Setup data update. | [
"Setup",
"data",
"update",
"."
] | def setup_data_update():
"""Setup data update."""
_sp_logger.log_debug('Setting up data update...')
if LOG_FILE_OPERATIONS:
builtins.open = old_open
from core.settings import _core_settings
if not _core_settings.auto_data_update:
_sp_logger.log_debug('Automatic data updates are disable.')
return
_sp_logger.log_info('Checking for data updates...')
from core.update import is_new_data_available, update_data
from translations.manager import language_manager
try:
if is_new_data_available():
_sp_logger.log_info('New data is available. Downloading...')
update_data()
# languages.ini is loaded before the data has been updated. Thus,
# we need to reload the file.
language_manager.reload()
else:
_sp_logger.log_info('No new data is available.')
except:
_sp_logger.log_exception(
'An error occured during the data update.', exc_info=True) | [
"def",
"setup_data_update",
"(",
")",
":",
"_sp_logger",
".",
"log_debug",
"(",
"'Setting up data update...'",
")",
"if",
"LOG_FILE_OPERATIONS",
":",
"builtins",
".",
"open",
"=",
"old_open",
"from",
"core",
".",
"settings",
"import",
"_core_settings",
"if",
"not"... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/source-python/__init__.py#L107-L137 | ||
travisgoodspeed/goodfet | 1750cc1e8588af5470385e52fa098ca7364c2863 | client/USBDevice.py | python | USBDevice.get_string_id | (self, s) | return i | [] | def get_string_id(self, s):
try:
i = self.strings.index(s)
except ValueError:
# string descriptors start at index 1
self.strings.append(s)
i = len(self.strings)
return i | [
"def",
"get_string_id",
"(",
"self",
",",
"s",
")",
":",
"try",
":",
"i",
"=",
"self",
".",
"strings",
".",
"index",
"(",
"s",
")",
"except",
"ValueError",
":",
"# string descriptors start at index 1",
"self",
".",
"strings",
".",
"append",
"(",
"s",
")"... | https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/client/USBDevice.py#L55-L63 | |||
jiangxinyang227/bert-for-task | 3e7aed9e3c757ebc22aabfd4f3fb7b4cd81b010a | bert_task/sentence_pair_task/data_helper.py | python | TrainData.gen_data | (self, file_path, is_training=True) | return inputs_ids, input_masks, segment_ids, labels_ids, label_to_index | 生成数据
:param file_path:
:param is_training
:return: | 生成数据
:param file_path:
:param is_training
:return: | [
"生成数据",
":",
"param",
"file_path",
":",
":",
"param",
"is_training",
":",
"return",
":"
] | def gen_data(self, file_path, is_training=True):
"""
生成数据
:param file_path:
:param is_training
:return:
"""
# 1,读取原始数据
text_as, text_bs, labels = self.read_data(file_path)
print("read finished")
if is_training:
uni_label = list(set(labels))
label_to_index = dict(zip(uni_label, list(range(len(uni_label)))))
with open(os.path.join(self.__output_path, "label_to_index.json"), "w", encoding="utf8") as fw:
json.dump(label_to_index, fw, indent=0, ensure_ascii=False)
else:
with open(os.path.join(self.__output_path, "label_to_index.json"), "r", encoding="utf8") as fr:
label_to_index = json.load(fr)
# 2,输入转索引
inputs_ids, input_masks, segment_ids = self.trans_to_index(text_as, text_bs)
print("index transform finished")
inputs_ids, input_masks, segment_ids = self.padding(inputs_ids, input_masks, segment_ids)
# 3,标签转索引
labels_ids = self.trans_label_to_index(labels, label_to_index)
print("label index transform finished")
for i in range(5):
print("line {}: *****************************************".format(i))
print("text_a: ", text_as[i])
print("text_b: ", text_bs[i])
print("input_id: ", inputs_ids[i])
print("input_mask: ", input_masks[i])
print("segment_id: ", segment_ids[i])
print("label_id: ", labels[i])
return inputs_ids, input_masks, segment_ids, labels_ids, label_to_index | [
"def",
"gen_data",
"(",
"self",
",",
"file_path",
",",
"is_training",
"=",
"True",
")",
":",
"# 1,读取原始数据",
"text_as",
",",
"text_bs",
",",
"labels",
"=",
"self",
".",
"read_data",
"(",
"file_path",
")",
"print",
"(",
"\"read finished\"",
")",
"if",
"is_tra... | https://github.com/jiangxinyang227/bert-for-task/blob/3e7aed9e3c757ebc22aabfd4f3fb7b4cd81b010a/bert_task/sentence_pair_task/data_helper.py#L119-L159 | |
jamiecaesar/securecrt-tools | f3cbb49223a485fc9af86e9799b5c940f19e8027 | s_save_output.py | python | script_main | (session) | | SINGLE device script
| Author: Jamie Caesar
| Email: jcaesar@presidio.com
This script will prompt the user for a command for a Cisco device and save the output into a file.
The path where the file is saved is specified in settings.ini file.
This script assumes that you are already connected to the device before running it.
:param session: A subclass of the sessions.Session object that represents this particular script session (either
SecureCRTSession or DirectSession)
:type session: sessions.Session | | SINGLE device script
| Author: Jamie Caesar
| Email: jcaesar@presidio.com | [
"|",
"SINGLE",
"device",
"script",
"|",
"Author",
":",
"Jamie",
"Caesar",
"|",
"Email",
":",
"jcaesar@presidio",
".",
"com"
] | def script_main(session):
"""
| SINGLE device script
| Author: Jamie Caesar
| Email: jcaesar@presidio.com
This script will prompt the user for a command for a Cisco device and save the output into a file.
The path where the file is saved is specified in settings.ini file.
This script assumes that you are already connected to the device before running it.
:param session: A subclass of the sessions.Session object that represents this particular script session (either
SecureCRTSession or DirectSession)
:type session: sessions.Session
"""
# Get script object that owns this session, so we can check settings, get textfsm templates, etc
script = session.script
# Start session with device, i.e. modify term parameters for better interaction (assuming already connected)
session.start_cisco_session()
send_cmd = script.prompt_window("Enter the command to capture")
logger.debug("Received command: '{0}'".format(send_cmd))
if send_cmd == "":
return
# Generate filename used for output files.
full_file_name = session.create_output_filename(send_cmd)
# Get the output of our command and save it to the filename specified
session.write_output_to_file(send_cmd, full_file_name)
# Return terminal parameters back to the original state.
session.end_cisco_session() | [
"def",
"script_main",
"(",
"session",
")",
":",
"# Get script object that owns this session, so we can check settings, get textfsm templates, etc",
"script",
"=",
"session",
".",
"script",
"# Start session with device, i.e. modify term parameters for better interaction (assuming already conn... | https://github.com/jamiecaesar/securecrt-tools/blob/f3cbb49223a485fc9af86e9799b5c940f19e8027/s_save_output.py#L29-L63 | ||
textX/Arpeggio | 9ec6c7ee402054616b2f81e76557d39d3d376fcd | examples/calc/calc.py | python | CalcVisitor.visit_term | (self, node, children) | return term | Divides or multiplies factors.
Factor nodes will be already evaluated. | Divides or multiplies factors.
Factor nodes will be already evaluated. | [
"Divides",
"or",
"multiplies",
"factors",
".",
"Factor",
"nodes",
"will",
"be",
"already",
"evaluated",
"."
] | def visit_term(self, node, children):
"""
Divides or multiplies factors.
Factor nodes will be already evaluated.
"""
if self.debug:
print("Term {}".format(children))
term = children[0]
for i in range(2, len(children), 2):
if children[i-1] == "*":
term *= children[i]
else:
term /= children[i]
if self.debug:
print("Term = {}".format(term))
return term | [
"def",
"visit_term",
"(",
"self",
",",
"node",
",",
"children",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Term {}\"",
".",
"format",
"(",
"children",
")",
")",
"term",
"=",
"children",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"("... | https://github.com/textX/Arpeggio/blob/9ec6c7ee402054616b2f81e76557d39d3d376fcd/examples/calc/calc.py#L52-L67 | |
rlworkgroup/garage | b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507 | src/garage/torch/policies/categorical_cnn_policy.py | python | CategoricalCNNPolicy.forward | (self, observations) | return dist, {} | Compute the action distributions from the observations.
Args:
observations (torch.Tensor): Observations to act on.
Returns:
torch.distributions.Distribution: Batch distribution of actions.
dict[str, torch.Tensor]: Additional agent_info, as torch Tensors.
Do not need to be detached, and can be on any device. | Compute the action distributions from the observations. | [
"Compute",
"the",
"action",
"distributions",
"from",
"the",
"observations",
"."
] | def forward(self, observations):
"""Compute the action distributions from the observations.
Args:
observations (torch.Tensor): Observations to act on.
Returns:
torch.distributions.Distribution: Batch distribution of actions.
dict[str, torch.Tensor]: Additional agent_info, as torch Tensors.
Do not need to be detached, and can be on any device.
"""
# We're given flattened observations.
observations = observations.reshape(
-1, *self._env_spec.observation_space.shape)
cnn_output = self._cnn_module(observations)
mlp_output = self._mlp_module(cnn_output)[0]
logits = torch.softmax(mlp_output, axis=1)
dist = torch.distributions.Categorical(logits=logits)
return dist, {} | [
"def",
"forward",
"(",
"self",
",",
"observations",
")",
":",
"# We're given flattened observations.",
"observations",
"=",
"observations",
".",
"reshape",
"(",
"-",
"1",
",",
"*",
"self",
".",
"_env_spec",
".",
"observation_space",
".",
"shape",
")",
"cnn_outpu... | https://github.com/rlworkgroup/garage/blob/b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507/src/garage/torch/policies/categorical_cnn_policy.py#L122-L140 | |
containernet/containernet | 7b2ae38d691b2ed8da2b2700b85ed03562271d01 | examples/miniedit.py | python | MiniEdit.createNodeBindings | ( self ) | return l | Create a set of bindings for nodes. | Create a set of bindings for nodes. | [
"Create",
"a",
"set",
"of",
"bindings",
"for",
"nodes",
"."
] | def createNodeBindings( self ):
"Create a set of bindings for nodes."
bindings = {
'<ButtonPress-1>': self.clickNode,
'<B1-Motion>': self.dragNode,
'<ButtonRelease-1>': self.releaseNode,
'<Enter>': self.enterNode,
'<Leave>': self.leaveNode
}
l = Label() # lightweight-ish owner for bindings
for event, binding in list(bindings.items()):
l.bind( event, binding )
return l | [
"def",
"createNodeBindings",
"(",
"self",
")",
":",
"bindings",
"=",
"{",
"'<ButtonPress-1>'",
":",
"self",
".",
"clickNode",
",",
"'<B1-Motion>'",
":",
"self",
".",
"dragNode",
",",
"'<ButtonRelease-1>'",
":",
"self",
".",
"releaseNode",
",",
"'<Enter>'",
":"... | https://github.com/containernet/containernet/blob/7b2ae38d691b2ed8da2b2700b85ed03562271d01/examples/miniedit.py#L2361-L2373 | |
hvac/hvac | ec048ded30d21c13c21cfa950d148c8bfc1467b0 | hvac/api/secrets_engines/pki.py | python | Pki.list_certificates | (self, mount_point=DEFAULT_MOUNT_POINT) | return self._adapter.list(
url=api_path,
) | List Certificates.
The list of the current certificates by serial number only.
Supported methods:
LIST: /{mount_point}/certs. Produces: 200 application/json
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: dict | List Certificates. | [
"List",
"Certificates",
"."
] | def list_certificates(self, mount_point=DEFAULT_MOUNT_POINT):
"""List Certificates.
The list of the current certificates by serial number only.
Supported methods:
LIST: /{mount_point}/certs. Produces: 200 application/json
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: dict
"""
api_path = utils.format_url("/v1/{mount_point}/certs", mount_point=mount_point)
return self._adapter.list(
url=api_path,
) | [
"def",
"list_certificates",
"(",
"self",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"api_path",
"=",
"utils",
".",
"format_url",
"(",
"\"/v1/{mount_point}/certs\"",
",",
"mount_point",
"=",
"mount_point",
")",
"return",
"self",
".",
"_adapter",
".",... | https://github.com/hvac/hvac/blob/ec048ded30d21c13c21cfa950d148c8bfc1467b0/hvac/api/secrets_engines/pki.py#L80-L96 | |
mchristopher/PokemonGo-DesktopMap | ec37575f2776ee7d64456e2a1f6b6b78830b4fe0 | app/pywin/Lib/macurl2path.py | python | pathname2url | (pathname) | OS-specific conversion from a file system path to a relative URL
of the 'file' scheme; not recommended for general use. | OS-specific conversion from a file system path to a relative URL
of the 'file' scheme; not recommended for general use. | [
"OS",
"-",
"specific",
"conversion",
"from",
"a",
"file",
"system",
"path",
"to",
"a",
"relative",
"URL",
"of",
"the",
"file",
"scheme",
";",
"not",
"recommended",
"for",
"general",
"use",
"."
] | def pathname2url(pathname):
"""OS-specific conversion from a file system path to a relative URL
of the 'file' scheme; not recommended for general use."""
if '/' in pathname:
raise RuntimeError, "Cannot convert pathname containing slashes"
components = pathname.split(':')
# Remove empty first and/or last component
if components[0] == '':
del components[0]
if components[-1] == '':
del components[-1]
# Replace empty string ('::') by .. (will result in '/../' later)
for i in range(len(components)):
if components[i] == '':
components[i] = '..'
# Truncate names longer than 31 bytes
components = map(_pncomp2url, components)
if os.path.isabs(pathname):
return '/' + '/'.join(components)
else:
return '/'.join(components) | [
"def",
"pathname2url",
"(",
"pathname",
")",
":",
"if",
"'/'",
"in",
"pathname",
":",
"raise",
"RuntimeError",
",",
"\"Cannot convert pathname containing slashes\"",
"components",
"=",
"pathname",
".",
"split",
"(",
"':'",
")",
"# Remove empty first and/or last componen... | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/macurl2path.py#L52-L73 | ||
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/werkzeug/wrappers.py | python | AcceptMixin.accept_mimetypes | (self) | return parse_accept_header(self.environ.get('HTTP_ACCEPT'), MIMEAccept) | List of mimetypes this client supports as
:class:`~werkzeug.datastructures.MIMEAccept` object. | List of mimetypes this client supports as
:class:`~werkzeug.datastructures.MIMEAccept` object. | [
"List",
"of",
"mimetypes",
"this",
"client",
"supports",
"as",
":",
"class",
":",
"~werkzeug",
".",
"datastructures",
".",
"MIMEAccept",
"object",
"."
] | def accept_mimetypes(self):
"""List of mimetypes this client supports as
:class:`~werkzeug.datastructures.MIMEAccept` object.
"""
return parse_accept_header(self.environ.get('HTTP_ACCEPT'), MIMEAccept) | [
"def",
"accept_mimetypes",
"(",
"self",
")",
":",
"return",
"parse_accept_header",
"(",
"self",
".",
"environ",
".",
"get",
"(",
"'HTTP_ACCEPT'",
")",
",",
"MIMEAccept",
")"
] | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/werkzeug/wrappers.py#L1095-L1099 | |
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-47/fabmetheus_utilities/geometry/geometry_utilities/matrix.py | python | setElementNodeDictionaryMatrix | (elementNode, matrix4X4) | Set the element attribute dictionary or element matrix to the matrix. | Set the element attribute dictionary or element matrix to the matrix. | [
"Set",
"the",
"element",
"attribute",
"dictionary",
"or",
"element",
"matrix",
"to",
"the",
"matrix",
"."
] | def setElementNodeDictionaryMatrix(elementNode, matrix4X4):
'Set the element attribute dictionary or element matrix to the matrix.'
if elementNode.xmlObject == None:
elementNode.attributes.update(matrix4X4.getAttributes('matrix.'))
else:
elementNode.xmlObject.matrix4X4 = matrix4X4 | [
"def",
"setElementNodeDictionaryMatrix",
"(",
"elementNode",
",",
"matrix4X4",
")",
":",
"if",
"elementNode",
".",
"xmlObject",
"==",
"None",
":",
"elementNode",
".",
"attributes",
".",
"update",
"(",
"matrix4X4",
".",
"getAttributes",
"(",
"'matrix.'",
")",
")"... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/geometry/geometry_utilities/matrix.py#L403-L408 | ||
fluentpython/notebooks | 0f6e1e8d1686743dacd9281df7c5b5921812010a | 18b-async-await/charfinder/charfinder.py | python | UnicodeNameIndex.get_descriptions | (self, chars) | [] | def get_descriptions(self, chars):
for char in chars:
yield self.describe(char) | [
"def",
"get_descriptions",
"(",
"self",
",",
"chars",
")",
":",
"for",
"char",
"in",
"chars",
":",
"yield",
"self",
".",
"describe",
"(",
"char",
")"
] | https://github.com/fluentpython/notebooks/blob/0f6e1e8d1686743dacd9281df7c5b5921812010a/18b-async-await/charfinder/charfinder.py#L189-L191 | ||||
GoogleCloudPlatform/compute-image-packages | cf4b33214f770da2299923a5fa73d3d95f66ec35 | packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_config.py | python | InstanceConfig.WriteConfig | (self) | Write the config values to the instance defaults file. | Write the config values to the instance defaults file. | [
"Write",
"the",
"config",
"values",
"to",
"the",
"instance",
"defaults",
"file",
"."
] | def WriteConfig(self):
"""Write the config values to the instance defaults file."""
super(InstanceConfig, self).WriteConfig(config_file=self.instance_config) | [
"def",
"WriteConfig",
"(",
"self",
")",
":",
"super",
"(",
"InstanceConfig",
",",
"self",
")",
".",
"WriteConfig",
"(",
"config_file",
"=",
"self",
".",
"instance_config",
")"
] | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/cf4b33214f770da2299923a5fa73d3d95f66ec35/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_config.py#L159-L161 | ||
yuxiaokui/Intranet-Penetration | f57678a204840c83cbf3308e3470ae56c5ff514b | proxy/XX-Net/code/default/python27/1.0/lib/noarch/OpenSSL/crypto.py | python | Revoked.set_reason | (self, reason) | Set the reason of this revocation.
If :py:data:`reason` is :py:const:`None`, delete the reason instead.
:param reason: The reason string.
:type reason: :py:class:`bytes` or :py:class:`NoneType`
:return: :py:const:`None`
.. seealso::
:py:meth:`all_reasons`, which gives you a list of all supported
reasons which you might pass to this method. | Set the reason of this revocation. | [
"Set",
"the",
"reason",
"of",
"this",
"revocation",
"."
] | def set_reason(self, reason):
"""
Set the reason of this revocation.
If :py:data:`reason` is :py:const:`None`, delete the reason instead.
:param reason: The reason string.
:type reason: :py:class:`bytes` or :py:class:`NoneType`
:return: :py:const:`None`
.. seealso::
:py:meth:`all_reasons`, which gives you a list of all supported
reasons which you might pass to this method.
"""
if reason is None:
self._delete_reason()
elif not isinstance(reason, bytes):
raise TypeError("reason must be None or a byte string")
else:
reason = reason.lower().replace(b' ', b'')
reason_code = [r.lower() for r in self._crl_reasons].index(reason)
new_reason_ext = _lib.ASN1_ENUMERATED_new()
if new_reason_ext == _ffi.NULL:
# TODO: This is untested.
_raise_current_error()
new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
if set_result == _ffi.NULL:
# TODO: This is untested.
_raise_current_error()
self._delete_reason()
add_result = _lib.X509_REVOKED_add1_ext_i2d(
self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
if not add_result:
# TODO: This is untested.
_raise_current_error() | [
"def",
"set_reason",
"(",
"self",
",",
"reason",
")",
":",
"if",
"reason",
"is",
"None",
":",
"self",
".",
"_delete_reason",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"reason",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"reason must be None or ... | https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/noarch/OpenSSL/crypto.py#L1793-L1834 | ||
enthought/traits | d22ce1f096e2a6f87c78d7f1bb5bf0abab1a18ff | traits/etsconfig/etsconfig.py | python | ETSConfig._initialize_toolkit | (self) | return toolkit | Initializes the toolkit. | Initializes the toolkit. | [
"Initializes",
"the",
"toolkit",
"."
] | def _initialize_toolkit(self):
"""
Initializes the toolkit.
"""
if self._toolkit is not None:
toolkit = self._toolkit
else:
toolkit = os.environ.get("ETS_TOOLKIT", "")
return toolkit | [
"def",
"_initialize_toolkit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_toolkit",
"is",
"not",
"None",
":",
"toolkit",
"=",
"self",
".",
"_toolkit",
"else",
":",
"toolkit",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"ETS_TOOLKIT\"",
",",
"\"\"",
"... | https://github.com/enthought/traits/blob/d22ce1f096e2a6f87c78d7f1bb5bf0abab1a18ff/traits/etsconfig/etsconfig.py#L440-L450 | |
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-modules/twisted/twisted/spread/pb.py | python | RemoteReference.jellyFor | (self, jellier) | If I am being sent back to where I came from, serialize as a local backreference. | If I am being sent back to where I came from, serialize as a local backreference. | [
"If",
"I",
"am",
"being",
"sent",
"back",
"to",
"where",
"I",
"came",
"from",
"serialize",
"as",
"a",
"local",
"backreference",
"."
] | def jellyFor(self, jellier):
"""If I am being sent back to where I came from, serialize as a local backreference.
"""
if jellier.invoker:
assert self.broker == jellier.invoker, "Can't send references to brokers other than their own."
return "local", self.luid
else:
return "unpersistable", "References cannot be serialized" | [
"def",
"jellyFor",
"(",
"self",
",",
"jellier",
")",
":",
"if",
"jellier",
".",
"invoker",
":",
"assert",
"self",
".",
"broker",
"==",
"jellier",
".",
"invoker",
",",
"\"Can't send references to brokers other than their own.\"",
"return",
"\"local\"",
",",
"self",... | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/spread/pb.py#L299-L306 | ||
javipalanca/spade | 6a857c2ae0a86b3bdfd20ccfcd28a11e1c6db81e | spade/behaviour.py | python | CyclicBehaviour.exit_code | (self) | Returns the exit_code of the behaviour.
It only works when the behaviour is done or killed,
otherwise it raises an exception.
Returns:
object: the exit code of the behaviour
Raises:
BehaviourNotFinishedException: if the behaviour is not yet finished | Returns the exit_code of the behaviour.
It only works when the behaviour is done or killed,
otherwise it raises an exception. | [
"Returns",
"the",
"exit_code",
"of",
"the",
"behaviour",
".",
"It",
"only",
"works",
"when",
"the",
"behaviour",
"is",
"done",
"or",
"killed",
"otherwise",
"it",
"raises",
"an",
"exception",
"."
] | def exit_code(self) -> Any:
"""
Returns the exit_code of the behaviour.
It only works when the behaviour is done or killed,
otherwise it raises an exception.
Returns:
object: the exit code of the behaviour
Raises:
BehaviourNotFinishedException: if the behaviour is not yet finished
"""
if self._done() or self.is_killed():
return self._exit_code
else:
raise BehaviourNotFinishedException | [
"def",
"exit_code",
"(",
"self",
")",
"->",
"Any",
":",
"if",
"self",
".",
"_done",
"(",
")",
"or",
"self",
".",
"is_killed",
"(",
")",
":",
"return",
"self",
".",
"_exit_code",
"else",
":",
"raise",
"BehaviourNotFinishedException"
] | https://github.com/javipalanca/spade/blob/6a857c2ae0a86b3bdfd20ccfcd28a11e1c6db81e/spade/behaviour.py#L163-L179 | ||
jwasham/code-catalog-python | c8645a1058b970206e688bfcb1782c18c64bcc00 | catalog/suggested/tree/expression_tree.py | python | ExpressionTree._evaluate_recur | (self, p) | Return the numeric result of subtree rooted at p. | Return the numeric result of subtree rooted at p. | [
"Return",
"the",
"numeric",
"result",
"of",
"subtree",
"rooted",
"at",
"p",
"."
] | def _evaluate_recur(self, p):
"""Return the numeric result of subtree rooted at p."""
if self.is_leaf(p):
return float(p.element()) # we assume element is numeric
else:
op = p.element()
left_val = self._evaluate_recur(self.left(p))
right_val = self._evaluate_recur(self.right(p))
if op == '+':
return left_val + right_val
elif op == '-':
return left_val - right_val
elif op == '/':
return left_val / right_val
else: # treat 'x' or '*' as multiplication
return left_val * right_val | [
"def",
"_evaluate_recur",
"(",
"self",
",",
"p",
")",
":",
"if",
"self",
".",
"is_leaf",
"(",
"p",
")",
":",
"return",
"float",
"(",
"p",
".",
"element",
"(",
")",
")",
"# we assume element is numeric",
"else",
":",
"op",
"=",
"p",
".",
"element",
"(... | https://github.com/jwasham/code-catalog-python/blob/c8645a1058b970206e688bfcb1782c18c64bcc00/catalog/suggested/tree/expression_tree.py#L47-L62 | ||
kbandla/ImmunityDebugger | 2abc03fb15c8f3ed0914e1175c4d8933977c73e3 | 1.84/Libs/librecognition.py | python | FunctionRecognition._searchFunctionByHeuristic | (self, search, functionhash=None, firstcallhash=None, exact=None, heuristic = 90, module = None, firstbb = None) | return poss_return | Search memory to find a function that fullfit the options.
@type search: STRING
@param search: searchCommand string to make the first selection
@type functionhash: STRING
@param functionhash: the primary function hash (use makeFunctionHash to generate this value)
@type firstcallhash: STRING
@param firstcallhash: the hash of the first call on single BB functions (use makeFunctionHash to generate this value)
@type exact: STRING
@param exact: an exact function hash, this's a binary byte-per-byte hash (use makeFunctionHash to generate this value)
@type heuristic: INTEGER
@param heuristic: heuristic threasold to consider a real function match
@type module: STRING
@param module: name of a module to restrict the search
@type firstbb: STRING
@param firstbb: generalized assembler of the first BB (to search function begin)
@rtype: LIST
@return: a list of tuples with possible function's addresses and the heauristic match percentage | Search memory to find a function that fullfit the options.
@type search: STRING
@param search: searchCommand string to make the first selection
@type functionhash: STRING
@param functionhash: the primary function hash (use makeFunctionHash to generate this value) | [
"Search",
"memory",
"to",
"find",
"a",
"function",
"that",
"fullfit",
"the",
"options",
".",
"@type",
"search",
":",
"STRING",
"@param",
"search",
":",
"searchCommand",
"string",
"to",
"make",
"the",
"first",
"selection",
"@type",
"functionhash",
":",
"STRING"... | def _searchFunctionByHeuristic(self, search, functionhash=None, firstcallhash=None, exact=None, heuristic = 90, module = None, firstbb = None):
"""
Search memory to find a function that fullfit the options.
@type search: STRING
@param search: searchCommand string to make the first selection
@type functionhash: STRING
@param functionhash: the primary function hash (use makeFunctionHash to generate this value)
@type firstcallhash: STRING
@param firstcallhash: the hash of the first call on single BB functions (use makeFunctionHash to generate this value)
@type exact: STRING
@param exact: an exact function hash, this's a binary byte-per-byte hash (use makeFunctionHash to generate this value)
@type heuristic: INTEGER
@param heuristic: heuristic threasold to consider a real function match
@type module: STRING
@param module: name of a module to restrict the search
@type firstbb: STRING
@param firstbb: generalized assembler of the first BB (to search function begin)
@rtype: LIST
@return: a list of tuples with possible function's addresses and the heauristic match percentage
"""
#if the first argument is a LIST, decode it to each real argument of the function, following the order in the CSV file.
#this give us a simple support for copy 'n paste from the CSV file.
if isinstance(search, list):
search.reverse()
tmp = search[:]
if tmp: search = tmp.pop()
if tmp: functionhash = tmp.pop()
if tmp: firstcallhash = tmp.pop()
if tmp: exact = tmp.pop()
if tmp: version = tmp.pop()
if tmp: file = tmp.pop()
if tmp: firstbb = tmp.pop()
#this arguments are mandatory
if not search or not functionhash:
return None
if not firstcallhash:
firstcallhash = ""
heu_addy = None
heu_perc = 0
poss_functions = []
poss_return = []
search = string.replace(search, "\\n","\n")
if search:
if module:
#XXX: access directly isn't the best way to do this
for key,mod in debugger.get_all_modules().iteritems():
if module.lower() in key.lower():
poss_functions += self.imm.searchCommandsOnModule(mod[0], search)
else:
poss_functions = self.imm.searchCommands(search)
if poss_functions:
for poss in poss_functions:
#self.imm.log("possible funct: %08X" % poss[0])
addy = self.imm.getFunctionBegin(poss[0])
if not addy:
#check entrypoint routine
for mod in self.imm.getAllModules().values():
if mod.getMainentry():
#self.imm.log("mainentry: %08X" % mod.getMainentry())
f = StackFunction(self.imm, mod.getMainentry())
if f.isInsideFunction(poss[0]):
addy = mod.getMainentry()
break
if not addy and firstbb:
#self.imm.log("Trying with the new firstbb")
addy = self.findBasicBlockHeuristically(poss[0], firstbb)
if not addy and firstbb:
tmp = self.findFirstBB(poss[0])
if tmp:
#self.imm.log("Trying with the new firstbb 2nd try:%X"%tmp,tmp)
addy = self.findBasicBlockHeuristically(tmp, firstbb)
if not addy:
addy = poss[0]
#self.imm.log("possible start: %08X" % addy)
#Make a comparision using an Exact Hash
if exact:
test = self.makeFunctionHashExact(addy)
if exact == test and not firstcallhash:
#self.imm.log("EXACT match")
#when we find an exact match, we don't need to search anymore
return [ (addy, 100) ]
perc = self.checkHeuristic(addy, functionhash, firstcallhash)
#self.imm.log("function %08X similar in %d%%" % (addy, perc))
if perc >= heuristic:
poss_return.append( (addy,perc) )
#self.imm.log("HEURISTIC match")
return poss_return | [
"def",
"_searchFunctionByHeuristic",
"(",
"self",
",",
"search",
",",
"functionhash",
"=",
"None",
",",
"firstcallhash",
"=",
"None",
",",
"exact",
"=",
"None",
",",
"heuristic",
"=",
"90",
",",
"module",
"=",
"None",
",",
"firstbb",
"=",
"None",
")",
":... | https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.84/Libs/librecognition.py#L380-L480 | |
trent-b/iterative-stratification | cf140d6bb56c761c73fd75c2230ddea68be08d9d | iterstrat/ml_stratifiers.py | python | MultilabelStratifiedShuffleSplit.split | (self, X, y, groups=None) | return super(MultilabelStratifiedShuffleSplit, self).split(X, y, groups) | Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
Note that providing ``y`` is sufficient to generate the splits and
hence ``np.zeros(n_samples)`` may be used as a placeholder for
``X`` instead of actual training data.
y : array-like, shape (n_samples, n_labels)
The target variable for supervised learning problems.
Multilabel stratification is done based on the y labels.
groups : object
Always ignored, exists for compatibility.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
Notes
-----
Randomized CV splitters may return different results for each call of
split. You can make the results identical by setting ``random_state``
to an integer. | Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
Note that providing ``y`` is sufficient to generate the splits and
hence ``np.zeros(n_samples)`` may be used as a placeholder for
``X`` instead of actual training data.
y : array-like, shape (n_samples, n_labels)
The target variable for supervised learning problems.
Multilabel stratification is done based on the y labels.
groups : object
Always ignored, exists for compatibility.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
Notes
-----
Randomized CV splitters may return different results for each call of
split. You can make the results identical by setting ``random_state``
to an integer. | [
"Generate",
"indices",
"to",
"split",
"data",
"into",
"training",
"and",
"test",
"set",
".",
"Parameters",
"----------",
"X",
":",
"array",
"-",
"like",
"shape",
"(",
"n_samples",
"n_features",
")",
"Training",
"data",
"where",
"n_samples",
"is",
"the",
"num... | def split(self, X, y, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
Note that providing ``y`` is sufficient to generate the splits and
hence ``np.zeros(n_samples)`` may be used as a placeholder for
``X`` instead of actual training data.
y : array-like, shape (n_samples, n_labels)
The target variable for supervised learning problems.
Multilabel stratification is done based on the y labels.
groups : object
Always ignored, exists for compatibility.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
Notes
-----
Randomized CV splitters may return different results for each call of
split. You can make the results identical by setting ``random_state``
to an integer.
"""
y = check_array(y, ensure_2d=False, dtype=None)
return super(MultilabelStratifiedShuffleSplit, self).split(X, y, groups) | [
"def",
"split",
"(",
"self",
",",
"X",
",",
"y",
",",
"groups",
"=",
"None",
")",
":",
"y",
"=",
"check_array",
"(",
"y",
",",
"ensure_2d",
"=",
"False",
",",
"dtype",
"=",
"None",
")",
"return",
"super",
"(",
"MultilabelStratifiedShuffleSplit",
",",
... | https://github.com/trent-b/iterative-stratification/blob/cf140d6bb56c761c73fd75c2230ddea68be08d9d/iterstrat/ml_stratifiers.py#L358-L386 | |
napari/napari | dbf4158e801fa7a429de8ef1cdee73bf6d64c61e | napari/utils/colormaps/colormap_utils.py | python | ensure_colormap | (colormap: ValidColormapArg) | return AVAILABLE_COLORMAPS[name] | Accept any valid colormap argument, and return Colormap, or raise.
Adds any new colormaps to AVAILABLE_COLORMAPS in the process, except
for custom unnamed colormaps created from color values.
Parameters
----------
colormap : ValidColormapArg
See ValidColormapArg for supported input types.
Returns
-------
Colormap
Warns
-----
UserWarning
If ``colormap`` is not a valid colormap argument type.
Raises
------
KeyError
If a string is provided that is not in AVAILABLE_COLORMAPS
TypeError
If a tuple is provided and the first element is not a string or the
second element is not a Colormap.
TypeError
If a dict is provided and any of the values are not Colormap instances
or valid inputs to the Colormap constructor. | Accept any valid colormap argument, and return Colormap, or raise. | [
"Accept",
"any",
"valid",
"colormap",
"argument",
"and",
"return",
"Colormap",
"or",
"raise",
"."
] | def ensure_colormap(colormap: ValidColormapArg) -> Colormap:
"""Accept any valid colormap argument, and return Colormap, or raise.
Adds any new colormaps to AVAILABLE_COLORMAPS in the process, except
for custom unnamed colormaps created from color values.
Parameters
----------
colormap : ValidColormapArg
See ValidColormapArg for supported input types.
Returns
-------
Colormap
Warns
-----
UserWarning
If ``colormap`` is not a valid colormap argument type.
Raises
------
KeyError
If a string is provided that is not in AVAILABLE_COLORMAPS
TypeError
If a tuple is provided and the first element is not a string or the
second element is not a Colormap.
TypeError
If a dict is provided and any of the values are not Colormap instances
or valid inputs to the Colormap constructor.
"""
with AVAILABLE_COLORMAPS_LOCK:
if isinstance(colormap, str):
name = colormap
if name not in AVAILABLE_COLORMAPS:
cmap = vispy_or_mpl_colormap(
name
) # raises KeyError if not found
AVAILABLE_COLORMAPS[name] = cmap
elif isinstance(colormap, Colormap):
AVAILABLE_COLORMAPS[colormap.name] = colormap
name = colormap.name
elif isinstance(colormap, VispyColormap):
# if a vispy colormap instance is provided, make sure we don't already
# know about it before adding a new unnamed colormap
name = None
for key, val in AVAILABLE_COLORMAPS.items():
if colormap == val:
name = key
break
if not name:
name, _display_name = _increment_unnamed_colormap(
AVAILABLE_COLORMAPS
)
# Convert from vispy colormap
cmap = convert_vispy_colormap(colormap, name=name)
AVAILABLE_COLORMAPS[name] = cmap
elif isinstance(colormap, tuple):
if (
len(colormap) == 2
and isinstance(colormap[0], str)
and isinstance(colormap[1], (VispyColormap, Colormap))
):
name, cmap = colormap
# Convert from vispy colormap
if isinstance(cmap, VispyColormap):
cmap = convert_vispy_colormap(cmap, name=name)
else:
cmap.name = name
AVAILABLE_COLORMAPS[name] = cmap
else:
colormap = _colormap_from_colors(colormap)
if colormap is not None:
# Return early because we don't have a name for this colormap.
return colormap
raise TypeError(
trans._(
"When providing a tuple as a colormap argument, either 1) the first element must be a string and the second a Colormap instance 2) or the tuple should be convertible to one or more colors",
deferred=True,
)
)
elif isinstance(colormap, dict):
if 'colors' in colormap and not (
isinstance(colormap['colors'], VispyColormap)
or isinstance(colormap['colors'], Colormap)
):
cmap = Colormap(**colormap)
name = cmap.name
AVAILABLE_COLORMAPS[name] = cmap
elif not all(
(isinstance(i, VispyColormap) or isinstance(i, Colormap))
for i in colormap.values()
):
raise TypeError(
trans._(
"When providing a dict as a colormap, all values must be Colormap instances",
deferred=True,
)
)
else:
# Convert from vispy colormaps
for key, cmap in colormap.items():
# Convert from vispy colormap
if isinstance(cmap, VispyColormap):
cmap = convert_vispy_colormap(cmap, name=key)
else:
cmap.name = key
name = key
colormap[name] = cmap
AVAILABLE_COLORMAPS.update(colormap)
if len(colormap) == 1:
name = list(colormap)[0] # first key in dict
elif len(colormap) > 1:
name = list(colormap.keys())[0]
warnings.warn(
trans._(
"only the first item in a colormap dict is used as an argument",
deferred=True,
)
)
else:
raise ValueError(
trans._(
"Received an empty dict as a colormap argument.",
deferred=True,
)
)
else:
colormap = _colormap_from_colors(colormap)
if colormap is not None:
# Return early because we don't have a name for this colormap.
return colormap
warnings.warn(
trans._(
'invalid type for colormap: {cm_type}. Must be a {{str, tuple, dict, napari.utils.Colormap, vispy.colors.Colormap}}. Reverting to default',
deferred=True,
cm_type=type(colormap),
)
)
# Use default colormap
name = 'gray'
return AVAILABLE_COLORMAPS[name] | [
"def",
"ensure_colormap",
"(",
"colormap",
":",
"ValidColormapArg",
")",
"->",
"Colormap",
":",
"with",
"AVAILABLE_COLORMAPS_LOCK",
":",
"if",
"isinstance",
"(",
"colormap",
",",
"str",
")",
":",
"name",
"=",
"colormap",
"if",
"name",
"not",
"in",
"AVAILABLE_C... | https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/utils/colormaps/colormap_utils.py#L492-L641 | |
facebookresearch/hydra | 9b2f4d54b328d1551aa70a241a1d638cbe046367 | hydra/core/override_parser/overrides_visitor.py | python | HydraErrorListener.syntaxError | (
self,
recognizer: Any,
offending_symbol: Any,
line: Any,
column: Any,
msg: Any,
e: Any,
) | [] | def syntaxError(
self,
recognizer: Any,
offending_symbol: Any,
line: Any,
column: Any,
msg: Any,
e: Any,
) -> None:
if msg is not None:
raise HydraException(msg) from e
else:
raise HydraException(str(e)) from e | [
"def",
"syntaxError",
"(",
"self",
",",
"recognizer",
":",
"Any",
",",
"offending_symbol",
":",
"Any",
",",
"line",
":",
"Any",
",",
"column",
":",
"Any",
",",
"msg",
":",
"Any",
",",
"e",
":",
"Any",
",",
")",
"->",
"None",
":",
"if",
"msg",
"is... | https://github.com/facebookresearch/hydra/blob/9b2f4d54b328d1551aa70a241a1d638cbe046367/hydra/core/override_parser/overrides_visitor.py#L362-L374 | ||||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/fsmt/modeling_fsmt.py | python | make_padding_mask | (input_ids, padding_idx=1) | return padding_mask | True for pad tokens | True for pad tokens | [
"True",
"for",
"pad",
"tokens"
] | def make_padding_mask(input_ids, padding_idx=1):
"""True for pad tokens"""
padding_mask = input_ids.eq(padding_idx)
if not padding_mask.any():
padding_mask = None
return padding_mask | [
"def",
"make_padding_mask",
"(",
"input_ids",
",",
"padding_idx",
"=",
"1",
")",
":",
"padding_mask",
"=",
"input_ids",
".",
"eq",
"(",
"padding_idx",
")",
"if",
"not",
"padding_mask",
".",
"any",
"(",
")",
":",
"padding_mask",
"=",
"None",
"return",
"padd... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/fsmt/modeling_fsmt.py#L379-L384 | |
autotest/autotest | 4614ae5f550cc888267b9a419e4b90deb54f8fae | utils/external_packages.py | python | ExternalPackage._build_and_install_current_dir_setupegg_py | (self, install_dir) | return self._install_from_egg(install_dir, egg_path) | For use as a _build_and_install_current_dir implementation. | For use as a _build_and_install_current_dir implementation. | [
"For",
"use",
"as",
"a",
"_build_and_install_current_dir",
"implementation",
"."
] | def _build_and_install_current_dir_setupegg_py(self, install_dir):
"""For use as a _build_and_install_current_dir implementation."""
egg_path = self._build_egg_using_setup_py(setup_py='setupegg.py')
if not egg_path:
return False
return self._install_from_egg(install_dir, egg_path) | [
"def",
"_build_and_install_current_dir_setupegg_py",
"(",
"self",
",",
"install_dir",
")",
":",
"egg_path",
"=",
"self",
".",
"_build_egg_using_setup_py",
"(",
"setup_py",
"=",
"'setupegg.py'",
")",
"if",
"not",
"egg_path",
":",
"return",
"False",
"return",
"self",
... | https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/utils/external_packages.py#L184-L189 | |
BrewPi/brewpi-script | 85f693ab5e3395cd10cc2d991ebcddc933c7d5cd | brewpiVersion.py | python | AvrInfo.toString | (self) | [] | def toString(self):
if self.version:
return str(self.version)
else:
return "0.0.0" | [
"def",
"toString",
"(",
"self",
")",
":",
"if",
"self",
".",
"version",
":",
"return",
"str",
"(",
"self",
".",
"version",
")",
"else",
":",
"return",
"\"0.0.0\""
] | https://github.com/BrewPi/brewpi-script/blob/85f693ab5e3395cd10cc2d991ebcddc933c7d5cd/brewpiVersion.py#L160-L164 | ||||
ramonhagenaars/jsons | a5150cdd2704e83fe5f8798822a1c901b54dcb1c | jsons/deserializers/default_timedelta.py | python | default_timedelta_deserializer | (obj: float,
cls: type = float,
**kwargs) | return timedelta(seconds=obj) | Deserialize a float to a timedelta instance.
:param obj: the float that is to be deserialized.
:param cls: not used.
:param kwargs: not used.
:return: a ``datetime.timedelta`` instance. | Deserialize a float to a timedelta instance.
:param obj: the float that is to be deserialized.
:param cls: not used.
:param kwargs: not used.
:return: a ``datetime.timedelta`` instance. | [
"Deserialize",
"a",
"float",
"to",
"a",
"timedelta",
"instance",
".",
":",
"param",
"obj",
":",
"the",
"float",
"that",
"is",
"to",
"be",
"deserialized",
".",
":",
"param",
"cls",
":",
"not",
"used",
".",
":",
"param",
"kwargs",
":",
"not",
"used",
"... | def default_timedelta_deserializer(obj: float,
cls: type = float,
**kwargs) -> timedelta:
"""
Deserialize a float to a timedelta instance.
:param obj: the float that is to be deserialized.
:param cls: not used.
:param kwargs: not used.
:return: a ``datetime.timedelta`` instance.
"""
return timedelta(seconds=obj) | [
"def",
"default_timedelta_deserializer",
"(",
"obj",
":",
"float",
",",
"cls",
":",
"type",
"=",
"float",
",",
"*",
"*",
"kwargs",
")",
"->",
"timedelta",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"obj",
")"
] | https://github.com/ramonhagenaars/jsons/blob/a5150cdd2704e83fe5f8798822a1c901b54dcb1c/jsons/deserializers/default_timedelta.py#L4-L14 | |
brendano/tweetmotif | 1b0b1e3a941745cd5a26eba01f554688b7c4b27e | everything_else/djfrontend/django-1.0.2/core/management/__init__.py | python | load_command_class | (app_name, name) | return getattr(__import__('%s.management.commands.%s' % (app_name, name),
{}, {}, ['Command']), 'Command')() | Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate. | Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate. | [
"Given",
"a",
"command",
"name",
"and",
"an",
"application",
"name",
"returns",
"the",
"Command",
"class",
"instance",
".",
"All",
"errors",
"raised",
"by",
"the",
"import",
"process",
"(",
"ImportError",
"AttributeError",
")",
"are",
"allowed",
"to",
"propaga... | def load_command_class(app_name, name):
"""
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
"""
return getattr(__import__('%s.management.commands.%s' % (app_name, name),
{}, {}, ['Command']), 'Command')() | [
"def",
"load_command_class",
"(",
"app_name",
",",
"name",
")",
":",
"return",
"getattr",
"(",
"__import__",
"(",
"'%s.management.commands.%s'",
"%",
"(",
"app_name",
",",
"name",
")",
",",
"{",
"}",
",",
"{",
"}",
",",
"[",
"'Command'",
"]",
")",
",",
... | https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/core/management/__init__.py#L60-L67 | |
liuyubobobo/Play-with-Linear-Algebra | e86175adb908b03756618fbeeeadb448a3551321 | 07-Elemental-Matrices-and-The-Properties-of-Inversion/02-Implement-Inverse-of-Matrix/playLA/Matrix.py | python | Matrix.__mul__ | (self, k) | return Matrix([[e * k for e in self.row_vector(i)]
for i in range(self.row_num())]) | 返回矩阵的数量乘结果: self * k | 返回矩阵的数量乘结果: self * k | [
"返回矩阵的数量乘结果",
":",
"self",
"*",
"k"
] | def __mul__(self, k):
"""返回矩阵的数量乘结果: self * k"""
return Matrix([[e * k for e in self.row_vector(i)]
for i in range(self.row_num())]) | [
"def",
"__mul__",
"(",
"self",
",",
"k",
")",
":",
"return",
"Matrix",
"(",
"[",
"[",
"e",
"*",
"k",
"for",
"e",
"in",
"self",
".",
"row_vector",
"(",
"i",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"row_num",
"(",
")",
")",
"]",
... | https://github.com/liuyubobobo/Play-with-Linear-Algebra/blob/e86175adb908b03756618fbeeeadb448a3551321/07-Elemental-Matrices-and-The-Properties-of-Inversion/02-Implement-Inverse-of-Matrix/playLA/Matrix.py#L56-L59 | |
facebookresearch/EmpatheticDialogues | 9649114c71e1af32189a3973b3598dc311297560 | retrieval_train.py | python | validate | (
epoch,
model,
data_loader,
max_exs=100000,
is_test=False,
nb_candidates=100,
shuffled_str="shuffled",
) | return 10 | [] | def validate(
epoch,
model,
data_loader,
max_exs=100000,
is_test=False,
nb_candidates=100,
shuffled_str="shuffled",
):
model.eval()
examples = 0
eval_start = time.time()
sum_losses = 0
n_losses = 0
correct = 0
all_context = []
all_cands = []
n_skipped = 0
dtype = model.module.opt.dataset_name
for i, ex in enumerate(data_loader):
batch_size = ex[0].size(0)
if dtype == "reddit" and is_test and n_skipped < max_exs:
n_skipped += batch_size
continue
params = [
field.cuda(non_blocking=True)
if opt.cuda
else field
if field is not None
else None
for field in ex
]
ctx, cands = model(*params)
all_context.append(ctx)
all_cands.append(cands)
loss, nb_ok = loss_fn(ctx, cands)
sum_losses += loss
correct += nb_ok
n_losses += 1
examples += batch_size
if examples >= max_exs and dtype == "reddit":
break
n_examples = 0
if len(all_context) > 0:
logging.info("Processing candidate top-K")
all_context = torch.cat(all_context, dim=0) # [:50000] # [N, 2h]
all_cands = torch.cat(all_cands, dim=0) # [:50000] # [N, 2h]
acc_ranges = [1, 3, 10]
n_correct = {r: 0 for r in acc_ranges}
for context, cands in list(
zip(all_context.split(nb_candidates), all_cands.split(nb_candidates))
)[:-1]:
_, top_answers = score_candidates(context, cands)
n_cands = cands.size(0)
gt_index = torch.arange(n_cands, out=top_answers.new(n_cands, 1))
for acc_range in acc_ranges:
n_acc = (top_answers[:, :acc_range] == gt_index).float().sum()
n_correct[acc_range] += n_acc
n_examples += n_cands
accuracies = {r: 100 * n_acc / n_examples for r, n_acc in n_correct.items()}
avg_loss = sum_losses / (n_losses + 0.00001)
avg_acc = 100 * correct / (examples + 0.000001)
valid_time = time.time() - eval_start
logging.info(
f"Valid ({shuffled_str}): Epoch = {epoch:d} | avg loss = {avg_loss:.3f} | "
f"batch P@1 = {avg_acc:.2f} % | "
+ f" | ".join(
f"P@{k},{nb_candidates} = {v:.2f}%" for k, v in accuracies.items()
)
+ f" | valid time = {valid_time:.2f} (s)"
)
return avg_loss
return 10 | [
"def",
"validate",
"(",
"epoch",
",",
"model",
",",
"data_loader",
",",
"max_exs",
"=",
"100000",
",",
"is_test",
"=",
"False",
",",
"nb_candidates",
"=",
"100",
",",
"shuffled_str",
"=",
"\"shuffled\"",
",",
")",
":",
"model",
".",
"eval",
"(",
")",
"... | https://github.com/facebookresearch/EmpatheticDialogues/blob/9649114c71e1af32189a3973b3598dc311297560/retrieval_train.py#L88-L160 | |||
spectacles/CodeComplice | 8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62 | libs/SilverCity/HTMLGenerator.py | python | SimpleHTMLGenerator.__init__ | (self, state_prefix) | [] | def __init__(self, state_prefix):
self.css_classes = {}
for constant in Utils.list_states(state_prefix):
self.css_classes[getattr(ScintillaConstants, constant)] = \
generate_css_name(constant) | [
"def",
"__init__",
"(",
"self",
",",
"state_prefix",
")",
":",
"self",
".",
"css_classes",
"=",
"{",
"}",
"for",
"constant",
"in",
"Utils",
".",
"list_states",
"(",
"state_prefix",
")",
":",
"self",
".",
"css_classes",
"[",
"getattr",
"(",
"ScintillaConsta... | https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/SilverCity/HTMLGenerator.py#L60-L64 | ||||
nadineproject/nadine | c41c8ef7ffe18f1853029c97eecc329039b4af6c | nadine/templatetags/list_tags.py | python | LoopCommaNode.render | (self, context) | [] | def render(self, context):
try:
last = self.for_last.resolve(context)
if last:
return ''
first = self.for_first.resolve(context)
if last and first:
return ''
return ', '
except template.VariableDoesNotExist:
print('does not exist')
return '' | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"last",
"=",
"self",
".",
"for_last",
".",
"resolve",
"(",
"context",
")",
"if",
"last",
":",
"return",
"''",
"first",
"=",
"self",
".",
"for_first",
".",
"resolve",
"(",
"context",
... | https://github.com/nadineproject/nadine/blob/c41c8ef7ffe18f1853029c97eecc329039b4af6c/nadine/templatetags/list_tags.py#L19-L30 | ||||
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/rl/envs/simulated_batch_env.py | python | SimulatedBatchEnv.observ | (self) | return self._observ.read_value() | Access the variable holding the current observation. | Access the variable holding the current observation. | [
"Access",
"the",
"variable",
"holding",
"the",
"current",
"observation",
"."
] | def observ(self):
"""Access the variable holding the current observation."""
return self._observ.read_value() | [
"def",
"observ",
"(",
"self",
")",
":",
"return",
"self",
".",
"_observ",
".",
"read_value",
"(",
")"
] | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/rl/envs/simulated_batch_env.py#L262-L264 | |
datawire/forge | d501be4571dcef5691804c7db7008ee877933c8d | forge/match.py | python | match | (*pattern) | return decorator | [] | def match(*pattern):
def decorator(function):
namespace = inspect.currentframe().f_back.f_locals
return _decorate(namespace, function, pattern)
return decorator | [
"def",
"match",
"(",
"*",
"pattern",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"namespace",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
".",
"f_locals",
"return",
"_decorate",
"(",
"namespace",
",",
"function",
",",
"patt... | https://github.com/datawire/forge/blob/d501be4571dcef5691804c7db7008ee877933c8d/forge/match.py#L518-L522 | |||
timesler/facenet-pytorch | 555aa4bec20ca3e7c2ead14e7e39d5bbce203e4b | models/utils/detect_face.py | python | batched_nms_numpy | (boxes, scores, idxs, threshold, method) | return torch.as_tensor(keep, dtype=torch.long, device=device) | [] | def batched_nms_numpy(boxes, scores, idxs, threshold, method):
device = boxes.device
if boxes.numel() == 0:
return torch.empty((0,), dtype=torch.int64, device=device)
# strategy: in order to perform NMS independently per class.
# we add an offset to all the boxes. The offset is dependent
# only on the class idx, and is large enough so that boxes
# from different classes do not overlap
max_coordinate = boxes.max()
offsets = idxs.to(boxes) * (max_coordinate + 1)
boxes_for_nms = boxes + offsets[:, None]
boxes_for_nms = boxes_for_nms.cpu().numpy()
scores = scores.cpu().numpy()
keep = nms_numpy(boxes_for_nms, scores, threshold, method)
return torch.as_tensor(keep, dtype=torch.long, device=device) | [
"def",
"batched_nms_numpy",
"(",
"boxes",
",",
"scores",
",",
"idxs",
",",
"threshold",
",",
"method",
")",
":",
"device",
"=",
"boxes",
".",
"device",
"if",
"boxes",
".",
"numel",
"(",
")",
"==",
"0",
":",
"return",
"torch",
".",
"empty",
"(",
"(",
... | https://github.com/timesler/facenet-pytorch/blob/555aa4bec20ca3e7c2ead14e7e39d5bbce203e4b/models/utils/detect_face.py#L260-L274 | |||
xlwings/xlwings | 44395c4d18b46f76249279b7d0965e640291499c | xlwings/main.py | python | Book.to_pdf | (self, path=None, include=None, exclude=None, layout=None, exclude_start_string='#', show=False) | Exports the whole Excel workbook or a subset of the sheets to a PDF file.
If you want to print hidden sheets, you will need to list them explicitely under ``include``.
Parameters
----------
path : str or path-like object, default None
Path to the PDF file, defaults to the same name as the workbook, in the same directory.
For unsaved workbooks, it defaults to the current working directory instead.
include : int or str or list, default None
Which sheets to include: provide a selection of sheets in the form of sheet indices (1-based like in Excel)
or sheet names. Can be an int/str for a single sheet or a list of int/str for multiple sheets.
exclude : int or str or list, default None
Which sheets to exclude: provide a selection of sheets in the form of sheet indices (1-based like in Excel)
or sheet names. Can be an int/str for a single sheet or a list of int/str for multiple sheets.
layout : str or path-like object, default None
This argument requires xlwings :guilabel:`PRO`.
Path to a PDF file on which the report will be printed. This is ideal for headers and footers
as well as borderless printing of graphics/artwork. The PDF file either needs to have only
1 page (every report page uses the same layout) or otherwise needs the same amount of pages
as the report (each report page is printed on the respective page in the layout PDF).
.. versionadded:: 0.24.3
exclude_start_string : str, default '#'
Sheet names that start with this character/string will not be printed.
.. versionadded:: 0.24.4
show : bool, default False
Once created, open the PDF file with the default application.
.. versionadded:: 0.24.6
Examples
--------
>>> wb = xw.Book()
>>> wb.sheets[0]['A1'].value = 'PDF'
>>> wb.to_pdf()
See also :meth:`xlwings.Sheet.to_pdf`
.. versionadded:: 0.21.1 | Exports the whole Excel workbook or a subset of the sheets to a PDF file.
If you want to print hidden sheets, you will need to list them explicitely under ``include``. | [
"Exports",
"the",
"whole",
"Excel",
"workbook",
"or",
"a",
"subset",
"of",
"the",
"sheets",
"to",
"a",
"PDF",
"file",
".",
"If",
"you",
"want",
"to",
"print",
"hidden",
"sheets",
"you",
"will",
"need",
"to",
"list",
"them",
"explicitely",
"under",
"inclu... | def to_pdf(self, path=None, include=None, exclude=None, layout=None, exclude_start_string='#', show=False):
"""
Exports the whole Excel workbook or a subset of the sheets to a PDF file.
If you want to print hidden sheets, you will need to list them explicitely under ``include``.
Parameters
----------
path : str or path-like object, default None
Path to the PDF file, defaults to the same name as the workbook, in the same directory.
For unsaved workbooks, it defaults to the current working directory instead.
include : int or str or list, default None
Which sheets to include: provide a selection of sheets in the form of sheet indices (1-based like in Excel)
or sheet names. Can be an int/str for a single sheet or a list of int/str for multiple sheets.
exclude : int or str or list, default None
Which sheets to exclude: provide a selection of sheets in the form of sheet indices (1-based like in Excel)
or sheet names. Can be an int/str for a single sheet or a list of int/str for multiple sheets.
layout : str or path-like object, default None
This argument requires xlwings :guilabel:`PRO`.
Path to a PDF file on which the report will be printed. This is ideal for headers and footers
as well as borderless printing of graphics/artwork. The PDF file either needs to have only
1 page (every report page uses the same layout) or otherwise needs the same amount of pages
as the report (each report page is printed on the respective page in the layout PDF).
.. versionadded:: 0.24.3
exclude_start_string : str, default '#'
Sheet names that start with this character/string will not be printed.
.. versionadded:: 0.24.4
show : bool, default False
Once created, open the PDF file with the default application.
.. versionadded:: 0.24.6
Examples
--------
>>> wb = xw.Book()
>>> wb.sheets[0]['A1'].value = 'PDF'
>>> wb.to_pdf()
See also :meth:`xlwings.Sheet.to_pdf`
.. versionadded:: 0.21.1
"""
report_path = utils.fspath(path)
layout_path = utils.fspath(layout)
if report_path is None:
# fullname won't work if file is stored on OneDrive
filename, extension = os.path.splitext(self.fullname)
directory, _ = os.path.split(self.fullname)
if directory:
report_path = os.path.join(directory, filename + '.pdf')
else:
report_path = filename + '.pdf'
if (include is not None) and (exclude is not None):
raise ValueError("You can only use either 'include' or 'exclude'")
# Hide sheets to exclude them from printing
if isinstance(include, (str, int)):
include = [include]
if isinstance(exclude, (str, int)):
exclude = [exclude]
exclude_by_name = [sheet.index for sheet in self.sheets if sheet.name.startswith(exclude_start_string)]
visibility = {}
if include or exclude or exclude_by_name:
for sheet in self.sheets:
visibility[sheet] = sheet.visible
try:
if include:
for sheet in self.sheets:
if (sheet.name in include) or (sheet.index in include):
sheet.visible = True
else:
sheet.visible = False
if exclude or exclude_by_name:
exclude = [] if exclude is None else exclude
for sheet in self.sheets:
if (sheet.name in exclude) or (sheet.index in exclude) or (sheet.index in exclude_by_name):
sheet.visible = False
self.impl.to_pdf(os.path.realpath(report_path))
except Exception:
raise
finally:
# Reset visibility
if include or exclude or exclude_by_name:
for sheet, tf in visibility.items():
sheet.visible = tf
if layout:
from .pro.reports.pdf import print_on_layout
print_on_layout(report_path=report_path, layout_path=layout_path)
if show:
if sys.platform.startswith('win'):
os.startfile(report_path)
else:
subprocess.run(['open', report_path]) | [
"def",
"to_pdf",
"(",
"self",
",",
"path",
"=",
"None",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"layout",
"=",
"None",
",",
"exclude_start_string",
"=",
"'#'",
",",
"show",
"=",
"False",
")",
":",
"report_path",
"=",
"utils",
"... | https://github.com/xlwings/xlwings/blob/44395c4d18b46f76249279b7d0965e640291499c/xlwings/main.py#L946-L1046 | ||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/hqadmin/views/users.py | python | SuperuserManagement.page_context | (self) | return {
'form': SuperuserManagementForm(*args),
'users': augmented_superusers(),
} | [] | def page_context(self):
# only staff can toggle is_staff
can_toggle_is_staff = self.request.user.is_staff
# render validation errors if rendered after POST
args = [can_toggle_is_staff, self.request.POST] if self.request.POST else [can_toggle_is_staff]
return {
'form': SuperuserManagementForm(*args),
'users': augmented_superusers(),
} | [
"def",
"page_context",
"(",
"self",
")",
":",
"# only staff can toggle is_staff",
"can_toggle_is_staff",
"=",
"self",
".",
"request",
".",
"user",
".",
"is_staff",
"# render validation errors if rendered after POST",
"args",
"=",
"[",
"can_toggle_is_staff",
",",
"self",
... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/hqadmin/views/users.py#L80-L88 | |||
CouchPotato/CouchPotatoServer | 7260c12f72447ddb6f062367c6dfbda03ecd4e9c | libs/suds/client.py | python | ServiceSelector.__getitem__ | (self, name) | return self.__find(name) | Provides selection of the I{service} by name (string) or
index (integer). In cases where only (1) service is defined
or a I{default} has been specified, the request is forwarded
to the L{PortSelector}.
@param name: The name (or index) of a service.
@type name: (int|str)
@return: A L{PortSelector} for the specified service.
@rtype: L{PortSelector}. | Provides selection of the I{service} by name (string) or
index (integer). In cases where only (1) service is defined
or a I{default} has been specified, the request is forwarded
to the L{PortSelector}. | [
"Provides",
"selection",
"of",
"the",
"I",
"{",
"service",
"}",
"by",
"name",
"(",
"string",
")",
"or",
"index",
"(",
"integer",
")",
".",
"In",
"cases",
"where",
"only",
"(",
"1",
")",
"service",
"is",
"defined",
"or",
"a",
"I",
"{",
"default",
"}... | def __getitem__(self, name):
"""
Provides selection of the I{service} by name (string) or
index (integer). In cases where only (1) service is defined
or a I{default} has been specified, the request is forwarded
to the L{PortSelector}.
@param name: The name (or index) of a service.
@type name: (int|str)
@return: A L{PortSelector} for the specified service.
@rtype: L{PortSelector}.
"""
if len(self.__services) == 1:
port = self.__find(0)
return port[name]
default = self.__ds()
if default is not None:
port = default
return port[name]
return self.__find(name) | [
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"if",
"len",
"(",
"self",
".",
"__services",
")",
"==",
"1",
":",
"port",
"=",
"self",
".",
"__find",
"(",
"0",
")",
"return",
"port",
"[",
"name",
"]",
"default",
"=",
"self",
".",
"__ds"... | https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/suds/client.py#L301-L319 | |
kbandla/ImmunityDebugger | 2abc03fb15c8f3ed0914e1175c4d8933977c73e3 | 1.85/Libs/immlib.py | python | Debugger.makeFunctionHashHeuristic | (self, address, compressed = False, followCalls = True, data="") | return FunctionRecognition.makeFunctionHashHeuristic(address, compressed, followCalls) | @type address: DWORD
@param address: address of the function to hash
@type compressed: Boolean
@param compressed: return a compressed base64 representation or the raw data
@type followCalls: Boolean
@param followCalls: follow the first call in a single basic block function
@type data: STRING|LIST
@param data: Name (or list of names) of the .dat file inside the Data folder, where're stored the function
patterns. Use an empty string to use all the files in the Data folder.
@rtype: LIST
@return: the first element is described below and the second is the result of this same function but over the first
call of a single basic block function (if applies), each element is like this:
a base64 representation of the compressed version of each bb hash:
[4 bytes BB(i) start][4 bytes BB(i) 1st edge][4 bytes BB(i) 2nd edge]
0 <= i < BB count
or the same but like a LIST with raw data. | @type address: DWORD
@param address: address of the function to hash | [
"@type",
"address",
":",
"DWORD",
"@param",
"address",
":",
"address",
"of",
"the",
"function",
"to",
"hash"
] | def makeFunctionHashHeuristic(self, address, compressed = False, followCalls = True, data=""):
"""
@type address: DWORD
@param address: address of the function to hash
@type compressed: Boolean
@param compressed: return a compressed base64 representation or the raw data
@type followCalls: Boolean
@param followCalls: follow the first call in a single basic block function
@type data: STRING|LIST
@param data: Name (or list of names) of the .dat file inside the Data folder, where're stored the function
patterns. Use an empty string to use all the files in the Data folder.
@rtype: LIST
@return: the first element is described below and the second is the result of this same function but over the first
call of a single basic block function (if applies), each element is like this:
a base64 representation of the compressed version of each bb hash:
[4 bytes BB(i) start][4 bytes BB(i) 1st edge][4 bytes BB(i) 2nd edge]
0 <= i < BB count
or the same but like a LIST with raw data.
"""
recon = FunctionRecognition(self, data)
return FunctionRecognition.makeFunctionHashHeuristic(address, compressed, followCalls) | [
"def",
"makeFunctionHashHeuristic",
"(",
"self",
",",
"address",
",",
"compressed",
"=",
"False",
",",
"followCalls",
"=",
"True",
",",
"data",
"=",
"\"\"",
")",
":",
"recon",
"=",
"FunctionRecognition",
"(",
"self",
",",
"data",
")",
"return",
"FunctionReco... | https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.85/Libs/immlib.py#L2983-L3007 | |
DasIch/brownie | 8e29a9ceb50622e50b7209690d31203ad42ca164 | brownie/terminal/progress.py | python | ProgressBar.from_string | (cls, string, writer, maxsteps=None, widgets=None) | return cls(rv, writer, maxsteps=maxsteps) | Returns a :class:`ProgressBar` from a string.
The string is used as a progressbar, ``$[a-zA-Z]+`` is substituted with
a widget as defined by `widgets`.
``$`` can be escaped with another ``$`` e.g. ``$$foo`` will not be
substituted.
Initial values as required for the :class:`HintWidget` are given like
this ``$hint:initial``, if the initial value is supposed to contain a
space you have to use a quoted string ``$hint:"foo bar"``; quoted can
be escaped using a backslash.
If you want to provide your own widgets or overwrite existing ones
pass a dictionary mapping the desired names to the widget classes to
this method using the `widgets` keyword argument. The default widgets
are:
+--------------+----------------------------------+-------------------+
| Name | Class | Requires maxsteps |
+==============+==================================+===================+
| `text` | :class:`TextWidget` | No |
+--------------+----------------------------------+-------------------+
| `hint` | :class:`HintWidget` | No |
+--------------+----------------------------------+-------------------+
| `percentage` | :class:`Percentage` | Yes |
+--------------+----------------------------------+-------------------+
| `bar` | :class:`BarWidget` | No |
+--------------+----------------------------------+-------------------+
| `sizedbar` | :class:`PercentageBarWidget` | Yes |
+--------------+----------------------------------+-------------------+
| `step` | :class:`StepWidget` | Yes |
+--------------+----------------------------------+-------------------+
| `time` | :class:`TimeWidget` | No |
+--------------+----------------------------------+-------------------+
| `speed` | :class:`DataTransferSpeedWidget` | No |
+--------------+----------------------------------+-------------------+ | Returns a :class:`ProgressBar` from a string. | [
"Returns",
"a",
":",
"class",
":",
"ProgressBar",
"from",
"a",
"string",
"."
] | def from_string(cls, string, writer, maxsteps=None, widgets=None):
"""
Returns a :class:`ProgressBar` from a string.
The string is used as a progressbar, ``$[a-zA-Z]+`` is substituted with
a widget as defined by `widgets`.
``$`` can be escaped with another ``$`` e.g. ``$$foo`` will not be
substituted.
Initial values as required for the :class:`HintWidget` are given like
this ``$hint:initial``, if the initial value is supposed to contain a
space you have to use a quoted string ``$hint:"foo bar"``; quoted can
be escaped using a backslash.
If you want to provide your own widgets or overwrite existing ones
pass a dictionary mapping the desired names to the widget classes to
this method using the `widgets` keyword argument. The default widgets
are:
+--------------+----------------------------------+-------------------+
| Name | Class | Requires maxsteps |
+==============+==================================+===================+
| `text` | :class:`TextWidget` | No |
+--------------+----------------------------------+-------------------+
| `hint` | :class:`HintWidget` | No |
+--------------+----------------------------------+-------------------+
| `percentage` | :class:`Percentage` | Yes |
+--------------+----------------------------------+-------------------+
| `bar` | :class:`BarWidget` | No |
+--------------+----------------------------------+-------------------+
| `sizedbar` | :class:`PercentageBarWidget` | Yes |
+--------------+----------------------------------+-------------------+
| `step` | :class:`StepWidget` | Yes |
+--------------+----------------------------------+-------------------+
| `time` | :class:`TimeWidget` | No |
+--------------+----------------------------------+-------------------+
| `speed` | :class:`DataTransferSpeedWidget` | No |
+--------------+----------------------------------+-------------------+
"""
default_widgets = {
'text': TextWidget,
'hint': HintWidget,
'percentage': PercentageWidget,
'bar': BarWidget,
'sizedbar': PercentageBarWidget,
'step': StepWidget,
'time': TimeWidget,
'speed': DataTransferSpeedWidget
}
widgets = dict(default_widgets.copy(), **(widgets or {}))
rv = []
for name, initial in parse_progressbar(string):
if name not in widgets:
raise ValueError('widget not found: %s' % name)
if initial:
widget = widgets[name](initial)
else:
widget = widgets[name]()
rv.append(widget)
return cls(rv, writer, maxsteps=maxsteps) | [
"def",
"from_string",
"(",
"cls",
",",
"string",
",",
"writer",
",",
"maxsteps",
"=",
"None",
",",
"widgets",
"=",
"None",
")",
":",
"default_widgets",
"=",
"{",
"'text'",
":",
"TextWidget",
",",
"'hint'",
":",
"HintWidget",
",",
"'percentage'",
":",
"Pe... | https://github.com/DasIch/brownie/blob/8e29a9ceb50622e50b7209690d31203ad42ca164/brownie/terminal/progress.py#L429-L489 | |
aio-libs/aiokafka | ccbcc25e9cd7dd5a980c175197f5315e0953e87c | aiokafka/producer/producer.py | python | AIOKafkaProducer.send_batch | (self, batch, topic, *, partition) | return future | Submit a BatchBuilder for publication.
Arguments:
batch (BatchBuilder): batch object to be published.
topic (str): topic where the batch will be published.
partition (int): partition where this batch will be published.
Returns:
asyncio.Future: object that will be set when the batch is
delivered. | Submit a BatchBuilder for publication. | [
"Submit",
"a",
"BatchBuilder",
"for",
"publication",
"."
] | async def send_batch(self, batch, topic, *, partition):
"""Submit a BatchBuilder for publication.
Arguments:
batch (BatchBuilder): batch object to be published.
topic (str): topic where the batch will be published.
partition (int): partition where this batch will be published.
Returns:
asyncio.Future: object that will be set when the batch is
delivered.
"""
# first make sure the metadata for the topic is available
await self.client._wait_on_metadata(topic)
# We only validate we have the partition in the metadata here
partition = self._partition(topic, partition, None, None, None, None)
# Ensure transaction is started and not committing
if self._txn_manager is not None:
txn_manager = self._txn_manager
if txn_manager.transactional_id is not None and \
not self._txn_manager.is_in_transaction():
raise IllegalOperation(
"Can't send messages while not in transaction")
tp = TopicPartition(topic, partition)
log.debug("Sending batch to %s", tp)
future = await self._message_accumulator.add_batch(
batch, tp, self._request_timeout_ms / 1000)
return future | [
"async",
"def",
"send_batch",
"(",
"self",
",",
"batch",
",",
"topic",
",",
"*",
",",
"partition",
")",
":",
"# first make sure the metadata for the topic is available",
"await",
"self",
".",
"client",
".",
"_wait_on_metadata",
"(",
"topic",
")",
"# We only validate... | https://github.com/aio-libs/aiokafka/blob/ccbcc25e9cd7dd5a980c175197f5315e0953e87c/aiokafka/producer/producer.py#L491-L520 | |
nortikin/sverchok | 7b460f01317c15f2681bfa3e337c5e7346f3711b | nodes/generator/line_mk4.py | python | SvLineNodeMK4.update_sockets | (self, context) | need to do UX transformation before updating node | need to do UX transformation before updating node | [
"need",
"to",
"do",
"UX",
"transformation",
"before",
"updating",
"node"
] | def update_sockets(self, context):
""" need to do UX transformation before updating node"""
def set_hide(sock, status):
if sock.hide_safe != status:
sock.hide_safe = status
if self.direction in (DIRECTION.op, DIRECTION.od):
set_hide(self.inputs['Origin'], False)
set_hide(self.inputs['Direction'], False)
else:
set_hide(self.inputs['Origin'], True)
set_hide(self.inputs['Direction'], True)
if self.length_mode == LENGTH.size:
set_hide(self.inputs['Num'], False)
set_hide(self.inputs['Steps'], True)
set_hide(self.inputs['Size'], False)
self.inputs['Steps'].prop_name = 'step'
elif self.length_mode == LENGTH.number:
set_hide(self.inputs['Num'], False)
set_hide(self.inputs['Steps'], False)
set_hide(self.inputs['Size'], True)
self.inputs['Steps'].prop_name = 'step'
elif self.length_mode == LENGTH.step:
set_hide(self.inputs['Num'], True)
set_hide(self.inputs['Steps'], False)
set_hide(self.inputs['Size'], True)
self.inputs['Steps'].prop_name = ''
elif self.length_mode == LENGTH.step_size:
set_hide(self.inputs['Num'], True)
set_hide(self.inputs['Steps'], False)
set_hide(self.inputs['Size'], False)
self.inputs['Steps'].prop_name = ''
updateNode(self, context) | [
"def",
"update_sockets",
"(",
"self",
",",
"context",
")",
":",
"def",
"set_hide",
"(",
"sock",
",",
"status",
")",
":",
"if",
"sock",
".",
"hide_safe",
"!=",
"status",
":",
"sock",
".",
"hide_safe",
"=",
"status",
"if",
"self",
".",
"direction",
"in",... | https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/nodes/generator/line_mk4.py#L217-L251 | ||
owid/covid-19-data | 936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92 | scripts/src/cowidev/vax/incremental/philippines.py | python | Philippines.read | (self) | return pd.Series(data=self._parse_data()) | [] | def read(self) -> pd.Series:
return pd.Series(data=self._parse_data()) | [
"def",
"read",
"(",
"self",
")",
"->",
"pd",
".",
"Series",
":",
"return",
"pd",
".",
"Series",
"(",
"data",
"=",
"self",
".",
"_parse_data",
"(",
")",
")"
] | https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/vax/incremental/philippines.py#L18-L19 | |||
oracle/oci-python-sdk | 3c1604e4e212008fb6718e2f68cdb5ef71fd5793 | src/oci/core/blockstorage_client_composite_operations.py | python | BlockstorageClientCompositeOperations.create_volume_and_wait_for_state | (self, create_volume_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}) | Calls :py:func:`~oci.core.BlockstorageClient.create_volume` and waits for the :py:class:`~oci.core.models.Volume` acted upon
to enter the given state(s).
:param oci.core.models.CreateVolumeDetails create_volume_details: (required)
Request to create a new volume.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.core.models.Volume.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.core.BlockstorageClient.create_volume`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait | Calls :py:func:`~oci.core.BlockstorageClient.create_volume` and waits for the :py:class:`~oci.core.models.Volume` acted upon
to enter the given state(s). | [
"Calls",
":",
"py",
":",
"func",
":",
"~oci",
".",
"core",
".",
"BlockstorageClient",
".",
"create_volume",
"and",
"waits",
"for",
"the",
":",
"py",
":",
"class",
":",
"~oci",
".",
"core",
".",
"models",
".",
"Volume",
"acted",
"upon",
"to",
"enter",
... | def create_volume_and_wait_for_state(self, create_volume_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.core.BlockstorageClient.create_volume` and waits for the :py:class:`~oci.core.models.Volume` acted upon
to enter the given state(s).
:param oci.core.models.CreateVolumeDetails create_volume_details: (required)
Request to create a new volume.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.core.models.Volume.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.core.BlockstorageClient.create_volume`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_volume(create_volume_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_volume(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e) | [
"def",
"create_volume_and_wait_for_state",
"(",
"self",
",",
"create_volume_details",
",",
"wait_for_states",
"=",
"[",
"]",
",",
"operation_kwargs",
"=",
"{",
"}",
",",
"waiter_kwargs",
"=",
"{",
"}",
")",
":",
"operation_result",
"=",
"self",
".",
"client",
... | https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/core/blockstorage_client_composite_operations.py#L305-L341 | ||
apachecn/AiLearning | 228b62a905a2a9bf6066f65c16d53056b10ec610 | src/py3.x/dl/rnn.py | python | RecurrentLayer.calc_gradient_t | (self, t) | 计算每个时刻t权重的梯度 | 计算每个时刻t权重的梯度 | [
"计算每个时刻t权重的梯度"
] | def calc_gradient_t(self, t):
'''
计算每个时刻t权重的梯度
'''
gradient = np.dot(self.delta_list[t],
self.state_list[t - 1].T)
self.gradient_list[t] = gradient | [
"def",
"calc_gradient_t",
"(",
"self",
",",
"t",
")",
":",
"gradient",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"delta_list",
"[",
"t",
"]",
",",
"self",
".",
"state_list",
"[",
"t",
"-",
"1",
"]",
".",
"T",
")",
"self",
".",
"gradient_list",
"["... | https://github.com/apachecn/AiLearning/blob/228b62a905a2a9bf6066f65c16d53056b10ec610/src/py3.x/dl/rnn.py#L84-L90 | ||
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/_tokenizer.py | python | HTMLTokenizer.selfClosingStartTagState | (self) | return True | [] | def selfClosingStartTagState(self):
data = self.stream.char()
if data == ">":
self.currentToken["selfClosing"] = True
self.emitCurrentToken()
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data":
"unexpected-EOF-after-solidus-in-tag"})
self.stream.unget(data)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-character-after-solidus-in-tag"})
self.stream.unget(data)
self.state = self.beforeAttributeNameState
return True | [
"def",
"selfClosingStartTagState",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"stream",
".",
"char",
"(",
")",
"if",
"data",
"==",
"\">\"",
":",
"self",
".",
"currentToken",
"[",
"\"selfClosing\"",
"]",
"=",
"True",
"self",
".",
"emitCurrentToken",
... | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/_tokenizer.py#L1076-L1092 | |||
gramps-project/gramps | 04d4651a43eb210192f40a9f8c2bad8ee8fa3753 | gramps/gui/plug/_windows.py | python | PluginStatus.__load | (self, obj, list_obj, id_col) | Callback function from the "Load" button | Callback function from the "Load" button | [
"Callback",
"function",
"from",
"the",
"Load",
"button"
] | def __load(self, obj, list_obj, id_col):
""" Callback function from the "Load" button
"""
selection = list_obj.get_selection()
model, node = selection.get_selected()
if not node:
return
idv = model.get_value(node, id_col)
pdata = self.__preg.get_plugin(idv)
self.__pmgr.load_plugin(pdata)
self.__rebuild_load_list() | [
"def",
"__load",
"(",
"self",
",",
"obj",
",",
"list_obj",
",",
"id_col",
")",
":",
"selection",
"=",
"list_obj",
".",
"get_selection",
"(",
")",
"model",
",",
"node",
"=",
"selection",
".",
"get_selected",
"(",
")",
"if",
"not",
"node",
":",
"return",... | https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/plug/_windows.py#L649-L659 | ||
quodlibet/quodlibet | e3099c89f7aa6524380795d325cc14630031886c | quodlibet/qltk/window.py | python | Window.has_close_button | (self) | return True | Returns True in case we are sure that the window decorations include
a close button. | Returns True in case we are sure that the window decorations include
a close button. | [
"Returns",
"True",
"in",
"case",
"we",
"are",
"sure",
"that",
"the",
"window",
"decorations",
"include",
"a",
"close",
"button",
"."
] | def has_close_button(self):
"""Returns True in case we are sure that the window decorations include
a close button.
"""
if self.get_type_hint() == Gdk.WindowTypeHint.NORMAL:
return True
if os.name == "nt":
return True
if sys.platform == "darwin":
return True
if self._header_bar is not None:
return self._header_bar.get_show_close_button()
screen = Gdk.Screen.get_default()
if hasattr(screen, "get_window_manager_name"):
# X11 only
wm_name = screen.get_window_manager_name()
# Older Gnome Shell didn't show close buttons.
# We can't get the version but the GTK+ version is a good guess,
# I guess..
if wm_name == "GNOME Shell" and gtk_version < (3, 18):
return False
return True | [
"def",
"has_close_button",
"(",
"self",
")",
":",
"if",
"self",
".",
"get_type_hint",
"(",
")",
"==",
"Gdk",
".",
"WindowTypeHint",
".",
"NORMAL",
":",
"return",
"True",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"return",
"True",
"if",
"sys",
".",
... | https://github.com/quodlibet/quodlibet/blob/e3099c89f7aa6524380795d325cc14630031886c/quodlibet/qltk/window.py#L195-L222 | |
guildai/guildai | 1665985a3d4d788efc1a3180ca51cc417f71ca78 | guild/op_util.py | python | op_cmd_for_opdef | (opdef, extra_cmd_env=None) | return op_cmd, run_attrs | Returns tuple of op cmd for opdef and associated run attrs.
Some operations require additional information from the opdef,
which is returned as the second element of the two-tuple. | Returns tuple of op cmd for opdef and associated run attrs. | [
"Returns",
"tuple",
"of",
"op",
"cmd",
"for",
"opdef",
"and",
"associated",
"run",
"attrs",
"."
] | def op_cmd_for_opdef(opdef, extra_cmd_env=None):
"""Returns tuple of op cmd for opdef and associated run attrs.
Some operations require additional information from the opdef,
which is returned as the second element of the two-tuple.
"""
cmd_args, run_attrs = _op_cmd_args_and_run_attrs(opdef)
cmd_env = _op_cmd_env(opdef, extra_cmd_env or {})
cmd_flags = _op_cmd_flags(opdef)
cmd_flags_dest = opdef.flags_dest or "args"
op_cmd = op_cmd_lib.OpCmd(cmd_args, cmd_env, cmd_flags, cmd_flags_dest)
return op_cmd, run_attrs | [
"def",
"op_cmd_for_opdef",
"(",
"opdef",
",",
"extra_cmd_env",
"=",
"None",
")",
":",
"cmd_args",
",",
"run_attrs",
"=",
"_op_cmd_args_and_run_attrs",
"(",
"opdef",
")",
"cmd_env",
"=",
"_op_cmd_env",
"(",
"opdef",
",",
"extra_cmd_env",
"or",
"{",
"}",
")",
... | https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/op_util.py#L1043-L1054 | |
jython/jython3 | def4f8ec47cb7a9c799ea4c745f12badf92c5769 | lib-python/3.5.1/tkinter/__init__.py | python | Variable.__del__ | (self) | Unset the variable in Tcl. | Unset the variable in Tcl. | [
"Unset",
"the",
"variable",
"in",
"Tcl",
"."
] | def __del__(self):
"""Unset the variable in Tcl."""
if self._tk is None:
return
if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
self._tk.globalunsetvar(self._name)
if self._tclCommands is not None:
for name in self._tclCommands:
#print '- Tkinter: deleted command', name
self._tk.deletecommand(name)
self._tclCommands = None | [
"def",
"__del__",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tk",
"is",
"None",
":",
"return",
"if",
"self",
".",
"_tk",
".",
"getboolean",
"(",
"self",
".",
"_tk",
".",
"call",
"(",
"\"info\"",
",",
"\"exists\"",
",",
"self",
".",
"_name",
")",
... | https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/tkinter/__init__.py#L244-L254 | ||
wistbean/fxxkpython | 88e16d79d8dd37236ba6ecd0d0ff11d63143968c | vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/packaging/specifiers.py | python | BaseSpecifier.__hash__ | (self) | Returns a hash value for this Specifier like object. | Returns a hash value for this Specifier like object. | [
"Returns",
"a",
"hash",
"value",
"for",
"this",
"Specifier",
"like",
"object",
"."
] | def __hash__(self):
"""
Returns a hash value for this Specifier like object.
""" | [
"def",
"__hash__",
"(",
"self",
")",
":"
] | https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/packaging/specifiers.py#L30-L33 | ||
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txdav/caldav/datastore/scheduling/implicit.py | python | ImplicitScheduler.doImplicitAttendee | (self) | [] | def doImplicitAttendee(self):
# Check SCHEDULE-AGENT
doScheduling = self.checkOrganizerScheduleAgent()
if self.action == "remove":
if self.calendar.hasPropertyValueInAllComponents(Property("STATUS", "CANCELLED")):
log.debug("Implicit - attendee '{attendee}' is removing cancelled UID: '{uid}'", attendee=self.attendee, uid=self.uid)
# Nothing else to do
elif doScheduling:
# If attendee is already marked as declined in all components - nothing to do
attendees = self.calendar.getAttendeeProperties((self.attendee,))
if all([attendee.parameterValue("PARTSTAT", "NEEDS-ACTION") == "DECLINED" for attendee in attendees]):
log.debug("Implicit - attendee '{attendee}' is removing fully declined UID: '{uid}'", attendee=self.attendee, uid=self.uid)
# Nothing else to do
else:
log.debug("Implicit - attendee '{attendee}' is cancelling UID: '{uid}'", attendee=self.attendee, uid=self.uid)
yield self.scheduleCancelWithOrganizer()
else:
log.debug("Implicit - attendee '{attendee}' is removing UID without server scheduling: '{uid}'", attendee=self.attendee, uid=self.uid)
# Nothing else to do
returnValue(None)
else:
# Make sure ORGANIZER is not changed
if self.resource is not None:
self.oldcalendar = (yield self.resource.componentForUser())
oldOrganizer = self.oldcalendar.getOrganizer()
newOrganizer = self.calendar.getOrganizer()
if oldOrganizer != newOrganizer:
log.error("valid-attendee-change: Cannot change ORGANIZER: UID:{uid}", uid=self.uid)
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
(caldav_namespace, "valid-attendee-change"),
"Cannot change organizer",
))
else:
self.oldcalendar = None
# Get the ORGANIZER's current copy of the calendar object
yield self.getOrganizersCopy()
if self.organizer_calendar:
# If Organizer copy exists we cannot allow SCHEDULE-AGENT=CLIENT or NONE
if not doScheduling:
# If an existing resource is present and it does not have SCHEDULE-AGENT=SERVER, then
# try and fix the situation by using the organizer's copy of the event and stripping
# the incoming attendee copy of any SCHEDULE-AGENT=CLIENT components. That should allow
# a fixed version of the data to be stored and proper scheduling to occur.
if self.oldcalendar is not None and not self.oldcalendar.getOrganizerScheduleAgent():
self.oldcalendar = self.organizer_calendar.duplicate()
self.oldcalendar.attendeesView((self.attendee,), onlyScheduleAgentServer=True)
self.calendar.cleanOrganizerScheduleAgent()
doScheduling = True
if not doScheduling:
log.error("valid-attendee-change: Attendee '{attendee}' is not allowed to change SCHEDULE-AGENT on organizer: UID:{uid}", attendee=self.attendeeAddress.record, uid=self.uid)
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
(caldav_namespace, "valid-attendee-change"),
"Cannot alter organizer",
))
# Determine whether the current change is allowed
changeAllowed, doITipReply, changedRids, newCalendar = self.isAttendeeChangeInsignificant()
if changeAllowed:
self.return_calendar = self.calendar = newCalendar
if not changeAllowed:
if self.calendar.hasPropertyValueInAllComponents(Property("STATUS", "CANCELLED")):
log.debug("Attendee '{attendee}' is creating CANCELLED event for mismatched UID: '{uid}' - removing entire event", attendee=self.attendee, uid=self.uid)
self.return_status = ImplicitScheduler.STATUS_ORPHANED_EVENT
returnValue(None)
else:
log.error("valid-attendee-change: Attendee '{attendee}' is not allowed to make an unauthorized change to an organized event: UID:{uid}", attendee=self.attendeeAddress.record, uid=self.uid)
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
(caldav_namespace, "valid-attendee-change"),
"Attendee changes are not allowed",
))
# Check that the return calendar actually has any components left - this can happen if a cancelled
# component is removed and replaced by another cancelled or invalid one
if self.calendar.mainType() is None:
log.debug("Attendee '{attendee}' is replacing CANCELLED event: '{uid}' - removing entire event", attendee=self.attendee, uid=self.uid)
self.return_status = ImplicitScheduler.STATUS_ORPHANED_EVENT
returnValue(None)
if not doITipReply:
log.debug("Implicit - attendee '{attendee}' is updating UID: '{uid}' but change is not significant", attendee=self.attendee, uid=self.uid)
returnValue(self.return_calendar)
log.debug("Attendee '{attendee}' is allowed to update UID: '{uid}' with local organizer '{organizer}'", attendee=self.attendee, uid=self.uid, organizer=self.organizer)
elif isinstance(self.organizerAddress, LocalCalendarUser):
# If Organizer copy does not exist we cannot allow SCHEDULE-AGENT=SERVER
if doScheduling:
# Check to see whether all instances are CANCELLED
if self.calendar.hasPropertyValueInAllComponents(Property("STATUS", "CANCELLED")):
if self.action == "create":
log.debug("Attendee '{attendee}' is creating CANCELLED event for missing UID: '{uid}' - removing entire event", attendee=self.attendee, uid=self.uid)
self.return_status = ImplicitScheduler.STATUS_ORPHANED_CANCELLED_EVENT
returnValue(None)
else:
log.debug("Attendee '{attendee}' is modifying CANCELLED event for missing UID: '{uid}'", attendee=self.attendee, uid=self.uid)
returnValue(None)
else:
# Check to see whether existing event is SCHEDULE-AGENT=CLIENT/NONE
if self.oldcalendar:
oldScheduling = self.oldcalendar.getOrganizerScheduleAgent()
if not oldScheduling:
log.error("valid-attendee-change: Attendee '{attendee}' is not allowed to set SCHEDULE-AGENT=SERVER on organizer: UID:{uid}", attendee=self.attendeeAddress.record, uid=self.uid)
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
(caldav_namespace, "valid-attendee-change"),
"Attendee cannot change organizer state",
))
log.debug("Attendee '{attendee}' is not allowed to update UID: '{uid}' - missing organizer copy - removing entire event", attendee=self.attendee, uid=self.uid)
self.return_status = ImplicitScheduler.STATUS_ORPHANED_EVENT
returnValue(None)
else:
log.debug("Implicit - attendee '{attendee}' is modifying UID without server scheduling: '{uid}'", attendee=self.attendee, uid=self.uid)
# Nothing else to do
returnValue(None)
elif isinstance(self.organizerAddress, InvalidCalendarUser):
# We will allow the attendee to do anything in this case, but we will mark the organizer
# with an schedule-status error
log.debug("Attendee '{attendee}' is allowed to update UID: '{uid}' with invalid organizer '{organizer}'", attendee=self.attendee, uid=self.uid, organizer=self.organizer)
if doScheduling:
self.calendar.setParameterToValueForPropertyWithValue(
"SCHEDULE-STATUS",
iTIPRequestStatus.NO_USER_SUPPORT_CODE,
"ORGANIZER",
self.organizer,
)
returnValue(None)
else:
# We have a remote Organizer of some kind. For now we will allow the Attendee
# to make any change they like as we cannot verify what is reasonable. In reality
# we ought to be comparing the Attendee changes against the attendee's own copy
# and restrict changes based on that when the organizer's copy is not available.
log.debug("Attendee '{attendee}' is allowed to update UID: '{uid}' with remote organizer '{organizer}'", attendee=self.attendee, uid=self.uid, organizer=self.organizer)
changedRids = None
if doScheduling:
log.debug("Implicit - attendee '{attendee}' is updating UID: '{uid}'", attendee=self.attendee, uid=self.uid)
yield self.scheduleWithOrganizer(changedRids)
else:
log.debug("Implicit - attendee '{attendee}' is updating UID without server scheduling: '{uid}'", attendee=self.attendee, uid=self.uid) | [
"def",
"doImplicitAttendee",
"(",
"self",
")",
":",
"# Check SCHEDULE-AGENT",
"doScheduling",
"=",
"self",
".",
"checkOrganizerScheduleAgent",
"(",
")",
"if",
"self",
".",
"action",
"==",
"\"remove\"",
":",
"if",
"self",
".",
"calendar",
".",
"hasPropertyValueInAl... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/caldav/datastore/scheduling/implicit.py#L1414-L1564 | ||||
snowflakedb/snowflake-connector-python | 1659ec6b78930d1f947b4eff985c891af614d86c | src/snowflake/connector/auth_idtoken.py | python | AuthByIdToken.authenticate | (self, authenticator, service_name, account, user, password) | Nothing to do here. | Nothing to do here. | [
"Nothing",
"to",
"do",
"here",
"."
] | def authenticate(self, authenticator, service_name, account, user, password):
"""Nothing to do here."""
pass | [
"def",
"authenticate",
"(",
"self",
",",
"authenticator",
",",
"service_name",
",",
"account",
",",
"user",
",",
"password",
")",
":",
"pass"
] | https://github.com/snowflakedb/snowflake-connector-python/blob/1659ec6b78930d1f947b4eff985c891af614d86c/src/snowflake/connector/auth_idtoken.py#L26-L28 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py | python | TollFreeInstance.address_requirements | (self) | return self._properties['address_requirements'] | :returns: Whether the phone number requires an Address registered with Twilio.
:rtype: TollFreeInstance.AddressRequirement | :returns: Whether the phone number requires an Address registered with Twilio.
:rtype: TollFreeInstance.AddressRequirement | [
":",
"returns",
":",
"Whether",
"the",
"phone",
"number",
"requires",
"an",
"Address",
"registered",
"with",
"Twilio",
".",
":",
"rtype",
":",
"TollFreeInstance",
".",
"AddressRequirement"
] | def address_requirements(self):
"""
:returns: Whether the phone number requires an Address registered with Twilio.
:rtype: TollFreeInstance.AddressRequirement
"""
return self._properties['address_requirements'] | [
"def",
"address_requirements",
"(",
"self",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'address_requirements'",
"]"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py#L364-L369 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/six.py | python | add_metaclass | (metaclass) | return wrapper | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | [
"Class",
"decorator",
"for",
"creating",
"a",
"class",
"with",
"a",
"metaclass",
"."
] | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/six.py#L812-L825 | |
geekan/scrapy-examples | edb1cb116bd6def65a6ef01f953b58eb43e54305 | misc/spider.py | python | CommonSpider.extract_items | (self, sel, rules, item) | [] | def extract_items(self, sel, rules, item):
for nk, nv in rules.items():
if nk in ('__use', '__list'):
continue
if nk not in item:
item[nk] = []
if sel.css(nv):
# item[nk] += [i.extract() for i in sel.css(nv)]
# Without any extra spaces:
item[nk] += self.extract_item(sel.css(nv))
else:
item[nk] = [] | [
"def",
"extract_items",
"(",
"self",
",",
"sel",
",",
"rules",
",",
"item",
")",
":",
"for",
"nk",
",",
"nv",
"in",
"rules",
".",
"items",
"(",
")",
":",
"if",
"nk",
"in",
"(",
"'__use'",
",",
"'__list'",
")",
":",
"continue",
"if",
"nk",
"not",
... | https://github.com/geekan/scrapy-examples/blob/edb1cb116bd6def65a6ef01f953b58eb43e54305/misc/spider.py#L73-L84 | ||||
google/mysql-tools | 02d18542735a528c4a6cca951207393383266bb9 | pylib/http_server.py | python | Request.get | (self, argument_name, default_value='') | return self._qs.get(argument_name, [default_value])[0] | Get one value of a query argument by name. | Get one value of a query argument by name. | [
"Get",
"one",
"value",
"of",
"a",
"query",
"argument",
"by",
"name",
"."
] | def get(self, argument_name, default_value=''):
"""Get one value of a query argument by name."""
return self._qs.get(argument_name, [default_value])[0] | [
"def",
"get",
"(",
"self",
",",
"argument_name",
",",
"default_value",
"=",
"''",
")",
":",
"return",
"self",
".",
"_qs",
".",
"get",
"(",
"argument_name",
",",
"[",
"default_value",
"]",
")",
"[",
"0",
"]"
] | https://github.com/google/mysql-tools/blob/02d18542735a528c4a6cca951207393383266bb9/pylib/http_server.py#L77-L79 | |
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit /tools/sqli/plugins/dbms/mysql/takeover.py | python | Takeover.udfSetRemotePath | (self) | [] | def udfSetRemotePath(self):
self.getVersionFromBanner()
banVer = kb.bannerFp["dbmsVersion"]
if banVer >= "5.0.67":
if self.__plugindir is None:
logger.info("retrieving MySQL plugin directory absolute path")
self.__plugindir = unArrayizeValue(inject.getValue("SELECT @@plugin_dir"))
# On MySQL 5.1 >= 5.1.19 and on any version of MySQL 6.0
if self.__plugindir is None and banVer >= "5.1.19":
logger.info("retrieving MySQL base directory absolute path")
# Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_basedir
self.__basedir = unArrayizeValue(inject.getValue("SELECT @@basedir"))
if re.search("^[\w]\:[\/\\\\]+", (self.__basedir or ""), re.I):
Backend.setOs(OS.WINDOWS)
else:
Backend.setOs(OS.LINUX)
# The DLL must be in C:\Program Files\MySQL\MySQL Server 5.1\lib\plugin
if Backend.isOs(OS.WINDOWS):
self.__plugindir = "%s/lib/plugin" % self.__basedir
else:
self.__plugindir = "%s/lib/mysql/plugin" % self.__basedir
self.__plugindir = ntToPosixSlashes(normalizePath(self.__plugindir))
self.udfRemoteFile = "%s/%s.%s" % (self.__plugindir, self.udfSharedLibName, self.udfSharedLibExt)
# On MySQL 4.1 < 4.1.25 and on MySQL 4.1 >= 4.1.25 with NO plugin_dir set in my.ini configuration file
# On MySQL 5.0 < 5.0.67 and on MySQL 5.0 >= 5.0.67 with NO plugin_dir set in my.ini configuration file
else:
#logger.debug("retrieving MySQL data directory absolute path")
# Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_datadir
#self.__datadir = inject.getValue("SELECT @@datadir")
# NOTE: specifying the relative path as './udf.dll'
# saves in @@datadir on both MySQL 4.1 and MySQL 5.0
self.__datadir = "."
self.__datadir = ntToPosixSlashes(normalizePath(self.__datadir))
# The DLL can be in either C:\WINDOWS, C:\WINDOWS\system,
# C:\WINDOWS\system32, @@basedir\bin or @@datadir
self.udfRemoteFile = "%s/%s.%s" % (self.__datadir, self.udfSharedLibName, self.udfSharedLibExt) | [
"def",
"udfSetRemotePath",
"(",
"self",
")",
":",
"self",
".",
"getVersionFromBanner",
"(",
")",
"banVer",
"=",
"kb",
".",
"bannerFp",
"[",
"\"dbmsVersion\"",
"]",
"if",
"banVer",
">=",
"\"5.0.67\"",
":",
"if",
"self",
".",
"__plugindir",
"is",
"None",
":"... | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/sqli/plugins/dbms/mysql/takeover.py#L35-L82 | ||||
rytilahti/python-miio | b6e53dd16fac77915426e7592e2528b78ef65190 | miio/integrations/vacuum/roidmi/roidmivacuum_miot.py | python | RoidmiConsumableStatus.main_brush_left | (self) | return timedelta(minutes=self.data["main_brush_left_minutes"]) | How long until the main brush should be changed. | How long until the main brush should be changed. | [
"How",
"long",
"until",
"the",
"main",
"brush",
"should",
"be",
"changed",
"."
] | def main_brush_left(self) -> timedelta:
"""How long until the main brush should be changed."""
return timedelta(minutes=self.data["main_brush_left_minutes"]) | [
"def",
"main_brush_left",
"(",
"self",
")",
"->",
"timedelta",
":",
"return",
"timedelta",
"(",
"minutes",
"=",
"self",
".",
"data",
"[",
"\"main_brush_left_minutes\"",
"]",
")"
] | https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/integrations/vacuum/roidmi/roidmivacuum_miot.py#L506-L508 | |
mlflow/mlflow | 364aca7daf0fcee3ec407ae0b1b16d9cb3085081 | mlflow/paddle/__init__.py | python | autolog | (
log_every_n_epoch=1,
log_models=True,
disable=False,
exclusive=False,
silent=False,
) | Enables (or disables) and configures autologging from PaddlePaddle to MLflow.
Autologging is performed when the `fit` method of `paddle.Model`_ is called.
.. _paddle.Model:
https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/Model_en.html
:param log_every_n_epoch: If specified, logs metrics once every `n` epochs. By default, metrics
are logged after every epoch.
:param log_models: If ``True``, trained models are logged as MLflow model artifacts.
If ``False``, trained models are not logged.
:param disable: If ``True``, disables the PaddlePaddle autologging integration.
If ``False``, enables the PaddlePaddle autologging integration.
:param exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
If ``False``, autologged content is logged to the active fluent run,
which may be user-created.
:param silent: If ``True``, suppress all event logs and warnings from MLflow during PyTorch
Lightning autologging. If ``False``, show all events and warnings during
PaddlePaddle autologging.
.. code-block:: python
:caption: Example
import paddle
import mlflow
def show_run_data(run_id):
run = mlflow.get_run(run_id)
print("params: {}".format(run.data.params))
print("metrics: {}".format(run.data.metrics))
client = mlflow.tracking.MlflowClient()
artifacts = [f.path for f in client.list_artifacts(run.info.run_id, "model")]
print("artifacts: {}".format(artifacts))
class LinearRegression(paddle.nn.Layer):
def __init__(self):
super().__init__()
self.fc = paddle.nn.Linear(13, 1)
def forward(self, feature):
return self.fc(feature)
train_dataset = paddle.text.datasets.UCIHousing(mode="train")
eval_dataset = paddle.text.datasets.UCIHousing(mode="test")
model = paddle.Model(LinearRegression())
optim = paddle.optimizer.SGD(learning_rate=1e-2, parameters=model.parameters())
model.prepare(optim, paddle.nn.MSELoss(), paddle.metric.Accuracy())
mlflow.paddle.autolog()
with mlflow.start_run() as run:
model.fit(train_dataset, eval_dataset, batch_size=16, epochs=10)
show_run_data(run.info.run_id)
.. code-block:: text
:caption: Output
params: {
"learning_rate": "0.01",
"optimizer_name": "SGD",
}
metrics: {
"loss": 17.482044,
"step": 25.0,
"acc": 0.0,
"eval_step": 6.0,
"eval_acc": 0.0,
"eval_batch_size": 6.0,
"batch_size": 4.0,
"eval_loss": 24.717455,
}
artifacts: [
"model/MLmodel",
"model/conda.yaml",
"model/model.pdiparams",
"model/model.pdiparams.info",
"model/model.pdmodel",
"model/requirements.txt",
] | Enables (or disables) and configures autologging from PaddlePaddle to MLflow. | [
"Enables",
"(",
"or",
"disables",
")",
"and",
"configures",
"autologging",
"from",
"PaddlePaddle",
"to",
"MLflow",
"."
] | def autolog(
log_every_n_epoch=1,
log_models=True,
disable=False,
exclusive=False,
silent=False,
): # pylint: disable=unused-argument
"""
Enables (or disables) and configures autologging from PaddlePaddle to MLflow.
Autologging is performed when the `fit` method of `paddle.Model`_ is called.
.. _paddle.Model:
https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/Model_en.html
:param log_every_n_epoch: If specified, logs metrics once every `n` epochs. By default, metrics
are logged after every epoch.
:param log_models: If ``True``, trained models are logged as MLflow model artifacts.
If ``False``, trained models are not logged.
:param disable: If ``True``, disables the PaddlePaddle autologging integration.
If ``False``, enables the PaddlePaddle autologging integration.
:param exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
If ``False``, autologged content is logged to the active fluent run,
which may be user-created.
:param silent: If ``True``, suppress all event logs and warnings from MLflow during PyTorch
Lightning autologging. If ``False``, show all events and warnings during
PaddlePaddle autologging.
.. code-block:: python
:caption: Example
import paddle
import mlflow
def show_run_data(run_id):
run = mlflow.get_run(run_id)
print("params: {}".format(run.data.params))
print("metrics: {}".format(run.data.metrics))
client = mlflow.tracking.MlflowClient()
artifacts = [f.path for f in client.list_artifacts(run.info.run_id, "model")]
print("artifacts: {}".format(artifacts))
class LinearRegression(paddle.nn.Layer):
def __init__(self):
super().__init__()
self.fc = paddle.nn.Linear(13, 1)
def forward(self, feature):
return self.fc(feature)
train_dataset = paddle.text.datasets.UCIHousing(mode="train")
eval_dataset = paddle.text.datasets.UCIHousing(mode="test")
model = paddle.Model(LinearRegression())
optim = paddle.optimizer.SGD(learning_rate=1e-2, parameters=model.parameters())
model.prepare(optim, paddle.nn.MSELoss(), paddle.metric.Accuracy())
mlflow.paddle.autolog()
with mlflow.start_run() as run:
model.fit(train_dataset, eval_dataset, batch_size=16, epochs=10)
show_run_data(run.info.run_id)
.. code-block:: text
:caption: Output
params: {
"learning_rate": "0.01",
"optimizer_name": "SGD",
}
metrics: {
"loss": 17.482044,
"step": 25.0,
"acc": 0.0,
"eval_step": 6.0,
"eval_acc": 0.0,
"eval_batch_size": 6.0,
"batch_size": 4.0,
"eval_loss": 24.717455,
}
artifacts: [
"model/MLmodel",
"model/conda.yaml",
"model/model.pdiparams",
"model/model.pdiparams.info",
"model/model.pdmodel",
"model/requirements.txt",
]
"""
import paddle
from mlflow.paddle._paddle_autolog import patched_fit
safe_patch(FLAVOR_NAME, paddle.Model, "fit", patched_fit, manage_run=True) | [
"def",
"autolog",
"(",
"log_every_n_epoch",
"=",
"1",
",",
"log_models",
"=",
"True",
",",
"disable",
"=",
"False",
",",
"exclusive",
"=",
"False",
",",
"silent",
"=",
"False",
",",
")",
":",
"# pylint: disable=unused-argument",
"import",
"paddle",
"from",
"... | https://github.com/mlflow/mlflow/blob/364aca7daf0fcee3ec407ae0b1b16d9cb3085081/mlflow/paddle/__init__.py#L462-L558 | ||
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/compat/dictconfig.py | python | BaseConfigurator.configure_custom | (self, config) | return result | Configure an object with a user-supplied factory. | Configure an object with a user-supplied factory. | [
"Configure",
"an",
"object",
"with",
"a",
"user",
"-",
"supplied",
"factory",
"."
] | def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict((k, config[k]) for k in config if valid_ident(k))
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result | [
"def",
"configure_custom",
"(",
"self",
",",
"config",
")",
":",
"c",
"=",
"config",
".",
"pop",
"(",
"'()'",
")",
"if",
"not",
"hasattr",
"(",
"c",
",",
"'__call__'",
")",
"and",
"hasattr",
"(",
"types",
",",
"'ClassType'",
")",
"and",
"type",
"(",
... | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/compat/dictconfig.py#L256-L268 | |
vojtamolda/autodrome | 3e3aa1198ac96f3c7453f9797b776239801434ae | autodrome/simulator/simulator.py | python | Simulator.setup_steam | (cls, steam_file: Path) | Setup a special Steam file
This little trick of creating 'steam_appid.txt' file with the Steam AppID prevents
SteamAPI_RestartAppIfNecessary(...) API call that would start a new process by forking
the Steam client application over which we would have no control.
Details: https://partner.steamgames.com/doc/api/steam_api#SteamAPI_RestartAppIfNecessary | Setup a special Steam file
This little trick of creating 'steam_appid.txt' file with the Steam AppID prevents
SteamAPI_RestartAppIfNecessary(...) API call that would start a new process by forking
the Steam client application over which we would have no control. | [
"Setup",
"a",
"special",
"Steam",
"file",
"This",
"little",
"trick",
"of",
"creating",
"steam_appid",
".",
"txt",
"file",
"with",
"the",
"Steam",
"AppID",
"prevents",
"SteamAPI_RestartAppIfNecessary",
"(",
"...",
")",
"API",
"call",
"that",
"would",
"start",
"... | def setup_steam(cls, steam_file: Path) -> None:
""" Setup a special Steam file
This little trick of creating 'steam_appid.txt' file with the Steam AppID prevents
SteamAPI_RestartAppIfNecessary(...) API call that would start a new process by forking
the Steam client application over which we would have no control.
Details: https://partner.steamgames.com/doc/api/steam_api#SteamAPI_RestartAppIfNecessary """
print(f"Setting up Steam ID in '{steam_file}'")
steam_file.write_text(str(cls.SteamAppID)) | [
"def",
"setup_steam",
"(",
"cls",
",",
"steam_file",
":",
"Path",
")",
"->",
"None",
":",
"print",
"(",
"f\"Setting up Steam ID in '{steam_file}'\"",
")",
"steam_file",
".",
"write_text",
"(",
"str",
"(",
"cls",
".",
"SteamAppID",
")",
")"
] | https://github.com/vojtamolda/autodrome/blob/3e3aa1198ac96f3c7453f9797b776239801434ae/autodrome/simulator/simulator.py#L96-L104 | ||
misterch0c/shadowbroker | e3a069bea47a2c1009697941ac214adc6f90aa8d | windows/Resources/Python/Core/Lib/multiprocessing/__init__.py | python | Manager | () | return m | Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects. | Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects. | [
"Returns",
"a",
"manager",
"associated",
"with",
"a",
"running",
"server",
"process",
"The",
"managers",
"methods",
"such",
"as",
"Lock",
"()",
"Condition",
"()",
"and",
"Queue",
"()",
"can",
"be",
"used",
"to",
"create",
"shared",
"objects",
"."
] | def Manager():
"""
Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
"""
from multiprocessing.managers import SyncManager
m = SyncManager()
m.start()
return m | [
"def",
"Manager",
"(",
")",
":",
"from",
"multiprocessing",
".",
"managers",
"import",
"SyncManager",
"m",
"=",
"SyncManager",
"(",
")",
"m",
".",
"start",
"(",
")",
"return",
"m"
] | https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/multiprocessing/__init__.py#L38-L48 | |
Alex-Fabbri/Multi-News | f6476d1f114662eb93db32e9b704b7c4fe047217 | code/Hi_MAP/onmt/inputters/inputter.py | python | _getstate | (self) | return dict(self.__dict__, stoi=dict(self.stoi)) | [] | def _getstate(self):
return dict(self.__dict__, stoi=dict(self.stoi)) | [
"def",
"_getstate",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"self",
".",
"__dict__",
",",
"stoi",
"=",
"dict",
"(",
"self",
".",
"stoi",
")",
")"
] | https://github.com/Alex-Fabbri/Multi-News/blob/f6476d1f114662eb93db32e9b704b7c4fe047217/code/Hi_MAP/onmt/inputters/inputter.py#L23-L24 | |||
ubuntu/ubuntu-make | 939668aad1f4c38ffb74cce55b3678f6fded5c71 | umake/decompressor.py | python | Decompressor._one_done | (self, future) | Callback that will be called once one decompress finishes.
(will be wired on the constructor) | Callback that will be called once one decompress finishes. | [
"Callback",
"that",
"will",
"be",
"called",
"once",
"one",
"decompress",
"finishes",
"."
] | def _one_done(self, future):
"""Callback that will be called once one decompress finishes.
(will be wired on the constructor)
"""
result = self.DecompressResult(error=None)
if future.exception():
logger.error("A decompression to {} failed: {}".format(future.tag_dest, future.exception()),
exc_info=future.exception())
result = result._replace(error=str(future.exception()))
logger.info("Decompression to {} finished".format(future.tag_dest))
self._decompressed[future.tag_fd] = result
if len(self._orders) == len(self._decompressed):
self._done() | [
"def",
"_one_done",
"(",
"self",
",",
"future",
")",
":",
"result",
"=",
"self",
".",
"DecompressResult",
"(",
"error",
"=",
"None",
")",
"if",
"future",
".",
"exception",
"(",
")",
":",
"logger",
".",
"error",
"(",
"\"A decompression to {} failed: {}\"",
... | https://github.com/ubuntu/ubuntu-make/blob/939668aad1f4c38ffb74cce55b3678f6fded5c71/umake/decompressor.py#L140-L155 | ||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3cfg.py | python | S3Config.get_project_activity_types | (self) | return self.project.get("activity_types", False) | Use Activity Types in Activities & Projects | Use Activity Types in Activities & Projects | [
"Use",
"Activity",
"Types",
"in",
"Activities",
"&",
"Projects"
] | def get_project_activity_types(self):
"""
Use Activity Types in Activities & Projects
"""
return self.project.get("activity_types", False) | [
"def",
"get_project_activity_types",
"(",
"self",
")",
":",
"return",
"self",
".",
"project",
".",
"get",
"(",
"\"activity_types\"",
",",
"False",
")"
] | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3cfg.py#L5875-L5879 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/Django-1.11.29/django/contrib/admin/checks.py | python | ModelAdminChecks._check_save_on_top | (self, obj) | Check save_on_top is a boolean. | Check save_on_top is a boolean. | [
"Check",
"save_on_top",
"is",
"a",
"boolean",
"."
] | def _check_save_on_top(self, obj):
""" Check save_on_top is a boolean. """
if not isinstance(obj.save_on_top, bool):
return must_be('a boolean', option='save_on_top',
obj=obj, id='admin.E102')
else:
return [] | [
"def",
"_check_save_on_top",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
".",
"save_on_top",
",",
"bool",
")",
":",
"return",
"must_be",
"(",
"'a boolean'",
",",
"option",
"=",
"'save_on_top'",
",",
"obj",
"=",
"obj",
",",
... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/contrib/admin/checks.py#L544-L551 | ||
peterdsharpe/AeroSandbox | ded68b0465f2bfdcaf4bc90abd8c91be0addcaba | aerosandbox/visualization/carpet_plot_utils.py | python | time_limit | (seconds) | Allows you to run a block of code with a timeout. This way, you can sweep through points to make a carpet plot
without getting stuck on a particular point that may not terminate in a reasonable amount of time.
Only runs on Linux!
Usage:
Attempt to set x equal to the value of a complicated function. If it takes longer than 5 seconds, skip it.
>>> try:
>>> with time_limit(5):
>>> x = complicated_function()
>>> except TimeoutException:
>>> x = np.NaN
Args:
seconds: Duration of timeout [seconds]
Returns: | Allows you to run a block of code with a timeout. This way, you can sweep through points to make a carpet plot
without getting stuck on a particular point that may not terminate in a reasonable amount of time. | [
"Allows",
"you",
"to",
"run",
"a",
"block",
"of",
"code",
"with",
"a",
"timeout",
".",
"This",
"way",
"you",
"can",
"sweep",
"through",
"points",
"to",
"make",
"a",
"carpet",
"plot",
"without",
"getting",
"stuck",
"on",
"a",
"particular",
"point",
"that"... | def time_limit(seconds):
"""
Allows you to run a block of code with a timeout. This way, you can sweep through points to make a carpet plot
without getting stuck on a particular point that may not terminate in a reasonable amount of time.
Only runs on Linux!
Usage:
Attempt to set x equal to the value of a complicated function. If it takes longer than 5 seconds, skip it.
>>> try:
>>> with time_limit(5):
>>> x = complicated_function()
>>> except TimeoutException:
>>> x = np.NaN
Args:
seconds: Duration of timeout [seconds]
Returns:
"""
def signal_handler(signum, frame):
raise TimeoutError()
try:
signal.signal(signal.SIGALRM, signal_handler)
except AttributeError:
raise OSError("signal.SIGALRM could not be found. This is probably because you're not using Linux.")
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0) | [
"def",
"time_limit",
"(",
"seconds",
")",
":",
"def",
"signal_handler",
"(",
"signum",
",",
"frame",
")",
":",
"raise",
"TimeoutError",
"(",
")",
"try",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGALRM",
",",
"signal_handler",
")",
"except",
"A... | https://github.com/peterdsharpe/AeroSandbox/blob/ded68b0465f2bfdcaf4bc90abd8c91be0addcaba/aerosandbox/visualization/carpet_plot_utils.py#L13-L46 | ||
OpenCobolIDE/OpenCobolIDE | c78d0d335378e5fe0a5e74f53c19b68b55e85388 | open_cobol_ide/extlibs/pyqode/core/modes/matcher.py | python | SymbolMatcherMode._match_left | (self, symbol, current_block, i, cpt) | return False | [] | def _match_left(self, symbol, current_block, i, cpt):
while current_block.isValid():
data = get_block_symbol_data(self.editor, current_block)
parentheses = data[symbol]
for j in range(i, len(parentheses)):
info = parentheses[j]
if info.character == self.SYMBOLS[symbol][OPEN]:
cpt += 1
continue
if info.character == self.SYMBOLS[symbol][CLOSE] and cpt == 0:
self._create_decoration(current_block.position() +
info.position)
return True
elif info.character == self.SYMBOLS[symbol][CLOSE]:
cpt -= 1
current_block = current_block.next()
i = 0
return False | [
"def",
"_match_left",
"(",
"self",
",",
"symbol",
",",
"current_block",
",",
"i",
",",
"cpt",
")",
":",
"while",
"current_block",
".",
"isValid",
"(",
")",
":",
"data",
"=",
"get_block_symbol_data",
"(",
"self",
".",
"editor",
",",
"current_block",
")",
... | https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/pyqode/core/modes/matcher.py#L187-L204 | |||
ANSSI-FR/polichombr | e2dc3874ae3d78c3b496e9656c9a6d1b88ae91e1 | polichombr/controllers/user.py | python | UserController.set_name | (user, name) | return True | Set's the user's complete name. | Set's the user's complete name. | [
"Set",
"s",
"the",
"user",
"s",
"complete",
"name",
"."
] | def set_name(user, name):
"""
Set's the user's complete name.
"""
user.completename = name
db.session.commit()
return True | [
"def",
"set_name",
"(",
"user",
",",
"name",
")",
":",
"user",
".",
"completename",
"=",
"name",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"True"
] | https://github.com/ANSSI-FR/polichombr/blob/e2dc3874ae3d78c3b496e9656c9a6d1b88ae91e1/polichombr/controllers/user.py#L128-L134 | |
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/models/v2alpha1_horizontal_pod_autoscaler_status.py | python | V2alpha1HorizontalPodAutoscalerStatus.last_scale_time | (self, last_scale_time) | Sets the last_scale_time of this V2alpha1HorizontalPodAutoscalerStatus.
lastScaleTime is the last time the HorizontalPodAutoscaler scaled the number of pods, used by the autoscaler to control how often the number of pods is changed.
:param last_scale_time: The last_scale_time of this V2alpha1HorizontalPodAutoscalerStatus.
:type: datetime | Sets the last_scale_time of this V2alpha1HorizontalPodAutoscalerStatus.
lastScaleTime is the last time the HorizontalPodAutoscaler scaled the number of pods, used by the autoscaler to control how often the number of pods is changed. | [
"Sets",
"the",
"last_scale_time",
"of",
"this",
"V2alpha1HorizontalPodAutoscalerStatus",
".",
"lastScaleTime",
"is",
"the",
"last",
"time",
"the",
"HorizontalPodAutoscaler",
"scaled",
"the",
"number",
"of",
"pods",
"used",
"by",
"the",
"autoscaler",
"to",
"control",
... | def last_scale_time(self, last_scale_time):
"""
Sets the last_scale_time of this V2alpha1HorizontalPodAutoscalerStatus.
lastScaleTime is the last time the HorizontalPodAutoscaler scaled the number of pods, used by the autoscaler to control how often the number of pods is changed.
:param last_scale_time: The last_scale_time of this V2alpha1HorizontalPodAutoscalerStatus.
:type: datetime
"""
self._last_scale_time = last_scale_time | [
"def",
"last_scale_time",
"(",
"self",
",",
"last_scale_time",
")",
":",
"self",
".",
"_last_scale_time",
"=",
"last_scale_time"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v2alpha1_horizontal_pod_autoscaler_status.py#L170-L179 | ||
cherrypy/cherrypy | a7983fe61f7237f2354915437b04295694100372 | cherrypy/_cpreqbody.py | python | unquote_plus | (bs) | return b''.join(atoms) | Bytes version of urllib.parse.unquote_plus. | Bytes version of urllib.parse.unquote_plus. | [
"Bytes",
"version",
"of",
"urllib",
".",
"parse",
".",
"unquote_plus",
"."
] | def unquote_plus(bs):
"""Bytes version of urllib.parse.unquote_plus."""
bs = bs.replace(b'+', b' ')
atoms = bs.split(b'%')
for i in range(1, len(atoms)):
item = atoms[i]
try:
pct = int(item[:2], 16)
atoms[i] = bytes([pct]) + item[2:]
except ValueError:
pass
return b''.join(atoms) | [
"def",
"unquote_plus",
"(",
"bs",
")",
":",
"bs",
"=",
"bs",
".",
"replace",
"(",
"b'+'",
",",
"b' '",
")",
"atoms",
"=",
"bs",
".",
"split",
"(",
"b'%'",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"atoms",
")",
")",
":",
"ite... | https://github.com/cherrypy/cherrypy/blob/a7983fe61f7237f2354915437b04295694100372/cherrypy/_cpreqbody.py#L127-L138 | |
naver/claf | 6f45b1ecca0aa2b3bcf99e79c9cb2c915ba0bf3b | claf/model/semantic_parsing/mixin.py | python | WikiSQL.make_metrics | (self, predictions) | return metrics | aggregator, select_column, conditions accuracy | aggregator, select_column, conditions accuracy | [
"aggregator",
"select_column",
"conditions",
"accuracy"
] | def make_metrics(self, predictions):
""" aggregator, select_column, conditions accuracy """
agg_accuracy, sel_accuracy, conds_accuracy = 0, 0, 0
for index, pred in predictions.items():
target = self._dataset.get_ground_truth(index)
# Aggregator, Select_Column, Conditions
agg_acc = 1 if pred["query"]["agg"] == target["agg_idx"] else 0
sel_acc = 1 if pred["query"]["sel"] == target["sel_idx"] else 0
pred_conds = pred["query"]["conds"]
string_set_pred_conds = set(["#".join(map(str, cond)).lower() for cond in pred_conds])
target_conds = [
[target["conds_col"][i], target["conds_op"][i], target["conds_val_str"][i]]
for i in range(target["conds_num"])
]
string_set_target_conds = set(
["#".join(map(str, cond)).lower() for cond in target_conds]
)
conds_acc = (
1 if string_set_pred_conds == string_set_target_conds else 0
) # not matter in order
agg_accuracy += agg_acc
sel_accuracy += sel_acc
conds_accuracy += conds_acc
total_count = len(self._dataset)
agg_accuracy = 100.0 * agg_accuracy / total_count
sel_accuracy = 100.0 * sel_accuracy / total_count
conds_accuracy = 100.0 * conds_accuracy / total_count
metrics = {
"agg_accuracy": agg_accuracy,
"sel_accuracy": sel_accuracy,
"conds_accuracy": conds_accuracy,
}
self.write_predictions(predictions)
wikisql_official_metrics = self._make_metrics_with_official(predictions)
metrics.update(wikisql_official_metrics)
return metrics | [
"def",
"make_metrics",
"(",
"self",
",",
"predictions",
")",
":",
"agg_accuracy",
",",
"sel_accuracy",
",",
"conds_accuracy",
"=",
"0",
",",
"0",
",",
"0",
"for",
"index",
",",
"pred",
"in",
"predictions",
".",
"items",
"(",
")",
":",
"target",
"=",
"s... | https://github.com/naver/claf/blob/6f45b1ecca0aa2b3bcf99e79c9cb2c915ba0bf3b/claf/model/semantic_parsing/mixin.py#L22-L68 | |
zestedesavoir/zds-site | 2ba922223c859984a413cc6c108a8aa4023b113e | zds/utils/templatetags/date.py | python | format_date | (value, small=False) | return date_formatter(value, tooltip=False, small=small) | Format a date to an human readable string.
If ``value`` is in future it is replaced by "In the future". | Format a date to an human readable string.
If ``value`` is in future it is replaced by "In the future". | [
"Format",
"a",
"date",
"to",
"an",
"human",
"readable",
"string",
".",
"If",
"value",
"is",
"in",
"future",
"it",
"is",
"replaced",
"by",
"In",
"the",
"future",
"."
] | def format_date(value, small=False):
"""
Format a date to an human readable string.
If ``value`` is in future it is replaced by "In the future".
"""
return date_formatter(value, tooltip=False, small=small) | [
"def",
"format_date",
"(",
"value",
",",
"small",
"=",
"False",
")",
":",
"return",
"date_formatter",
"(",
"value",
",",
"tooltip",
"=",
"False",
",",
"small",
"=",
"small",
")"
] | https://github.com/zestedesavoir/zds-site/blob/2ba922223c859984a413cc6c108a8aa4023b113e/zds/utils/templatetags/date.py#L54-L59 | |
quentinhardy/odat | 364b94cc662dcbb95a0b28880c6a71ddfc66dd6b | Output.py | python | Output.unknownNews | (self,m) | print unknow news | print unknow news | [
"print",
"unknow",
"news"
] | def unknownNews(self,m):
'''
print unknow news
'''
m = m.encode(encoding='UTF-8',errors='ignore')
formatMesg = '[+] {0}'.format(m.decode())
if self.noColor == True or TERMCOLOR_AVAILABLE == False: print(formatMesg)
else : print(colored(formatMesg, 'yellow',attrs=['bold'])) | [
"def",
"unknownNews",
"(",
"self",
",",
"m",
")",
":",
"m",
"=",
"m",
".",
"encode",
"(",
"encoding",
"=",
"'UTF-8'",
",",
"errors",
"=",
"'ignore'",
")",
"formatMesg",
"=",
"'[+] {0}'",
".",
"format",
"(",
"m",
".",
"decode",
"(",
")",
")",
"if",
... | https://github.com/quentinhardy/odat/blob/364b94cc662dcbb95a0b28880c6a71ddfc66dd6b/Output.py#L81-L88 | ||
missionpinball/mpf | 8e6b74cff4ba06d2fec9445742559c1068b88582 | mpf/platforms/system11.py | python | System11OverlayPlatform.a_side_busy | (self) | return self.drivers_holding_a_side or self.a_side_done_time > self.machine.clock.get_time() or self.a_side_queue | Return if A side cannot be switches off right away. | Return if A side cannot be switches off right away. | [
"Return",
"if",
"A",
"side",
"cannot",
"be",
"switches",
"off",
"right",
"away",
"."
] | def a_side_busy(self):
"""Return if A side cannot be switches off right away."""
return self.drivers_holding_a_side or self.a_side_done_time > self.machine.clock.get_time() or self.a_side_queue | [
"def",
"a_side_busy",
"(",
"self",
")",
":",
"return",
"self",
".",
"drivers_holding_a_side",
"or",
"self",
".",
"a_side_done_time",
">",
"self",
".",
"machine",
".",
"clock",
".",
"get_time",
"(",
")",
"or",
"self",
".",
"a_side_queue"
] | https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/platforms/system11.py#L64-L66 | |
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | thirdparty_libs/requests/hooks.py | python | dispatch_hook | (key, hooks, hook_data, **kwargs) | return hook_data | Dispatches a hook dictionary on a given piece of data. | Dispatches a hook dictionary on a given piece of data. | [
"Dispatches",
"a",
"hook",
"dictionary",
"on",
"a",
"given",
"piece",
"of",
"data",
"."
] | def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or dict()
if key in hooks:
hooks = hooks.get(key)
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data | [
"def",
"dispatch_hook",
"(",
"key",
",",
"hooks",
",",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
":",
"hooks",
"=",
"hooks",
"or",
"dict",
"(",
")",
"if",
"key",
"in",
"hooks",
":",
"hooks",
"=",
"hooks",
".",
"get",
"(",
"key",
")",
"if",
"hasa... | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/requests/hooks.py#L29-L45 | |
benknight/hue-alfred-workflow | 4447ba61116caf4a448b50c4bfb866565d66d81e | logic/packages/requests/adapters.py | python | HTTPAdapter.build_response | (self, req, resp) | return response | Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object. | Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>` | [
"Builds",
"a",
":",
"class",
":",
"Response",
"<requests",
".",
"Response",
">",
"object",
"from",
"a",
"urllib3",
"response",
".",
"This",
"should",
"not",
"be",
"called",
"from",
"user",
"code",
"and",
"is",
"only",
"exposed",
"for",
"use",
"when",
"su... | def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
"""
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response | [
"def",
"build_response",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"response",
"=",
"Response",
"(",
")",
"# Fallback to None if there's no status_code, for whatever reason.",
"response",
".",
"status_code",
"=",
"getattr",
"(",
"resp",
",",
"'status'",
",",
... | https://github.com/benknight/hue-alfred-workflow/blob/4447ba61116caf4a448b50c4bfb866565d66d81e/logic/packages/requests/adapters.py#L139-L173 | |
quantumlib/Cirq | 89f88b01d69222d3f1ec14d649b7b3a85ed9211f | cirq-ionq/cirq_ionq/results.py | python | SimulatorResult.probabilities | (self, key: Optional[str] = None) | return result | Returns the probabilities of the measurement results.
If a key parameter is supplied, these are the probabilities for the measurement results for
the qubits measured by the measurement gate with that key. If no key is given, these
are the measurement results from measuring all qubits in the circuit.
The key in the returned dictionary is the computational basis state measured for the
qubits that have been measured. This is expressed in big-endian form. For example, if
no measurement key is supplied and all qubits are measured, the key in this returned dict
has a bit string where the `cirq.LineQubit`s are expressed in the order:
(cirq.LineQubit(0), cirq.LineQubit(1), ..., cirq.LineQubit(n-1))
In the case where only `r` qubits are measured corresponding to targets t_0, t_1,...t_{r-1},
the bit string corresponds to the order
(cirq.LineQubit(t_0), cirq.LineQubit(t_1), ... cirq.LineQubit(t_{r-1}))
The value is the probability that the corresponding bit string occurred.
See `to_cirq_result` to convert to a `cirq.Result`. | Returns the probabilities of the measurement results. | [
"Returns",
"the",
"probabilities",
"of",
"the",
"measurement",
"results",
"."
] | def probabilities(self, key: Optional[str] = None) -> Dict[int, float]:
"""Returns the probabilities of the measurement results.
If a key parameter is supplied, these are the probabilities for the measurement results for
the qubits measured by the measurement gate with that key. If no key is given, these
are the measurement results from measuring all qubits in the circuit.
The key in the returned dictionary is the computational basis state measured for the
qubits that have been measured. This is expressed in big-endian form. For example, if
no measurement key is supplied and all qubits are measured, the key in this returned dict
has a bit string where the `cirq.LineQubit`s are expressed in the order:
(cirq.LineQubit(0), cirq.LineQubit(1), ..., cirq.LineQubit(n-1))
In the case where only `r` qubits are measured corresponding to targets t_0, t_1,...t_{r-1},
the bit string corresponds to the order
(cirq.LineQubit(t_0), cirq.LineQubit(t_1), ... cirq.LineQubit(t_{r-1}))
The value is the probability that the corresponding bit string occurred.
See `to_cirq_result` to convert to a `cirq.Result`.
"""
if key is None:
return self._probabilities
if not key in self._measurement_dict:
raise ValueError(
f'Measurement key {key} is not a key for a measurement gate in the'
'circuit that produced these results.'
)
targets = self._measurement_dict[key]
result: Dict[int, float] = dict()
for value, probability in self._probabilities.items():
bits = [(value >> (self.num_qubits() - target - 1)) & 1 for target in targets]
bit_value = sum(bit * (1 << i) for i, bit in enumerate(bits[::-1]))
if bit_value in result:
result[bit_value] += probability
else:
result[bit_value] = probability
return result | [
"def",
"probabilities",
"(",
"self",
",",
"key",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"int",
",",
"float",
"]",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"_probabilities",
"if",
"not",
"key",
"in"... | https://github.com/quantumlib/Cirq/blob/89f88b01d69222d3f1ec14d649b7b3a85ed9211f/cirq-ionq/cirq_ionq/results.py#L191-L227 | |
inspurer/WorkAttendanceSystem | 1221e2d67bdf5bb15fe99517cc3ded58ccb066df | V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/lockfile/__init__.py | python | locked | (path, timeout=None) | return decor | Decorator which enables locks for decorated function.
Arguments:
- path: path for lockfile.
- timeout (optional): Timeout for acquiring lock.
Usage:
@locked('/var/run/myname', timeout=0)
def myname(...):
... | Decorator which enables locks for decorated function. | [
"Decorator",
"which",
"enables",
"locks",
"for",
"decorated",
"function",
"."
] | def locked(path, timeout=None):
"""Decorator which enables locks for decorated function.
Arguments:
- path: path for lockfile.
- timeout (optional): Timeout for acquiring lock.
Usage:
@locked('/var/run/myname', timeout=0)
def myname(...):
...
"""
def decor(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock = FileLock(path, timeout=timeout)
lock.acquire()
try:
return func(*args, **kwargs)
finally:
lock.release()
return wrapper
return decor | [
"def",
"locked",
"(",
"path",
",",
"timeout",
"=",
"None",
")",
":",
"def",
"decor",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lock",
"=",
"F... | https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/lockfile/__init__.py#L315-L337 | |
tryton/trytond | 9fc68232536d0707b73614eab978bd6f813e3677 | trytond/ir/model.py | python | ModelButton.get_view_attributes | (cls, model, name) | return attributes | Return the view attributes of the named button of the model | Return the view attributes of the named button of the model | [
"Return",
"the",
"view",
"attributes",
"of",
"the",
"named",
"button",
"of",
"the",
"model"
] | def get_view_attributes(cls, model, name):
"Return the view attributes of the named button of the model"
key = (model, name, Transaction().language)
attributes = cls._view_attributes_cache.get(key)
if attributes is not None:
return attributes
buttons = cls.search([
('model.model', '=', model),
('name', '=', name),
])
if not buttons:
attributes = {}
else:
button, = buttons
attributes = {
'string': button.string,
'help': button.help,
'confirm': button.confirm,
}
cls._view_attributes_cache.set(key, attributes)
return attributes | [
"def",
"get_view_attributes",
"(",
"cls",
",",
"model",
",",
"name",
")",
":",
"key",
"=",
"(",
"model",
",",
"name",
",",
"Transaction",
"(",
")",
".",
"language",
")",
"attributes",
"=",
"cls",
".",
"_view_attributes_cache",
".",
"get",
"(",
"key",
"... | https://github.com/tryton/trytond/blob/9fc68232536d0707b73614eab978bd6f813e3677/trytond/ir/model.py#L981-L1001 | |
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-modules/twisted/twisted/protocols/htb.py | python | IBucketFilter.getBucketFor | (*somethings, **some_kw) | I'll give you a bucket for something.
@returntype: L{Bucket} | I'll give you a bucket for something. | [
"I",
"ll",
"give",
"you",
"a",
"bucket",
"for",
"something",
"."
] | def getBucketFor(*somethings, **some_kw):
"""I'll give you a bucket for something.
@returntype: L{Bucket}
""" | [
"def",
"getBucketFor",
"(",
"*",
"somethings",
",",
"*",
"*",
"some_kw",
")",
":"
] | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/protocols/htb.py#L100-L104 | ||
bendmorris/static-python | 2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473 | Lib/idlelib/rpc.py | python | RPCServer.handle_error | (self, request, client_address) | Override TCPServer method
Error message goes to __stderr__. No error message if exiting
normally or socket raised EOF. Other exceptions not handled in
server code will cause os._exit. | Override TCPServer method | [
"Override",
"TCPServer",
"method"
] | def handle_error(self, request, client_address):
"""Override TCPServer method
Error message goes to __stderr__. No error message if exiting
normally or socket raised EOF. Other exceptions not handled in
server code will cause os._exit.
"""
try:
raise
except SystemExit:
raise
except:
erf = sys.__stderr__
print('\n' + '-'*40, file=erf)
print('Unhandled server exception!', file=erf)
print('Thread: %s' % threading.current_thread().name, file=erf)
print('Client Address: ', client_address, file=erf)
print('Request: ', repr(request), file=erf)
traceback.print_exc(file=erf)
print('\n*** Unrecoverable, server exiting!', file=erf)
print('-'*40, file=erf)
os._exit(0) | [
"def",
"handle_error",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"try",
":",
"raise",
"except",
"SystemExit",
":",
"raise",
"except",
":",
"erf",
"=",
"sys",
".",
"__stderr__",
"print",
"(",
"'\\n'",
"+",
"'-'",
"*",
"40",
",",
"fil... | https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/idlelib/rpc.py#L94-L116 | ||
qibinlou/SinaWeibo-Emotion-Classification | f336fc104abd68b0ec4180fe2ed80fafe49cb790 | nltk/corpus/reader/tagged.py | python | TaggedCorpusReader.tagged_paras | (self, fileids=None, simplify_tags=False) | return concat([TaggedCorpusView(fileid, enc,
True, True, True,
self._sep, self._word_tokenizer,
self._sent_tokenizer,
self._para_block_reader,
tag_mapping_function)
for (fileid, enc) in self.abspaths(fileids, True)]) | :return: the given file(s) as a list of
paragraphs, each encoded as a list of sentences, which are
in turn encoded as lists of ``(word,tag)`` tuples.
:rtype: list(list(list(tuple(str,str)))) | :return: the given file(s) as a list of
paragraphs, each encoded as a list of sentences, which are
in turn encoded as lists of ``(word,tag)`` tuples.
:rtype: list(list(list(tuple(str,str)))) | [
":",
"return",
":",
"the",
"given",
"file",
"(",
"s",
")",
"as",
"a",
"list",
"of",
"paragraphs",
"each",
"encoded",
"as",
"a",
"list",
"of",
"sentences",
"which",
"are",
"in",
"turn",
"encoded",
"as",
"lists",
"of",
"(",
"word",
"tag",
")",
"tuples"... | def tagged_paras(self, fileids=None, simplify_tags=False):
"""
:return: the given file(s) as a list of
paragraphs, each encoded as a list of sentences, which are
in turn encoded as lists of ``(word,tag)`` tuples.
:rtype: list(list(list(tuple(str,str))))
"""
if simplify_tags:
tag_mapping_function = self._tag_mapping_function
else:
tag_mapping_function = None
return concat([TaggedCorpusView(fileid, enc,
True, True, True,
self._sep, self._word_tokenizer,
self._sent_tokenizer,
self._para_block_reader,
tag_mapping_function)
for (fileid, enc) in self.abspaths(fileids, True)]) | [
"def",
"tagged_paras",
"(",
"self",
",",
"fileids",
"=",
"None",
",",
"simplify_tags",
"=",
"False",
")",
":",
"if",
"simplify_tags",
":",
"tag_mapping_function",
"=",
"self",
".",
"_tag_mapping_function",
"else",
":",
"tag_mapping_function",
"=",
"None",
"retur... | https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/corpus/reader/tagged.py#L152-L169 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/asymptotic/term_monoid.py | python | GenericTermMonoid.term_monoid | (self, type) | return TermMonoid(type,
growth_group=self.growth_group,
coefficient_ring=self.coefficient_ring) | r"""
Return the term monoid of specified ``type``.
INPUT:
- ``type`` -- 'O' or 'exact', or an instance of an existing
term monoid.
See :class:`~sage.rings.asymptotic.term_monoid.TermMonoidFactory`
for more details.
OUTPUT:
A term monoid object derived from
:class:`~sage.rings.asymptotic.term_monoid.GenericTermMonoid`.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import DefaultTermMonoidFactory as TermMonoid
sage: E = TermMonoid('exact', GrowthGroup('x^ZZ'), ZZ); E
Exact Term Monoid x^ZZ with coefficients in Integer Ring
sage: E.term_monoid('O')
O-Term Monoid x^ZZ with implicit coefficients in Integer Ring
TESTS::
sage: E.term_monoid('exact') is E
True | r"""
Return the term monoid of specified ``type``. | [
"r",
"Return",
"the",
"term",
"monoid",
"of",
"specified",
"type",
"."
] | def term_monoid(self, type):
r"""
Return the term monoid of specified ``type``.
INPUT:
- ``type`` -- 'O' or 'exact', or an instance of an existing
term monoid.
See :class:`~sage.rings.asymptotic.term_monoid.TermMonoidFactory`
for more details.
OUTPUT:
A term monoid object derived from
:class:`~sage.rings.asymptotic.term_monoid.GenericTermMonoid`.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import DefaultTermMonoidFactory as TermMonoid
sage: E = TermMonoid('exact', GrowthGroup('x^ZZ'), ZZ); E
Exact Term Monoid x^ZZ with coefficients in Integer Ring
sage: E.term_monoid('O')
O-Term Monoid x^ZZ with implicit coefficients in Integer Ring
TESTS::
sage: E.term_monoid('exact') is E
True
"""
TermMonoid = self.term_monoid_factory
return TermMonoid(type,
growth_group=self.growth_group,
coefficient_ring=self.coefficient_ring) | [
"def",
"term_monoid",
"(",
"self",
",",
"type",
")",
":",
"TermMonoid",
"=",
"self",
".",
"term_monoid_factory",
"return",
"TermMonoid",
"(",
"type",
",",
"growth_group",
"=",
"self",
".",
"growth_group",
",",
"coefficient_ring",
"=",
"self",
".",
"coefficient... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/asymptotic/term_monoid.py#L1539-L1572 | |
nipy/nipype | cd4c34d935a43812d1756482fdc4034844e485b8 | nipype/pipeline/engine/workflows.py | python | Workflow._create_flat_graph | (self) | return workflowcopy._graph | Make a simple DAG where no node is a workflow. | Make a simple DAG where no node is a workflow. | [
"Make",
"a",
"simple",
"DAG",
"where",
"no",
"node",
"is",
"a",
"workflow",
"."
] | def _create_flat_graph(self):
"""Make a simple DAG where no node is a workflow."""
logger.debug("Creating flat graph for workflow: %s", self.name)
workflowcopy = deepcopy(self)
workflowcopy._generate_flatgraph()
return workflowcopy._graph | [
"def",
"_create_flat_graph",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Creating flat graph for workflow: %s\"",
",",
"self",
".",
"name",
")",
"workflowcopy",
"=",
"deepcopy",
"(",
"self",
")",
"workflowcopy",
".",
"_generate_flatgraph",
"(",
")",
"... | https://github.com/nipy/nipype/blob/cd4c34d935a43812d1756482fdc4034844e485b8/nipype/pipeline/engine/workflows.py#L929-L934 | |
gkhayes/mlrose | 2a9d604ea464cccc48f30b8fe6b81fe5c4337c80 | mlrose/opt_probs.py | python | ContinuousOpt.random_neighbor | (self) | return neighbor | Return random neighbor of current state vector.
Returns
-------
neighbor: array
State vector of random neighbor. | Return random neighbor of current state vector. | [
"Return",
"random",
"neighbor",
"of",
"current",
"state",
"vector",
"."
] | def random_neighbor(self):
"""Return random neighbor of current state vector.
Returns
-------
neighbor: array
State vector of random neighbor.
"""
while True:
neighbor = np.copy(self.state)
i = np.random.randint(0, self.length)
neighbor[i] += self.step*np.random.choice([-1, 1])
if neighbor[i] > self.max_val:
neighbor[i] = self.max_val
elif neighbor[i] < self.min_val:
neighbor[i] = self.min_val
if not np.array_equal(np.array(neighbor), self.state):
break
return neighbor | [
"def",
"random_neighbor",
"(",
"self",
")",
":",
"while",
"True",
":",
"neighbor",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"state",
")",
"i",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"self",
".",
"length",
")",
"neighbor",
"[",
... | https://github.com/gkhayes/mlrose/blob/2a9d604ea464cccc48f30b8fe6b81fe5c4337c80/mlrose/opt_probs.py#L754-L777 | |
stevearc/dql | 9666cfba19773c20c7b4be29adc7d6179cf00d44 | dql/throttle.py | python | TableLimits._compute_limit | (self, limit, throughput) | Compute a percentage limit or return a point limit | Compute a percentage limit or return a point limit | [
"Compute",
"a",
"percentage",
"limit",
"or",
"return",
"a",
"point",
"limit"
] | def _compute_limit(self, limit, throughput):
"""Compute a percentage limit or return a point limit"""
if limit[-1] == "%":
return throughput * float(limit[:-1]) / 100.0
else:
return float(limit) | [
"def",
"_compute_limit",
"(",
"self",
",",
"limit",
",",
"throughput",
")",
":",
"if",
"limit",
"[",
"-",
"1",
"]",
"==",
"\"%\"",
":",
"return",
"throughput",
"*",
"float",
"(",
"limit",
"[",
":",
"-",
"1",
"]",
")",
"/",
"100.0",
"else",
":",
"... | https://github.com/stevearc/dql/blob/9666cfba19773c20c7b4be29adc7d6179cf00d44/dql/throttle.py#L16-L21 | ||
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/command/easy_install.py | python | easy_install.write_script | (self, script_name, contents, mode="t", blockers=()) | Write an executable file to the scripts directory | Write an executable file to the scripts directory | [
"Write",
"an",
"executable",
"file",
"to",
"the",
"scripts",
"directory"
] | def write_script(self, script_name, contents, mode="t", blockers=()):
"""Write an executable file to the scripts directory"""
self.delete_blockers( # clean up old .py/.pyw w/o a script
[os.path.join(self.script_dir, x) for x in blockers]
)
log.info("Installing %s script to %s", script_name, self.script_dir)
target = os.path.join(self.script_dir, script_name)
self.add_output(target)
if self.dry_run:
return
mask = current_umask()
ensure_directory(target)
if os.path.exists(target):
os.unlink(target)
with open(target, "w" + mode) as f:
f.write(contents)
chmod(target, 0o777 - mask) | [
"def",
"write_script",
"(",
"self",
",",
"script_name",
",",
"contents",
",",
"mode",
"=",
"\"t\"",
",",
"blockers",
"=",
"(",
")",
")",
":",
"self",
".",
"delete_blockers",
"(",
"# clean up old .py/.pyw w/o a script",
"[",
"os",
".",
"path",
".",
"join",
... | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/command/easy_install.py#L825-L843 | ||
praekeltfoundation/vumi | b74b5dac95df778519f54c670a353e4bda496df9 | vumi/transports/parlayx/xmlutil.py | python | ElementMaker.element | (self, tag, *children, **attrib) | return elem | Create an ElementTree element.
:param tag: Tag name or `QualifiedName` instance.
:param *children: Child content or elements.
:param **attrib: Element XML attributes.
:return: ElementTree element. | Create an ElementTree element. | [
"Create",
"an",
"ElementTree",
"element",
"."
] | def element(self, tag, *children, **attrib):
"""
Create an ElementTree element.
:param tag: Tag name or `QualifiedName` instance.
:param *children: Child content or elements.
:param **attrib: Element XML attributes.
:return: ElementTree element.
"""
if isinstance(tag, etree.QName):
tag = tag.text
elem = self._makeelement(tag)
if attrib:
self._set_attributes(elem, attrib)
for child in children:
self._handle_child(elem, child)
return elem | [
"def",
"element",
"(",
"self",
",",
"tag",
",",
"*",
"children",
",",
"*",
"*",
"attrib",
")",
":",
"if",
"isinstance",
"(",
"tag",
",",
"etree",
".",
"QName",
")",
":",
"tag",
"=",
"tag",
".",
"text",
"elem",
"=",
"self",
".",
"_makeelement",
"(... | https://github.com/praekeltfoundation/vumi/blob/b74b5dac95df778519f54c670a353e4bda496df9/vumi/transports/parlayx/xmlutil.py#L271-L291 | |
zentralopensource/zentral | c41f4f0824f0855fb8d382493cfea9d151cbc13c | zentral/contrib/osquery/compliance_checks.py | python | sync_query_compliance_check | (query, on) | return created, updated, deleted | Create update or delete the query compliance check | Create update or delete the query compliance check | [
"Create",
"update",
"or",
"delete",
"the",
"query",
"compliance",
"check"
] | def sync_query_compliance_check(query, on):
"Create update or delete the query compliance check"
created = updated = deleted = False
if on:
if not isinstance(query.version, int):
query.refresh_from_db()
cc_defaults = {
"model": OsqueryCheck.get_model(),
"name": query.name,
"version": query.version,
"description": query.description
}
if not query.compliance_check:
query.compliance_check = ComplianceCheck.objects.create(**cc_defaults)
query.save()
created = True
else:
for key, val in cc_defaults.items():
if getattr(query.compliance_check, key) != val:
setattr(query.compliance_check, key, val)
updated = True
if updated:
query.compliance_check.save()
elif query.compliance_check:
query.compliance_check.delete()
deleted = True
return created, updated, deleted | [
"def",
"sync_query_compliance_check",
"(",
"query",
",",
"on",
")",
":",
"created",
"=",
"updated",
"=",
"deleted",
"=",
"False",
"if",
"on",
":",
"if",
"not",
"isinstance",
"(",
"query",
".",
"version",
",",
"int",
")",
":",
"query",
".",
"refresh_from_... | https://github.com/zentralopensource/zentral/blob/c41f4f0824f0855fb8d382493cfea9d151cbc13c/zentral/contrib/osquery/compliance_checks.py#L39-L65 | |
facebookresearch/SpanBERT | 0670d8b6a38f6714b85ea7a033f16bd8cc162676 | pretraining/fairseq/trainer.py | python | Trainer.get_lr | (self) | return self.optimizer.get_lr() | Get the current learning rate. | Get the current learning rate. | [
"Get",
"the",
"current",
"learning",
"rate",
"."
] | def get_lr(self):
"""Get the current learning rate."""
return self.optimizer.get_lr() | [
"def",
"get_lr",
"(",
"self",
")",
":",
"return",
"self",
".",
"optimizer",
".",
"get_lr",
"(",
")"
] | https://github.com/facebookresearch/SpanBERT/blob/0670d8b6a38f6714b85ea7a033f16bd8cc162676/pretraining/fairseq/trainer.py#L361-L363 | |
tensorlayer/RLzoo | 8dd3ff1003d1c7a446f45119bbd6b48c048990f4 | rlzoo/common/distributions.py | python | DiagGaussian.sample | (self) | return self.mean, self.std * np.random.normal(0, 1, np.shape(self.mean)) | Get actions in deterministic or stochastic manner | Get actions in deterministic or stochastic manner | [
"Get",
"actions",
"in",
"deterministic",
"or",
"stochastic",
"manner"
] | def sample(self):
""" Get actions in deterministic or stochastic manner """
return self.mean, self.std * np.random.normal(0, 1, np.shape(self.mean)) | [
"def",
"sample",
"(",
"self",
")",
":",
"return",
"self",
".",
"mean",
",",
"self",
".",
"std",
"*",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"np",
".",
"shape",
"(",
"self",
".",
"mean",
")",
")"
] | https://github.com/tensorlayer/RLzoo/blob/8dd3ff1003d1c7a446f45119bbd6b48c048990f4/rlzoo/common/distributions.py#L159-L161 | |
osmr/imgclsmob | f2993d3ce73a2f7ddba05da3891defb08547d504 | chainer_/chainercv2/models/densenet.py | python | densenet121 | (**kwargs) | return get_densenet(blocks=121, model_name="densenet121", **kwargs) | DenseNet-121 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/models'
Location for keeping the model parameters. | DenseNet-121 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993. | [
"DenseNet",
"-",
"121",
"model",
"from",
"Densely",
"Connected",
"Convolutional",
"Networks",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1608",
".",
"06993",
"."
] | def densenet121(**kwargs):
"""
DenseNet-121 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/models'
Location for keeping the model parameters.
"""
return get_densenet(blocks=121, model_name="densenet121", **kwargs) | [
"def",
"densenet121",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"get_densenet",
"(",
"blocks",
"=",
"121",
",",
"model_name",
"=",
"\"densenet121\"",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/chainer_/chainercv2/models/densenet.py#L234-L245 | |
baidu-security/openrasp-iast | d4a5643420853a95614d371cf38d5c65ccf9cfd4 | openrasp_iast/core/components/common.py | python | split_host | (host_port) | return host, port | 将使用 "_" 连接为字符串的host、port还原
Parameters:
host_port - str
Returns:
str, int | 将使用 "_" 连接为字符串的host、port还原 | [
"将使用",
"_",
"连接为字符串的host、port还原"
] | def split_host(host_port):
"""
将使用 "_" 连接为字符串的host、port还原
Parameters:
host_port - str
Returns:
str, int
"""
host_port_split = host_port.split("_")
host = "_".join(host_port_split[:-1])
port = int(host_port_split[-1])
return host, port | [
"def",
"split_host",
"(",
"host_port",
")",
":",
"host_port_split",
"=",
"host_port",
".",
"split",
"(",
"\"_\"",
")",
"host",
"=",
"\"_\"",
".",
"join",
"(",
"host_port_split",
"[",
":",
"-",
"1",
"]",
")",
"port",
"=",
"int",
"(",
"host_port_split",
... | https://github.com/baidu-security/openrasp-iast/blob/d4a5643420853a95614d371cf38d5c65ccf9cfd4/openrasp_iast/core/components/common.py#L120-L133 | |
bikalims/bika.lims | 35e4bbdb5a3912cae0b5eb13e51097c8b0486349 | bika/lims/idserver.py | python | get_ids_with_prefix | (portal_type, prefix) | return ids | Return a list of ids sharing the same portal type and prefix | Return a list of ids sharing the same portal type and prefix | [
"Return",
"a",
"list",
"of",
"ids",
"sharing",
"the",
"same",
"portal",
"type",
"and",
"prefix"
] | def get_ids_with_prefix(portal_type, prefix):
"""Return a list of ids sharing the same portal type and prefix
"""
brains = search_by_prefix(portal_type, prefix)
ids = map(api.get_id, brains)
return ids | [
"def",
"get_ids_with_prefix",
"(",
"portal_type",
",",
"prefix",
")",
":",
"brains",
"=",
"search_by_prefix",
"(",
"portal_type",
",",
"prefix",
")",
"ids",
"=",
"map",
"(",
"api",
".",
"get_id",
",",
"brains",
")",
"return",
"ids"
] | https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/idserver.py#L236-L241 | |
007gzs/dingtalk-sdk | 7979da2e259fdbc571728cae2425a04dbc65850a | dingtalk/client/api/taobao.py | python | TbCaiNiaoKongZhiTa.cainiao_ecc_exceptions_delay_get | (
self,
mail_no
) | return self._top_request(
"cainiao.ecc.exceptions.delay.get",
{
"mail_no": mail_no
}
) | 菜鸟控制塔包裹滞留异常信息获取
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=43853
:param mail_no: 运单号 | 菜鸟控制塔包裹滞留异常信息获取
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=43853 | [
"菜鸟控制塔包裹滞留异常信息获取",
"文档地址:https",
":",
"//",
"open",
"-",
"doc",
".",
"dingtalk",
".",
"com",
"/",
"docs",
"/",
"api",
".",
"htm?apiId",
"=",
"43853"
] | def cainiao_ecc_exceptions_delay_get(
self,
mail_no
):
"""
菜鸟控制塔包裹滞留异常信息获取
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=43853
:param mail_no: 运单号
"""
return self._top_request(
"cainiao.ecc.exceptions.delay.get",
{
"mail_no": mail_no
}
) | [
"def",
"cainiao_ecc_exceptions_delay_get",
"(",
"self",
",",
"mail_no",
")",
":",
"return",
"self",
".",
"_top_request",
"(",
"\"cainiao.ecc.exceptions.delay.get\"",
",",
"{",
"\"mail_no\"",
":",
"mail_no",
"}",
")"
] | https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L110024-L110039 | |
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | common/lib/xmodule/xmodule/lti_2_util.py | python | LTI20BlockMixin.clear_user_module_score | (self, user) | Clears the module user state, including grades and comments, and also scoring in db's courseware_studentmodule
Arguments:
user (django.contrib.auth.models.User): Actual user whose module state is to be cleared
Returns:
nothing | Clears the module user state, including grades and comments, and also scoring in db's courseware_studentmodule | [
"Clears",
"the",
"module",
"user",
"state",
"including",
"grades",
"and",
"comments",
"and",
"also",
"scoring",
"in",
"db",
"s",
"courseware_studentmodule"
] | def clear_user_module_score(self, user):
"""
Clears the module user state, including grades and comments, and also scoring in db's courseware_studentmodule
Arguments:
user (django.contrib.auth.models.User): Actual user whose module state is to be cleared
Returns:
nothing
"""
self.set_user_module_score(user, None, None, score_deleted=True) | [
"def",
"clear_user_module_score",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"set_user_module_score",
"(",
"user",
",",
"None",
",",
"None",
",",
"score_deleted",
"=",
"True",
")"
] | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/lib/xmodule/xmodule/lti_2_util.py#L226-L236 | ||
deanishe/alfred-reddit | 2f7545e682fc1579489947baa679e19b4eb1900e | src/workflow/util.py | python | set_config | (name, value, bundleid=None, exportable=False) | Set a workflow variable in ``info.plist``.
.. versionadded:: 1.33
Args:
name (str): Name of variable to set.
value (str): Value to set variable to.
bundleid (str, optional): Bundle ID of workflow variable belongs to.
exportable (bool, optional): Whether variable should be marked
as exportable (Don't Export checkbox). | Set a workflow variable in ``info.plist``. | [
"Set",
"a",
"workflow",
"variable",
"in",
"info",
".",
"plist",
"."
] | def set_config(name, value, bundleid=None, exportable=False):
"""Set a workflow variable in ``info.plist``.
.. versionadded:: 1.33
Args:
name (str): Name of variable to set.
value (str): Value to set variable to.
bundleid (str, optional): Bundle ID of workflow variable belongs to.
exportable (bool, optional): Whether variable should be marked
as exportable (Don't Export checkbox).
"""
if not bundleid:
bundleid = os.getenv('alfred_workflow_bundleid')
name = applescriptify(name)
value = applescriptify(value)
bundleid = applescriptify(bundleid)
if exportable:
export = 'exportable true'
else:
export = 'exportable false'
script = AS_CONFIG_SET.format(name=name, bundleid=bundleid,
value=value, export=export)
run_applescript(script) | [
"def",
"set_config",
"(",
"name",
",",
"value",
",",
"bundleid",
"=",
"None",
",",
"exportable",
"=",
"False",
")",
":",
"if",
"not",
"bundleid",
":",
"bundleid",
"=",
"os",
".",
"getenv",
"(",
"'alfred_workflow_bundleid'",
")",
"name",
"=",
"applescriptif... | https://github.com/deanishe/alfred-reddit/blob/2f7545e682fc1579489947baa679e19b4eb1900e/src/workflow/util.py#L244-L272 | ||
AstroPrint/AstroBox | e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75 | src/astroprint/printer/s3g/__init__.py | python | PrinterS3g.doDisconnect | (self) | return True | [] | def doDisconnect(self):
with self._state_condition:
if self._printJob:
self._printJob.cancel()
self._printJob.join()
self._printJob = None
if self.isConnected():
self._comm.close()
self._comm = None
self._profile = None
self._gcodeParser = None
if self._botThread:
self._botThread = None
self._firmwareVersion = None
self._changeState(self.STATE_CLOSED)
return True | [
"def",
"doDisconnect",
"(",
"self",
")",
":",
"with",
"self",
".",
"_state_condition",
":",
"if",
"self",
".",
"_printJob",
":",
"self",
".",
"_printJob",
".",
"cancel",
"(",
")",
"self",
".",
"_printJob",
".",
"join",
"(",
")",
"self",
".",
"_printJob... | https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/printer/s3g/__init__.py#L294-L313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.