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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cclib/cclib | 81cd4a81cc4a3bbed7016b3e417ca9bff8ad3a92 | cclib/method/volume.py | python | Volume.write | (self, filename, fformat="Cube") | Write the volume to a file. | Write the volume to a file. | [
"Write",
"the",
"volume",
"to",
"a",
"file",
"."
] | def write(self, filename, fformat="Cube"):
"""Write the volume to a file."""
fformat = fformat.lower()
writers = {
"vtk": self.writeasvtk,
"cube": self.writeascube,
}
if fformat not in writers:
raise RuntimeError("File format must be either VTK or Cube")
writers[fformat](filename) | [
"def",
"write",
"(",
"self",
",",
"filename",
",",
"fformat",
"=",
"\"Cube\"",
")",
":",
"fformat",
"=",
"fformat",
".",
"lower",
"(",
")",
"writers",
"=",
"{",
"\"vtk\"",
":",
"self",
".",
"writeasvtk",
",",
"\"cube\"",
":",
"self",
".",
"writeascube"... | https://github.com/cclib/cclib/blob/81cd4a81cc4a3bbed7016b3e417ca9bff8ad3a92/cclib/method/volume.py#L190-L203 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_oa_utils/filter_plugins/oo_filters.py | python | FilterModule.filters | (self) | return {
"lib_utils_oo_select_keys": lib_utils_oo_select_keys,
"lib_utils_oo_select_keys_from_list": lib_utils_oo_select_keys_from_list,
"lib_utils_oo_collect": lib_utils_oo_collect,
"lib_utils_oo_pdb": lib_utils_oo_pdb,
"lib_utils_oo_prepend_strings_in_list": lib_utils_oo_prepend_strings_in_list,
"lib_utils_oo_dict_to_list_of_dict": lib_utils_oo_dict_to_list_of_dict,
"lib_utils_oo_split": lib_utils_oo_split,
"lib_utils_oo_dict_to_keqv_list": lib_utils_oo_dict_to_keqv_list,
"lib_utils_oo_list_to_dict": lib_utils_oo_list_to_dict,
"lib_utils_oo_parse_named_certificates": lib_utils_oo_parse_named_certificates,
"lib_utils_oo_parse_certificate_san": lib_utils_oo_parse_certificate_san,
"lib_utils_oo_generate_secret": lib_utils_oo_generate_secret,
"lib_utils_oo_image_tag_to_rpm_version": lib_utils_oo_image_tag_to_rpm_version,
"lib_utils_oo_hostname_from_url": lib_utils_oo_hostname_from_url,
"lib_utils_oo_loadbalancer_frontends": lib_utils_oo_loadbalancer_frontends,
"lib_utils_oo_loadbalancer_backends": lib_utils_oo_loadbalancer_backends,
"lib_utils_to_padded_yaml": lib_utils_to_padded_yaml,
"lib_utils_oo_random_word": lib_utils_oo_random_word,
"lib_utils_oo_selector_to_string_list": lib_utils_oo_selector_to_string_list,
"lib_utils_oo_filter_sa_secrets": lib_utils_oo_filter_sa_secrets,
"lib_utils_oo_l_of_d_to_csv": lib_utils_oo_l_of_d_to_csv,
"map_from_pairs": map_from_pairs,
"map_to_pairs": map_to_pairs,
"lib_utils_oo_etcd_host_urls": lib_utils_oo_etcd_host_urls,
"lib_utils_mutate_htpass_provider": lib_utils_mutate_htpass_provider,
"lib_utils_oo_oreg_image": lib_utils_oo_oreg_image,
"lib_utils_oo_list_of_dict_to_dict_from_key": lib_utils_oo_list_of_dict_to_dict_from_key,
} | returns a mapping of filters to methods | returns a mapping of filters to methods | [
"returns",
"a",
"mapping",
"of",
"filters",
"to",
"methods"
] | def filters(self):
""" returns a mapping of filters to methods """
return {
"lib_utils_oo_select_keys": lib_utils_oo_select_keys,
"lib_utils_oo_select_keys_from_list": lib_utils_oo_select_keys_from_list,
"lib_utils_oo_collect": lib_utils_oo_collect,
"lib_utils_oo_pdb": lib_utils_oo_pdb,
"lib_utils_oo_prepend_strings_in_list": lib_utils_oo_prepend_strings_in_list,
"lib_utils_oo_dict_to_list_of_dict": lib_utils_oo_dict_to_list_of_dict,
"lib_utils_oo_split": lib_utils_oo_split,
"lib_utils_oo_dict_to_keqv_list": lib_utils_oo_dict_to_keqv_list,
"lib_utils_oo_list_to_dict": lib_utils_oo_list_to_dict,
"lib_utils_oo_parse_named_certificates": lib_utils_oo_parse_named_certificates,
"lib_utils_oo_parse_certificate_san": lib_utils_oo_parse_certificate_san,
"lib_utils_oo_generate_secret": lib_utils_oo_generate_secret,
"lib_utils_oo_image_tag_to_rpm_version": lib_utils_oo_image_tag_to_rpm_version,
"lib_utils_oo_hostname_from_url": lib_utils_oo_hostname_from_url,
"lib_utils_oo_loadbalancer_frontends": lib_utils_oo_loadbalancer_frontends,
"lib_utils_oo_loadbalancer_backends": lib_utils_oo_loadbalancer_backends,
"lib_utils_to_padded_yaml": lib_utils_to_padded_yaml,
"lib_utils_oo_random_word": lib_utils_oo_random_word,
"lib_utils_oo_selector_to_string_list": lib_utils_oo_selector_to_string_list,
"lib_utils_oo_filter_sa_secrets": lib_utils_oo_filter_sa_secrets,
"lib_utils_oo_l_of_d_to_csv": lib_utils_oo_l_of_d_to_csv,
"map_from_pairs": map_from_pairs,
"map_to_pairs": map_to_pairs,
"lib_utils_oo_etcd_host_urls": lib_utils_oo_etcd_host_urls,
"lib_utils_mutate_htpass_provider": lib_utils_mutate_htpass_provider,
"lib_utils_oo_oreg_image": lib_utils_oo_oreg_image,
"lib_utils_oo_list_of_dict_to_dict_from_key": lib_utils_oo_list_of_dict_to_dict_from_key,
} | [
"def",
"filters",
"(",
"self",
")",
":",
"return",
"{",
"\"lib_utils_oo_select_keys\"",
":",
"lib_utils_oo_select_keys",
",",
"\"lib_utils_oo_select_keys_from_list\"",
":",
"lib_utils_oo_select_keys_from_list",
",",
"\"lib_utils_oo_collect\"",
":",
"lib_utils_oo_collect",
",",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_utils/filter_plugins/oo_filters.py#L689-L719 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/partition_tuple.py | python | PartitionTuple.contains | (self, mu) | return mu.level()<=self.level() and all(self[c].contains(mu[c]) for c in range(len(mu))) | r"""
Return ``True`` if this partition tuple contains `\mu`.
If `\lambda=(\lambda^{(1)}, \ldots, \lambda^{(l)})` and
`\mu=(\mu^{(1)}, \ldots, \mu^{(m)})` are two partition tuples then
`\lambda` contains `\mu` if `m \leq l` and
`\mu^{(i)}_r \leq \lambda^{(i)}_r` for `1 \leq i \leq m` and `r \geq 0`.
EXAMPLES::
sage: PartitionTuple([[1,1],[2],[2,1]]).contains( PartitionTuple([[1,1],[2],[2,1]]) )
True | r"""
Return ``True`` if this partition tuple contains `\mu`. | [
"r",
"Return",
"True",
"if",
"this",
"partition",
"tuple",
"contains",
"\\",
"mu",
"."
] | def contains(self, mu):
r"""
Return ``True`` if this partition tuple contains `\mu`.
If `\lambda=(\lambda^{(1)}, \ldots, \lambda^{(l)})` and
`\mu=(\mu^{(1)}, \ldots, \mu^{(m)})` are two partition tuples then
`\lambda` contains `\mu` if `m \leq l` and
`\mu^{(i)}_r \leq \lambda^{(i)}_r` for `1 \leq i \leq m` and `r \geq 0`.
EXAMPLES::
sage: PartitionTuple([[1,1],[2],[2,1]]).contains( PartitionTuple([[1,1],[2],[2,1]]) )
True
"""
return mu.level()<=self.level() and all(self[c].contains(mu[c]) for c in range(len(mu))) | [
"def",
"contains",
"(",
"self",
",",
"mu",
")",
":",
"return",
"mu",
".",
"level",
"(",
")",
"<=",
"self",
".",
"level",
"(",
")",
"and",
"all",
"(",
"self",
"[",
"c",
"]",
".",
"contains",
"(",
"mu",
"[",
"c",
"]",
")",
"for",
"c",
"in",
"... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/partition_tuple.py#L1333-L1347 | |
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/cinder/cinder/openstack/common/excutils.py | python | save_and_reraise_exception | () | Save current exception, run some code and then re-raise.
In some cases the exception context can be cleared, resulting in None
being attempted to be re-raised after an exception handler is run. This
can happen when eventlet switches greenthreads or when running an
exception handler, code raises and catches an exception. In both
cases the exception context will be cleared.
To work around this, we save the exception state, run handler code, and
then re-raise the original exception. If another exception occurs, the
saved exception is logged and the new exception is re-raised. | Save current exception, run some code and then re-raise. | [
"Save",
"current",
"exception",
"run",
"some",
"code",
"and",
"then",
"re",
"-",
"raise",
"."
] | def save_and_reraise_exception():
"""Save current exception, run some code and then re-raise.
In some cases the exception context can be cleared, resulting in None
being attempted to be re-raised after an exception handler is run. This
can happen when eventlet switches greenthreads or when running an
exception handler, code raises and catches an exception. In both
cases the exception context will be cleared.
To work around this, we save the exception state, run handler code, and
then re-raise the original exception. If another exception occurs, the
saved exception is logged and the new exception is re-raised.
"""
type_, value, tb = sys.exc_info()
try:
yield
except Exception:
logging.error(_('Original exception being dropped: %s'),
traceback.format_exception(type_, value, tb))
raise
raise type_, value, tb | [
"def",
"save_and_reraise_exception",
"(",
")",
":",
"type_",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"try",
":",
"yield",
"except",
"Exception",
":",
"logging",
".",
"error",
"(",
"_",
"(",
"'Original exception being dropped: %s'",
")... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/openstack/common/excutils.py#L31-L51 | ||
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/config/oidc.py | python | _parse_oidc_config_dict | (
oidc_config: JsonDict, config_path: Tuple[str, ...]
) | return OidcProviderConfig(
idp_id=idp_id,
idp_name=oidc_config.get("idp_name", "OIDC"),
idp_icon=idp_icon,
idp_brand=oidc_config.get("idp_brand"),
discover=oidc_config.get("discover", True),
issuer=oidc_config["issuer"],
client_id=oidc_config["client_id"],
client_secret=oidc_config.get("client_secret"),
client_secret_jwt_key=client_secret_jwt_key,
client_auth_method=oidc_config.get("client_auth_method", "client_secret_basic"),
scopes=oidc_config.get("scopes", ["openid"]),
authorization_endpoint=oidc_config.get("authorization_endpoint"),
token_endpoint=oidc_config.get("token_endpoint"),
userinfo_endpoint=oidc_config.get("userinfo_endpoint"),
jwks_uri=oidc_config.get("jwks_uri"),
skip_verification=oidc_config.get("skip_verification", False),
user_profile_method=oidc_config.get("user_profile_method", "auto"),
allow_existing_users=oidc_config.get("allow_existing_users", False),
user_mapping_provider_class=user_mapping_provider_class,
user_mapping_provider_config=user_mapping_provider_config,
attribute_requirements=attribute_requirements,
) | Take the configuration dict and parse it into an OidcProviderConfig
Raises:
ConfigError if the configuration is malformed. | Take the configuration dict and parse it into an OidcProviderConfig | [
"Take",
"the",
"configuration",
"dict",
"and",
"parse",
"it",
"into",
"an",
"OidcProviderConfig"
] | def _parse_oidc_config_dict(
oidc_config: JsonDict, config_path: Tuple[str, ...]
) -> "OidcProviderConfig":
"""Take the configuration dict and parse it into an OidcProviderConfig
Raises:
ConfigError if the configuration is malformed.
"""
ump_config = oidc_config.get("user_mapping_provider", {})
ump_config.setdefault("module", DEFAULT_USER_MAPPING_PROVIDER)
if ump_config.get("module") == LEGACY_USER_MAPPING_PROVIDER:
ump_config["module"] = DEFAULT_USER_MAPPING_PROVIDER
ump_config.setdefault("config", {})
(
user_mapping_provider_class,
user_mapping_provider_config,
) = load_module(ump_config, config_path + ("user_mapping_provider",))
# Ensure loaded user mapping module has defined all necessary methods
required_methods = [
"get_remote_user_id",
"map_user_attributes",
]
missing_methods = [
method
for method in required_methods
if not hasattr(user_mapping_provider_class, method)
]
if missing_methods:
raise ConfigError(
"Class %s is missing required "
"methods: %s"
% (
user_mapping_provider_class,
", ".join(missing_methods),
),
config_path + ("user_mapping_provider", "module"),
)
idp_id = oidc_config.get("idp_id", "oidc")
# prefix the given IDP with a prefix specific to the SSO mechanism, to avoid
# clashes with other mechs (such as SAML, CAS).
#
# We allow "oidc" as an exception so that people migrating from old-style
# "oidc_config" format (which has long used "oidc" as its idp_id) can migrate to
# a new-style "oidc_providers" entry without changing the idp_id for their provider
# (and thereby invalidating their user_external_ids data).
if idp_id != "oidc":
idp_id = "oidc-" + idp_id
# MSC2858 also specifies that the idp_icon must be a valid MXC uri
idp_icon = oidc_config.get("idp_icon")
if idp_icon is not None:
try:
parse_and_validate_mxc_uri(idp_icon)
except ValueError as e:
raise ConfigError(
"idp_icon must be a valid MXC URI", config_path + ("idp_icon",)
) from e
client_secret_jwt_key_config = oidc_config.get("client_secret_jwt_key")
client_secret_jwt_key: Optional[OidcProviderClientSecretJwtKey] = None
if client_secret_jwt_key_config is not None:
keyfile = client_secret_jwt_key_config.get("key_file")
if keyfile:
key = read_file(keyfile, config_path + ("client_secret_jwt_key",))
else:
key = client_secret_jwt_key_config["key"]
client_secret_jwt_key = OidcProviderClientSecretJwtKey(
key=key,
jwt_header=client_secret_jwt_key_config["jwt_header"],
jwt_payload=client_secret_jwt_key_config.get("jwt_payload", {}),
)
# parse attribute_requirements from config (list of dicts) into a list of SsoAttributeRequirement
attribute_requirements = [
SsoAttributeRequirement(**x)
for x in oidc_config.get("attribute_requirements", [])
]
return OidcProviderConfig(
idp_id=idp_id,
idp_name=oidc_config.get("idp_name", "OIDC"),
idp_icon=idp_icon,
idp_brand=oidc_config.get("idp_brand"),
discover=oidc_config.get("discover", True),
issuer=oidc_config["issuer"],
client_id=oidc_config["client_id"],
client_secret=oidc_config.get("client_secret"),
client_secret_jwt_key=client_secret_jwt_key,
client_auth_method=oidc_config.get("client_auth_method", "client_secret_basic"),
scopes=oidc_config.get("scopes", ["openid"]),
authorization_endpoint=oidc_config.get("authorization_endpoint"),
token_endpoint=oidc_config.get("token_endpoint"),
userinfo_endpoint=oidc_config.get("userinfo_endpoint"),
jwks_uri=oidc_config.get("jwks_uri"),
skip_verification=oidc_config.get("skip_verification", False),
user_profile_method=oidc_config.get("user_profile_method", "auto"),
allow_existing_users=oidc_config.get("allow_existing_users", False),
user_mapping_provider_class=user_mapping_provider_class,
user_mapping_provider_config=user_mapping_provider_config,
attribute_requirements=attribute_requirements,
) | [
"def",
"_parse_oidc_config_dict",
"(",
"oidc_config",
":",
"JsonDict",
",",
"config_path",
":",
"Tuple",
"[",
"str",
",",
"...",
"]",
")",
"->",
"\"OidcProviderConfig\"",
":",
"ump_config",
"=",
"oidc_config",
".",
"get",
"(",
"\"user_mapping_provider\"",
",",
"... | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/config/oidc.py#L391-L495 | |
ucsb-seclab/karonte | 427ac313e596f723e40768b95d13bd7a9fc92fd8 | tool/bdg/binary_dependency_graph.py | python | BdgNode.set_orphan | (self) | [] | def set_orphan(self):
self._orphan = True | [
"def",
"set_orphan",
"(",
"self",
")",
":",
"self",
".",
"_orphan",
"=",
"True"
] | https://github.com/ucsb-seclab/karonte/blob/427ac313e596f723e40768b95d13bd7a9fc92fd8/tool/bdg/binary_dependency_graph.py#L117-L118 | ||||
intel/virtual-storage-manager | 00706ab9701acbd0d5e04b19cc80c6b66a2973b8 | source/python-vsmclient/vsmclient/v1/servers.py | python | Server.delete | (self) | Delete this server. | Delete this server. | [
"Delete",
"this",
"server",
"."
] | def delete(self):
"""Delete this server."""
self.manager.delete(self) | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"manager",
".",
"delete",
"(",
"self",
")"
] | https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/python-vsmclient/vsmclient/v1/servers.py#L28-L30 | ||
spyder-ide/spyder | 55da47c032dfcf519600f67f8b30eab467f965e7 | spyder/widgets/mixins.py | python | GetHelpMixin.show_object_info | (self, text, call=False, force=False) | Show signature calltip and/or docstring in the Help plugin | Show signature calltip and/or docstring in the Help plugin | [
"Show",
"signature",
"calltip",
"and",
"/",
"or",
"docstring",
"in",
"the",
"Help",
"plugin"
] | def show_object_info(self, text, call=False, force=False):
"""Show signature calltip and/or docstring in the Help plugin"""
text = to_text_string(text)
# Show docstring
help_enabled = self.help_enabled or force
if help_enabled:
doc = {
'name': text,
'ignore_unknown': False,
}
self.sig_help_requested.emit(doc)
# Show calltip
if call and getattr(self, 'calltips', None):
# Display argument list if this is a function call
iscallable = self.iscallable(text)
if iscallable is not None:
if iscallable:
arglist = self.get_arglist(text)
name = text.split('.')[-1]
argspec = signature = ''
if isinstance(arglist, bool):
arglist = []
if arglist:
argspec = '(' + ''.join(arglist) + ')'
else:
doc = self.get__doc__(text)
if doc is not None:
# This covers cases like np.abs, whose docstring is
# the same as np.absolute and because of that a
# proper signature can't be obtained correctly
argspec = getargspecfromtext(doc)
if not argspec:
signature = getsignaturefromtext(doc, name)
if argspec or signature:
if argspec:
tiptext = name + argspec
else:
tiptext = signature
# TODO: Select language and pass it to call
self.show_calltip(tiptext) | [
"def",
"show_object_info",
"(",
"self",
",",
"text",
",",
"call",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"# Show docstring",
"help_enabled",
"=",
"self",
".",
"help_enabled",
"or",
"force",
"if"... | https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/widgets/mixins.py#L1474-L1515 | ||
jython/frozen-mirror | b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99 | lib-python/2.7/bdb.py | python | Bdb.set_next | (self, frame) | Stop on the next line in or below the given frame. | Stop on the next line in or below the given frame. | [
"Stop",
"on",
"the",
"next",
"line",
"in",
"or",
"below",
"the",
"given",
"frame",
"."
] | def set_next(self, frame):
"""Stop on the next line in or below the given frame."""
self._set_stopinfo(frame, None) | [
"def",
"set_next",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"_set_stopinfo",
"(",
"frame",
",",
"None",
")"
] | https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/bdb.py#L204-L206 | ||
missionpinball/mpf | 8e6b74cff4ba06d2fec9445742559c1068b88582 | mpf/core/bcp/bcp_pickle_client.py | python | BcpPickleClient.accept_connection | (self, receiver, sender) | Create client for incoming connection. | Create client for incoming connection. | [
"Create",
"client",
"for",
"incoming",
"connection",
"."
] | def accept_connection(self, receiver, sender):
"""Create client for incoming connection."""
self._receiver = receiver
self._sender = sender | [
"def",
"accept_connection",
"(",
"self",
",",
"receiver",
",",
"sender",
")",
":",
"self",
".",
"_receiver",
"=",
"receiver",
"self",
".",
"_sender",
"=",
"sender"
] | https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/core/bcp/bcp_pickle_client.py#L51-L54 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/pip/_vendor/html5lib/_inputstream.py | python | EncodingParser.getAttribute | (self) | Return a name,value pair for the next attribute in the stream,
if one is found, or None | Return a name,value pair for the next attribute in the stream,
if one is found, or None | [
"Return",
"a",
"name",
"value",
"pair",
"for",
"the",
"next",
"attribute",
"in",
"the",
"stream",
"if",
"one",
"is",
"found",
"or",
"None"
] | def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c) | [
"def",
"getAttribute",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"# Step 1 (skip chars)",
"c",
"=",
"data",
".",
"skip",
"(",
"spaceCharactersBytes",
"|",
"frozenset",
"(",
"[",
"b\"/\"",
"]",
")",
")",
"assert",
"c",
"is",
"None",
"or",
... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_vendor/html5lib/_inputstream.py#L792-L866 | ||
apache/libcloud | 90971e17bfd7b6bb97b2489986472c531cc8e140 | libcloud/compute/drivers/nttcis.py | python | NttCisNodeDriver.ex_set_firewall_rule_state | (self, rule, state) | return response_code in ["IN_PROGRESS", "OK"] | Change the state (enabled or disabled) of a rule
:param rule: The rule to delete
:type rule: :class:`NttCisFirewallRule`
:param state: The desired state enabled (True) or disabled (False)
:type state: ``bool``
:rtype: ``bool`` | Change the state (enabled or disabled) of a rule | [
"Change",
"the",
"state",
"(",
"enabled",
"or",
"disabled",
")",
"of",
"a",
"rule"
] | def ex_set_firewall_rule_state(self, rule, state):
"""
Change the state (enabled or disabled) of a rule
:param rule: The rule to delete
:type rule: :class:`NttCisFirewallRule`
:param state: The desired state enabled (True) or disabled (False)
:type state: ``bool``
:rtype: ``bool``
"""
update_node = ET.Element("editFirewallRule", {"xmlns": TYPES_URN})
update_node.set("id", rule.id)
ET.SubElement(update_node, "enabled").text = str(state).lower()
result = self.connection.request_with_orgId_api_2(
"network/editFirewallRule", method="POST", data=ET.tostring(update_node)
).object
response_code = findtext(result, "responseCode", TYPES_URN)
return response_code in ["IN_PROGRESS", "OK"] | [
"def",
"ex_set_firewall_rule_state",
"(",
"self",
",",
"rule",
",",
"state",
")",
":",
"update_node",
"=",
"ET",
".",
"Element",
"(",
"\"editFirewallRule\"",
",",
"{",
"\"xmlns\"",
":",
"TYPES_URN",
"}",
")",
"update_node",
".",
"set",
"(",
"\"id\"",
",",
... | https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/nttcis.py#L2573-L2594 | |
theupdateframework/python-tuf | 45cf6076e3da7ff47968975f8106c4d6a03f9d4c | tuf/keydb.py | python | get_key | (keyid, repository_name='default') | <Purpose>
Return the key belonging to 'keyid'.
<Arguments>
keyid:
An object conformant to 'securesystemslib.formats.KEYID_SCHEMA'. It is used as an
identifier for keys.
repository_name:
The name of the repository to get the key. If not supplied, the key is
retrieved from the 'default' repository.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments do not have the correct format.
tuf.exceptions.UnknownKeyError, if 'keyid' is not found in the keydb database.
securesystemslib.exceptions.InvalidNameError, if 'repository_name' does not exist in the key
database.
<Side Effects>
None.
<Returns>
The key matching 'keyid'. In the case of RSA keys, a dictionary conformant
to 'securesystemslib.formats.RSAKEY_SCHEMA' is returned. | <Purpose>
Return the key belonging to 'keyid'. | [
"<Purpose",
">",
"Return",
"the",
"key",
"belonging",
"to",
"keyid",
"."
] | def get_key(keyid, repository_name='default'):
"""
<Purpose>
Return the key belonging to 'keyid'.
<Arguments>
keyid:
An object conformant to 'securesystemslib.formats.KEYID_SCHEMA'. It is used as an
identifier for keys.
repository_name:
The name of the repository to get the key. If not supplied, the key is
retrieved from the 'default' repository.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments do not have the correct format.
tuf.exceptions.UnknownKeyError, if 'keyid' is not found in the keydb database.
securesystemslib.exceptions.InvalidNameError, if 'repository_name' does not exist in the key
database.
<Side Effects>
None.
<Returns>
The key matching 'keyid'. In the case of RSA keys, a dictionary conformant
to 'securesystemslib.formats.RSAKEY_SCHEMA' is returned.
"""
# Does 'keyid' have the correct format?
# This check will ensure 'keyid' has the appropriate number of objects
# and object types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' is the match fails.
sslib_formats.KEYID_SCHEMA.check_match(keyid)
# Does 'repository_name' have the correct format?
sslib_formats.NAME_SCHEMA.check_match(repository_name)
if repository_name not in _keydb_dict:
raise sslib_exceptions.InvalidNameError('Repository name does not exist:'
' ' + repr(repository_name))
# Return the key belonging to 'keyid', if found in the key database.
try:
return copy.deepcopy(_keydb_dict[repository_name][keyid])
except KeyError as error:
raise exceptions.UnknownKeyError('Key: ' + keyid) from error | [
"def",
"get_key",
"(",
"keyid",
",",
"repository_name",
"=",
"'default'",
")",
":",
"# Does 'keyid' have the correct format?",
"# This check will ensure 'keyid' has the appropriate number of objects",
"# and object types, and that all dict keys are properly named.",
"# Raise 'securesystems... | https://github.com/theupdateframework/python-tuf/blob/45cf6076e3da7ff47968975f8106c4d6a03f9d4c/tuf/keydb.py#L293-L341 | ||
chebee7i/nxpd | a0797cd0ee4f8584c9ee49bab45e63f6ed05613a | nxpd/pydot/__init__.py | python | Graph.get_type | (self) | return self.obj_dict['type'] | Get the graph's type, 'graph' or 'digraph'. | Get the graph's type, 'graph' or 'digraph'. | [
"Get",
"the",
"graph",
"s",
"type",
"graph",
"or",
"digraph",
"."
] | def get_type(self):
"""Get the graph's type, 'graph' or 'digraph'."""
return self.obj_dict['type'] | [
"def",
"get_type",
"(",
"self",
")",
":",
"return",
"self",
".",
"obj_dict",
"[",
"'type'",
"]"
] | https://github.com/chebee7i/nxpd/blob/a0797cd0ee4f8584c9ee49bab45e63f6ed05613a/nxpd/pydot/__init__.py#L1175-L1178 | |
OpenMDAO/OpenMDAO1 | 791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317 | openmdao/recorders/recording_manager.py | python | RecordingManager.append | (self, recorder) | Add a recorder for recording.
Args
----
recorder : `BaseRecorder`
Recorder instance. | Add a recorder for recording. | [
"Add",
"a",
"recorder",
"for",
"recording",
"."
] | def append(self, recorder):
""" Add a recorder for recording.
Args
----
recorder : `BaseRecorder`
Recorder instance.
"""
self._recorders.append(recorder) | [
"def",
"append",
"(",
"self",
",",
"recorder",
")",
":",
"self",
".",
"_recorders",
".",
"append",
"(",
"recorder",
")"
] | https://github.com/OpenMDAO/OpenMDAO1/blob/791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317/openmdao/recorders/recording_manager.py#L34-L42 | ||
fepegar/torchio | 3e07b78da16d6db4da7193325b3f9cb31fc0911a | torchio/external/due.py | python | InactiveDueCreditCollector.dcite | (self, *args, **kwargs) | return nondecorating_decorator | If I could cite I would | If I could cite I would | [
"If",
"I",
"could",
"cite",
"I",
"would"
] | def dcite(self, *args, **kwargs):
"""If I could cite I would"""
def nondecorating_decorator(func):
return func
return nondecorating_decorator | [
"def",
"dcite",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"nondecorating_decorator",
"(",
"func",
")",
":",
"return",
"func",
"return",
"nondecorating_decorator"
] | https://github.com/fepegar/torchio/blob/3e07b78da16d6db4da7193325b3f9cb31fc0911a/torchio/external/due.py#L37-L41 | |
Qirky/FoxDot | 76318f9630bede48ff3994146ed644affa27bfa4 | FoxDot/lib/OSC.py | python | OSCStreamingClient._transmitMsgWithTimeout | (self, msg) | [] | def _transmitMsgWithTimeout(self, msg):
if not isinstance(msg, OSCMessage):
raise TypeError("'msg' argument is not an OSCMessage or OSCBundle object")
binary = msg.getBinary()
length = len(binary)
# prepend length of packet before the actual message (big endian)
len_big_endian = array.array('c', '\0' * 4)
struct.pack_into(">L", len_big_endian, 0, length)
len_big_endian = len_big_endian.tostring()
if self._transmitWithTimeout(len_big_endian) and self._transmitWithTimeout(binary):
return True
else:
return False | [
"def",
"_transmitMsgWithTimeout",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"OSCMessage",
")",
":",
"raise",
"TypeError",
"(",
"\"'msg' argument is not an OSCMessage or OSCBundle object\"",
")",
"binary",
"=",
"msg",
".",
"getB... | https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/OSC.py#L2829-L2841 | ||||
mitogen-hq/mitogen | 5b505f524a7ae170fe68613841ab92b299613d3f | ansible_mitogen/runner.py | python | shlex_split_b | (s) | return [t for t in shlex.split(s, comments=True)] | Use shlex.split() to split characters in some single-byte encoding, without
knowing what that encoding is. The input is bytes, the output is a list of
bytes. | Use shlex.split() to split characters in some single-byte encoding, without
knowing what that encoding is. The input is bytes, the output is a list of
bytes. | [
"Use",
"shlex",
".",
"split",
"()",
"to",
"split",
"characters",
"in",
"some",
"single",
"-",
"byte",
"encoding",
"without",
"knowing",
"what",
"that",
"encoding",
"is",
".",
"The",
"input",
"is",
"bytes",
"the",
"output",
"is",
"a",
"list",
"of",
"bytes... | def shlex_split_b(s):
"""
Use shlex.split() to split characters in some single-byte encoding, without
knowing what that encoding is. The input is bytes, the output is a list of
bytes.
"""
assert isinstance(s, mitogen.core.BytesType)
if mitogen.core.PY3:
return [
t.encode('latin1')
for t in shlex.split(s.decode('latin1'), comments=True)
]
return [t for t in shlex.split(s, comments=True)] | [
"def",
"shlex_split_b",
"(",
"s",
")",
":",
"assert",
"isinstance",
"(",
"s",
",",
"mitogen",
".",
"core",
".",
"BytesType",
")",
"if",
"mitogen",
".",
"core",
".",
"PY3",
":",
"return",
"[",
"t",
".",
"encode",
"(",
"'latin1'",
")",
"for",
"t",
"i... | https://github.com/mitogen-hq/mitogen/blob/5b505f524a7ae170fe68613841ab92b299613d3f/ansible_mitogen/runner.py#L105-L118 | |
cloudmarker/cloudmarker | 0dd2daadfa0203b3d1062e5067b14e4e0f189697 | cloudmarker/events/azpostgreslogconnectionsevent.py | python | AzPostgresLogConnectionsEvent.__init__ | (self) | Create an instance of :class:`AzPostgresLogConnectionsEvent`. | Create an instance of :class:`AzPostgresLogConnectionsEvent`. | [
"Create",
"an",
"instance",
"of",
":",
"class",
":",
"AzPostgresLogConnectionsEvent",
"."
] | def __init__(self):
"""Create an instance of :class:`AzPostgresLogConnectionsEvent`.""" | [
"def",
"__init__",
"(",
"self",
")",
":"
] | https://github.com/cloudmarker/cloudmarker/blob/0dd2daadfa0203b3d1062e5067b14e4e0f189697/cloudmarker/events/azpostgreslogconnectionsevent.py#L20-L21 | ||
calliope-project/calliope | 9d588fa98ec8eb11065ebb43bcc90d07657b0d43 | calliope/backend/pyomo/constraints/milp.py | python | storage_capacity_max_purchase_milp_constraint_rule | (backend_model, node, tech) | Set maximum storage capacity.
The first valid case is applied:
.. container:: scrolling-wrapper
.. math::
\\boldsymbol{storage_{cap}}(loc::tech)
\\begin{cases}
= storage_{cap, equals}(loc::tech) \\times \\boldsymbol{purchased},&
\\text{if } storage_{cap, equals} \\\\
\\leq storage_{cap, max}(loc::tech) \\times \\boldsymbol{purchased},&
\\text{if } storage_{cap, max}(loc::tech)\\\\
\\text{unconstrained},& \\text{otherwise}
\\end{cases}
\\forall loc::tech \\in loc::techs_{purchase, store} | Set maximum storage capacity. | [
"Set",
"maximum",
"storage",
"capacity",
"."
] | def storage_capacity_max_purchase_milp_constraint_rule(backend_model, node, tech):
"""
Set maximum storage capacity.
The first valid case is applied:
.. container:: scrolling-wrapper
.. math::
\\boldsymbol{storage_{cap}}(loc::tech)
\\begin{cases}
= storage_{cap, equals}(loc::tech) \\times \\boldsymbol{purchased},&
\\text{if } storage_{cap, equals} \\\\
\\leq storage_{cap, max}(loc::tech) \\times \\boldsymbol{purchased},&
\\text{if } storage_{cap, max}(loc::tech)\\\\
\\text{unconstrained},& \\text{otherwise}
\\end{cases}
\\forall loc::tech \\in loc::techs_{purchase, store}
"""
storage_cap_max = get_param(backend_model, "storage_cap_max", (node, tech))
storage_cap_equals = get_param(backend_model, "storage_cap_equals", (node, tech))
if po.value(storage_cap_equals):
return backend_model.storage_cap[node, tech] == (
storage_cap_equals * backend_model.purchased[node, tech]
)
elif po.value(storage_cap_max):
return backend_model.storage_cap[node, tech] <= (
storage_cap_max * backend_model.purchased[node, tech]
)
else:
return po.Constraint.Skip | [
"def",
"storage_capacity_max_purchase_milp_constraint_rule",
"(",
"backend_model",
",",
"node",
",",
"tech",
")",
":",
"storage_cap_max",
"=",
"get_param",
"(",
"backend_model",
",",
"\"storage_cap_max\"",
",",
"(",
"node",
",",
"tech",
")",
")",
"storage_cap_equals",... | https://github.com/calliope-project/calliope/blob/9d588fa98ec8eb11065ebb43bcc90d07657b0d43/calliope/backend/pyomo/constraints/milp.py#L298-L333 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/idlelib/configdialog.py | python | GenPage.init_validators | (self) | [] | def init_validators(self):
digits_or_empty_re = re.compile(r'[0-9]*')
def is_digits_or_empty(s):
"Return 's is blank or contains only digits'"
return digits_or_empty_re.fullmatch(s) is not None
self.digits_only = (self.register(is_digits_or_empty), '%P',) | [
"def",
"init_validators",
"(",
"self",
")",
":",
"digits_or_empty_re",
"=",
"re",
".",
"compile",
"(",
"r'[0-9]*'",
")",
"def",
"is_digits_or_empty",
"(",
"s",
")",
":",
"\"Return 's is blank or contains only digits'\"",
"return",
"digits_or_empty_re",
".",
"fullmatch... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/idlelib/configdialog.py#L1786-L1791 | ||||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/shutil.py | python | ignore_patterns | (*patterns) | return _ignore_patterns | Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files | Function that can be used as copytree() ignore parameter. | [
"Function",
"that",
"can",
"be",
"used",
"as",
"copytree",
"()",
"ignore",
"parameter",
"."
] | def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files"""
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns | [
"def",
"ignore_patterns",
"(",
"*",
"patterns",
")",
":",
"def",
"_ignore_patterns",
"(",
"path",
",",
"names",
")",
":",
"ignored_names",
"=",
"[",
"]",
"for",
"pattern",
"in",
"patterns",
":",
"ignored_names",
".",
"extend",
"(",
"fnmatch",
".",
"filter"... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/shutil.py#L152-L162 | |
rll/rllab | ba78e4c16dc492982e648f117875b22af3965579 | rllab/algos/cma_es_lib.py | python | OOOptimizer.stop | (self) | abstract method, return satisfied termination conditions in
a dictionary like ``{'termination reason': value, ...}``,
for example ``{'tolfun': 1e-12}``, or the empty dictionary ``{}``.
The implementation of `stop()` should prevent an infinite
loop. | abstract method, return satisfied termination conditions in
a dictionary like ``{'termination reason': value, ...}``,
for example ``{'tolfun': 1e-12}``, or the empty dictionary ``{}``.
The implementation of `stop()` should prevent an infinite
loop. | [
"abstract",
"method",
"return",
"satisfied",
"termination",
"conditions",
"in",
"a",
"dictionary",
"like",
"{",
"termination",
"reason",
":",
"value",
"...",
"}",
"for",
"example",
"{",
"tolfun",
":",
"1e",
"-",
"12",
"}",
"or",
"the",
"empty",
"dictionary",... | def stop(self):
"""abstract method, return satisfied termination conditions in
a dictionary like ``{'termination reason': value, ...}``,
for example ``{'tolfun': 1e-12}``, or the empty dictionary ``{}``.
The implementation of `stop()` should prevent an infinite
loop.
"""
raise NotImplementedError('method stop() is not implemented') | [
"def",
"stop",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'method stop() is not implemented'",
")"
] | https://github.com/rll/rllab/blob/ba78e4c16dc492982e648f117875b22af3965579/rllab/algos/cma_es_lib.py#L1982-L1990 | ||
edgewall/trac | beb3e4eaf1e0a456d801a50a8614ecab06de29fc | tracopt/versioncontrol/svn/svn_fs.py | python | SubversionRepository.get_node | (self, path, rev=None) | return SubversionNode(path, rev, self, self.pool) | Produce a `SubversionNode` from given path and optionally revision
specifications. No revision given means use the latest. | Produce a `SubversionNode` from given path and optionally revision
specifications. No revision given means use the latest. | [
"Produce",
"a",
"SubversionNode",
"from",
"given",
"path",
"and",
"optionally",
"revision",
"specifications",
".",
"No",
"revision",
"given",
"means",
"use",
"the",
"latest",
"."
] | def get_node(self, path, rev=None):
"""Produce a `SubversionNode` from given path and optionally revision
specifications. No revision given means use the latest.
"""
path = path or ''
if path and path != '/' and path[-1] == '/':
path = path[:-1]
rev = self.normalize_rev(rev) or self.youngest_rev
return SubversionNode(path, rev, self, self.pool) | [
"def",
"get_node",
"(",
"self",
",",
"path",
",",
"rev",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"''",
"if",
"path",
"and",
"path",
"!=",
"'/'",
"and",
"path",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"path",
"=",
"path",
"[",
":",
"-"... | https://github.com/edgewall/trac/blob/beb3e4eaf1e0a456d801a50a8614ecab06de29fc/tracopt/versioncontrol/svn/svn_fs.py#L411-L419 | |
Yam-cn/pyalgotrade-cn | d8ba00e9a2bb609e3e925db17a9a97929c57f672 | pyalgotrade/talibext/indicator.py | python | CDLGAPSIDESIDEWHITE | (barDs, count) | return call_talib_with_ohlc(barDs, count, talib.CDLGAPSIDESIDEWHITE) | Up/Down-gap side-by-side white lines | Up/Down-gap side-by-side white lines | [
"Up",
"/",
"Down",
"-",
"gap",
"side",
"-",
"by",
"-",
"side",
"white",
"lines"
] | def CDLGAPSIDESIDEWHITE(barDs, count):
"""Up/Down-gap side-by-side white lines"""
return call_talib_with_ohlc(barDs, count, talib.CDLGAPSIDESIDEWHITE) | [
"def",
"CDLGAPSIDESIDEWHITE",
"(",
"barDs",
",",
"count",
")",
":",
"return",
"call_talib_with_ohlc",
"(",
"barDs",
",",
"count",
",",
"talib",
".",
"CDLGAPSIDESIDEWHITE",
")"
] | https://github.com/Yam-cn/pyalgotrade-cn/blob/d8ba00e9a2bb609e3e925db17a9a97929c57f672/pyalgotrade/talibext/indicator.py#L325-L327 | |
misterch0c/shadowbroker | e3a069bea47a2c1009697941ac214adc6f90aa8d | windows/Resources/Python/Core/Lib/pydoc.py | python | Helper.getline | (self, prompt) | Read one line, using raw_input when available. | Read one line, using raw_input when available. | [
"Read",
"one",
"line",
"using",
"raw_input",
"when",
"available",
"."
] | def getline(self, prompt):
"""Read one line, using raw_input when available."""
if self.input is sys.stdin:
return raw_input(prompt)
else:
self.output.write(prompt)
self.output.flush()
return self.input.readline() | [
"def",
"getline",
"(",
"self",
",",
"prompt",
")",
":",
"if",
"self",
".",
"input",
"is",
"sys",
".",
"stdin",
":",
"return",
"raw_input",
"(",
"prompt",
")",
"else",
":",
"self",
".",
"output",
".",
"write",
"(",
"prompt",
")",
"self",
".",
"outpu... | https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/pydoc.py#L1656-L1663 | ||
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/Centos_5.9/paramiko/sftp_server.py | python | SFTPServer._convert_pflags | (self, pflags) | return flags | convert SFTP-style open() flags to python's os.open() flags | convert SFTP-style open() flags to python's os.open() flags | [
"convert",
"SFTP",
"-",
"style",
"open",
"()",
"flags",
"to",
"python",
"s",
"os",
".",
"open",
"()",
"flags"
] | def _convert_pflags(self, pflags):
"convert SFTP-style open() flags to python's os.open() flags"
if (pflags & SFTP_FLAG_READ) and (pflags & SFTP_FLAG_WRITE):
flags = os.O_RDWR
elif pflags & SFTP_FLAG_WRITE:
flags = os.O_WRONLY
else:
flags = os.O_RDONLY
if pflags & SFTP_FLAG_APPEND:
flags |= os.O_APPEND
if pflags & SFTP_FLAG_CREATE:
flags |= os.O_CREAT
if pflags & SFTP_FLAG_TRUNC:
flags |= os.O_TRUNC
if pflags & SFTP_FLAG_EXCL:
flags |= os.O_EXCL
return flags | [
"def",
"_convert_pflags",
"(",
"self",
",",
"pflags",
")",
":",
"if",
"(",
"pflags",
"&",
"SFTP_FLAG_READ",
")",
"and",
"(",
"pflags",
"&",
"SFTP_FLAG_WRITE",
")",
":",
"flags",
"=",
"os",
".",
"O_RDWR",
"elif",
"pflags",
"&",
"SFTP_FLAG_WRITE",
":",
"fl... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_5.9/paramiko/sftp_server.py#L298-L314 | |
usb-tools/ViewSB | 0318dc7b3d7da290a841b1681e62a0654c8c82e6 | viewsb/frontends/tui.py | python | VSBPacketNode.load_child_keys | (self) | return list(range(len(packet.subordinate_packets))) | Return all of the child packet indices for the given node. | Return all of the child packet indices for the given node. | [
"Return",
"all",
"of",
"the",
"child",
"packet",
"indices",
"for",
"the",
"given",
"node",
"."
] | def load_child_keys(self):
""" Return all of the child packet indices for the given node. """
# Our child packets are just organized into a list,
# so we can just return a range of the same length as our list.
packet = self.get_value()
return list(range(len(packet.subordinate_packets))) | [
"def",
"load_child_keys",
"(",
"self",
")",
":",
"# Our child packets are just organized into a list,",
"# so we can just return a range of the same length as our list.",
"packet",
"=",
"self",
".",
"get_value",
"(",
")",
"return",
"list",
"(",
"range",
"(",
"len",
"(",
"... | https://github.com/usb-tools/ViewSB/blob/0318dc7b3d7da290a841b1681e62a0654c8c82e6/viewsb/frontends/tui.py#L529-L535 | |
CedricGuillemet/Imogen | ee417b42747ed5b46cb11b02ef0c3630000085b3 | bin/Lib/asyncio/unix_events.py | python | _UnixSelectorEventLoop.remove_signal_handler | (self, sig) | return True | Remove a handler for a signal. UNIX only.
Return True if a signal handler was removed, False if not. | Remove a handler for a signal. UNIX only. | [
"Remove",
"a",
"handler",
"for",
"a",
"signal",
".",
"UNIX",
"only",
"."
] | def remove_signal_handler(self, sig):
"""Remove a handler for a signal. UNIX only.
Return True if a signal handler was removed, False if not.
"""
self._check_signal(sig)
try:
del self._signal_handlers[sig]
except KeyError:
return False
if sig == signal.SIGINT:
handler = signal.default_int_handler
else:
handler = signal.SIG_DFL
try:
signal.signal(sig, handler)
except OSError as exc:
if exc.errno == errno.EINVAL:
raise RuntimeError(f'sig {sig} cannot be caught')
else:
raise
if not self._signal_handlers:
try:
signal.set_wakeup_fd(-1)
except (ValueError, OSError) as exc:
logger.info('set_wakeup_fd(-1) failed: %s', exc)
return True | [
"def",
"remove_signal_handler",
"(",
"self",
",",
"sig",
")",
":",
"self",
".",
"_check_signal",
"(",
"sig",
")",
"try",
":",
"del",
"self",
".",
"_signal_handlers",
"[",
"sig",
"]",
"except",
"KeyError",
":",
"return",
"False",
"if",
"sig",
"==",
"signa... | https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/asyncio/unix_events.py#L130-L160 | |
Yelp/clusterman | 54beef89c01a2681aafd1fbb93b6ad5f6252d6cf | clusterman/simulator/simulated_spot_fleet_resource_group.py | python | SimulatedSpotFleetResourceGroup.modify_target_capacity | (self, target_capacity, *, dry_run=False) | Modify the requested capacity for a particular spot fleet
:param target_capacity: desired capacity after this operation | Modify the requested capacity for a particular spot fleet | [
"Modify",
"the",
"requested",
"capacity",
"for",
"a",
"particular",
"spot",
"fleet"
] | def modify_target_capacity(self, target_capacity, *, dry_run=False):
""" Modify the requested capacity for a particular spot fleet
:param target_capacity: desired capacity after this operation
"""
if dry_run:
return
curr_capacity = self.fulfilled_capacity
self.__target_capacity = target_capacity
if curr_capacity < target_capacity:
self._increase_capacity_to_target(target_capacity) | [
"def",
"modify_target_capacity",
"(",
"self",
",",
"target_capacity",
",",
"*",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"dry_run",
":",
"return",
"curr_capacity",
"=",
"self",
".",
"fulfilled_capacity",
"self",
".",
"__target_capacity",
"=",
"target_capaci... | https://github.com/Yelp/clusterman/blob/54beef89c01a2681aafd1fbb93b6ad5f6252d6cf/clusterman/simulator/simulated_spot_fleet_resource_group.py#L86-L97 | ||
blawar/nut | 2cf351400418399a70164987e28670309f6c9cb5 | nut/aes128.py | python | AESXTS.decrypt_sector | (self, data, tweak) | return out | [] | def decrypt_sector(self, data, tweak):
if len(data) % self.block_size:
raise ValueError('Data is not aligned to block size!')
out = b''
tweak = self.K2.encrypt(uhx('%032X' % tweak))
while data:
a = self.K1.decrypt(sxor(data[:0x10], tweak))
out += sxor(tweak, a)
_t = int(hx(tweak[::-1]), 16)
_t <<= 1
if _t & (1 << 128):
_t ^= ((1 << 128) | (0x87))
tweak = uhx('%032X' % _t)[::-1]
data = data[0x10:]
return out | [
"def",
"decrypt_sector",
"(",
"self",
",",
"data",
",",
"tweak",
")",
":",
"if",
"len",
"(",
"data",
")",
"%",
"self",
".",
"block_size",
":",
"raise",
"ValueError",
"(",
"'Data is not aligned to block size!'",
")",
"out",
"=",
"b''",
"tweak",
"=",
"self",... | https://github.com/blawar/nut/blob/2cf351400418399a70164987e28670309f6c9cb5/nut/aes128.py#L136-L150 | |||
iwonbigbro/gsync | 03db22fe826f073e56877918b0acb7b4ba908f18 | libgsync/drive/__init__.py | python | DriveFileObject.write | (self, data) | Writes data into the file at the current offset.
Currently not supported by Google Drive API. | Writes data into the file at the current offset. | [
"Writes",
"data",
"into",
"the",
"file",
"at",
"the",
"current",
"offset",
"."
] | def write(self, data):
"""
Writes data into the file at the current offset.
Currently not supported by Google Drive API.
"""
data = data # static_cast<void>(data) for pylint
self._required_open()
self._required_modes([ "w", "a" ]) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
"# static_cast<void>(data) for pylint",
"self",
".",
"_required_open",
"(",
")",
"self",
".",
"_required_modes",
"(",
"[",
"\"w\"",
",",
"\"a\"",
"]",
")"
] | https://github.com/iwonbigbro/gsync/blob/03db22fe826f073e56877918b0acb7b4ba908f18/libgsync/drive/__init__.py#L226-L234 | ||
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/dev/bdf_vectorized/cards/elements/solid/cpenta15.py | python | CPENTA15.update | (self, maps) | maps = {
'node_id' : nid_map,
'property' : pid_map,
} | maps = {
'node_id' : nid_map,
'property' : pid_map,
} | [
"maps",
"=",
"{",
"node_id",
":",
"nid_map",
"property",
":",
"pid_map",
"}"
] | def update(self, maps):
"""
maps = {
'node_id' : nid_map,
'property' : pid_map,
}
"""
if self.n:
eid_map = maps['element']
nid_map = maps['node']
pid_map = maps['property']
for i, (eid, pid, nids) in enumerate(zip(self.element_id, self.property_id, self.node_ids)):
print(self.print_card(i))
self.element_id[i] = eid_map[eid]
self.property_id[i] = pid_map[pid]
self.node_ids[i, 0] = nid_map[nids[0]]
self.node_ids[i, 1] = nid_map[nids[1]]
self.node_ids[i, 2] = nid_map[nids[2]]
self.node_ids[i, 3] = nid_map[nids[3]]
self.node_ids[i, 4] = nid_map[nids[4]]
self.node_ids[i, 5] = nid_map[nids[5]]
self.node_ids[i, 6] = nid_map[nids[6]]
self.node_ids[i, 7] = nid_map[nids[7]]
self.node_ids[i, 8] = nid_map[nids[8]]
self.node_ids[i, 9] = nid_map[nids[9]]
self.node_ids[i, 10] = nid_map[nids[10]]
self.node_ids[i, 11] = nid_map[nids[11]]
self.node_ids[i, 12] = nid_map[nids[12]]
self.node_ids[i, 13] = nid_map[nids[13]]
self.node_ids[i, 14] = nid_map[nids[14]] | [
"def",
"update",
"(",
"self",
",",
"maps",
")",
":",
"if",
"self",
".",
"n",
":",
"eid_map",
"=",
"maps",
"[",
"'element'",
"]",
"nid_map",
"=",
"maps",
"[",
"'node'",
"]",
"pid_map",
"=",
"maps",
"[",
"'property'",
"]",
"for",
"i",
",",
"(",
"ei... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized/cards/elements/solid/cpenta15.py#L59-L88 | ||
iopsgroup/imoocc | de810eb6d4c1697b7139305925a5b0ba21225f3f | extra_apps/xadmin/plugins/xversion.py | python | BaseReversionView._order_version_queryset | (self, queryset) | return queryset.order_by("pk") | Applies the correct ordering to the given version queryset. | Applies the correct ordering to the given version queryset. | [
"Applies",
"the",
"correct",
"ordering",
"to",
"the",
"given",
"version",
"queryset",
"."
] | def _order_version_queryset(self, queryset):
"""Applies the correct ordering to the given version queryset."""
if self.history_latest_first:
return queryset.order_by("-pk")
return queryset.order_by("pk") | [
"def",
"_order_version_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"if",
"self",
".",
"history_latest_first",
":",
"return",
"queryset",
".",
"order_by",
"(",
"\"-pk\"",
")",
"return",
"queryset",
".",
"order_by",
"(",
"\"pk\"",
")"
] | https://github.com/iopsgroup/imoocc/blob/de810eb6d4c1697b7139305925a5b0ba21225f3f/extra_apps/xadmin/plugins/xversion.py#L176-L180 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/pip/_internal/req/req_file.py | python | parse_requirements | (
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None # type: Optional[bool]
) | Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option. | Parse a requirements file and yield InstallRequirement instances. | [
"Parse",
"a",
"requirements",
"file",
"and",
"yield",
"InstallRequirement",
"instances",
"."
] | def parse_requirements(
filename, # type: str
finder=None, # type: Optional[PackageFinder]
comes_from=None, # type: Optional[str]
options=None, # type: Optional[optparse.Values]
session=None, # type: Optional[PipSession]
constraint=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
use_pep517=None # type: Optional[bool]
):
# type: (...) -> Iterator[InstallRequirement]
"""Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.PackageFinder.
:param comes_from: Origin description of requirements.
:param options: cli options.
:param session: Instance of pip.download.PipSession.
:param constraint: If true, parsing a constraint file rather than
requirements file.
:param wheel_cache: Instance of pip.wheel.WheelCache
:param use_pep517: Value of the --use-pep517 option.
"""
if session is None:
raise TypeError(
"parse_requirements() missing 1 required keyword argument: "
"'session'"
)
_, content = get_file_content(
filename, comes_from=comes_from, session=session
)
lines_enum = preprocess(content, options)
for line_number, line in lines_enum:
req_iter = process_line(line, filename, line_number, finder,
comes_from, options, session, wheel_cache,
use_pep517=use_pep517, constraint=constraint)
for req in req_iter:
yield req | [
"def",
"parse_requirements",
"(",
"filename",
",",
"# type: str",
"finder",
"=",
"None",
",",
"# type: Optional[PackageFinder]",
"comes_from",
"=",
"None",
",",
"# type: Optional[str]",
"options",
"=",
"None",
",",
"# type: Optional[optparse.Values]",
"session",
"=",
"N... | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_internal/req/req_file.py#L74-L114 | ||
openstack/neutron | fb229fb527ac8b95526412f7762d90826ac41428 | neutron/services/trunk/utils.py | python | get_agent_types_by_host | (context, host) | return agent_types | Return the agent types registered on the host. | Return the agent types registered on the host. | [
"Return",
"the",
"agent",
"types",
"registered",
"on",
"the",
"host",
"."
] | def get_agent_types_by_host(context, host):
"""Return the agent types registered on the host."""
agent_types = []
core_plugin = directory.get_plugin()
if extensions.is_extension_supported(core_plugin, 'agent'):
agents = core_plugin.get_agents(
context.elevated(), filters={'host': [host]})
agent_types = [a['agent_type'] for a in agents]
return agent_types | [
"def",
"get_agent_types_by_host",
"(",
"context",
",",
"host",
")",
":",
"agent_types",
"=",
"[",
"]",
"core_plugin",
"=",
"directory",
".",
"get_plugin",
"(",
")",
"if",
"extensions",
".",
"is_extension_supported",
"(",
"core_plugin",
",",
"'agent'",
")",
":"... | https://github.com/openstack/neutron/blob/fb229fb527ac8b95526412f7762d90826ac41428/neutron/services/trunk/utils.py#L21-L29 | |
man-group/PythonTrainingExercises | 00a2435649fcf53fdafede2d10b40f08463728fe | Beginners/ListsTuples/solutions.py | python | select_first_items | () | return [v[0] for v in x] | Select first item on each list. | Select first item on each list. | [
"Select",
"first",
"item",
"on",
"each",
"list",
"."
] | def select_first_items():
"""Select first item on each list."""
x = [('A','x'), ('B','y'), ('C','z')]
return [v[0] for v in x] | [
"def",
"select_first_items",
"(",
")",
":",
"x",
"=",
"[",
"(",
"'A'",
",",
"'x'",
")",
",",
"(",
"'B'",
",",
"'y'",
")",
",",
"(",
"'C'",
",",
"'z'",
")",
"]",
"return",
"[",
"v",
"[",
"0",
"]",
"for",
"v",
"in",
"x",
"]"
] | https://github.com/man-group/PythonTrainingExercises/blob/00a2435649fcf53fdafede2d10b40f08463728fe/Beginners/ListsTuples/solutions.py#L130-L133 | |
jieter/django-tables2 | ce392ee2ee341d7180345a6113919cf9a3925f16 | django_tables2/columns/base.py | python | Library.register | (self, column) | return column | [] | def register(self, column):
if not hasattr(column, "from_field"):
raise ImproperlyConfigured(
"{} is not a subclass of Column".format(column.__class__.__name__)
)
self.columns.append(column)
return column | [
"def",
"register",
"(",
"self",
",",
"column",
")",
":",
"if",
"not",
"hasattr",
"(",
"column",
",",
"\"from_field\"",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"{} is not a subclass of Column\"",
".",
"format",
"(",
"column",
".",
"__class__",
".",
"_... | https://github.com/jieter/django-tables2/blob/ce392ee2ee341d7180345a6113919cf9a3925f16/django_tables2/columns/base.py#L26-L32 | |||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/ctx_base.py | python | StandardBaseContext.fneg | (ctx, x, **kwargs) | return -ctx.convert(x) | [] | def fneg(ctx, x, **kwargs):
return -ctx.convert(x) | [
"def",
"fneg",
"(",
"ctx",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"-",
"ctx",
".",
"convert",
"(",
"x",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/ctx_base.py#L80-L81 | |||
PySimpleGUI/PySimpleGUI | 6c0d1fb54f493d45e90180b322fbbe70f7a5af3c | DemoPrograms/Demo_User_Settings.py | python | settings_window | () | Create and interact with a "settings window". You can a similar pair of functions to your
code to add a "settings" feature. | Create and interact with a "settings window". You can a similar pair of functions to your
code to add a "settings" feature. | [
"Create",
"and",
"interact",
"with",
"a",
"settings",
"window",
".",
"You",
"can",
"a",
"similar",
"pair",
"of",
"functions",
"to",
"your",
"code",
"to",
"add",
"a",
"settings",
"feature",
"."
] | def settings_window():
"""
Create and interact with a "settings window". You can a similar pair of functions to your
code to add a "settings" feature.
"""
window = make_window()
current_theme = sg.theme()
while True:
event, values = window.read()
if event in (sg.WINDOW_CLOSED, 'Exit'):
break
if event == 'Save':
# Save some of the values as user settings
sg.user_settings_set_entry('input', values['-IN-'])
sg.user_settings_set_entry('theme', values['-LISTBOX-'][0])
sg.user_settings_set_entry('option1', values['-CB1-'])
sg.user_settings_set_entry('option2', values['-CB2-'])
# if the theme was changed, restart the window
if values['-LISTBOX-'][0] != current_theme:
current_theme = values['-LISTBOX-'][0]
window.close()
window = make_window() | [
"def",
"settings_window",
"(",
")",
":",
"window",
"=",
"make_window",
"(",
")",
"current_theme",
"=",
"sg",
".",
"theme",
"(",
")",
"while",
"True",
":",
"event",
",",
"values",
"=",
"window",
".",
"read",
"(",
")",
"if",
"event",
"in",
"(",
"sg",
... | https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/DemoPrograms/Demo_User_Settings.py#L52-L76 | ||
savon-noir/python-libnmap | 8f442747a7a16969309d6f7653ad1b13a3a99bae | libnmap/plugins/s3.py | python | NmapS3Plugin.getall | (self, dict_filter=None) | return nmapreportlist | :rtype: List of tuple
:return: list of key/report
:todo: add a filter capability | :rtype: List of tuple
:return: list of key/report
:todo: add a filter capability | [
":",
"rtype",
":",
"List",
"of",
"tuple",
":",
"return",
":",
"list",
"of",
"key",
"/",
"report",
":",
"todo",
":",
"add",
"a",
"filter",
"capability"
] | def getall(self, dict_filter=None):
"""
:rtype: List of tuple
:return: list of key/report
:todo: add a filter capability
"""
nmapreportlist = []
for key in bucket_lister(self.bucket):
if isinstance(key, Key):
nmapreportjson = json.loads(key.get_contents_as_string())
nmapreport = NmapParser.parse_fromdict(nmapreportjson)
nmapreportlist.append((key.key, nmapreport))
return nmapreportlist | [
"def",
"getall",
"(",
"self",
",",
"dict_filter",
"=",
"None",
")",
":",
"nmapreportlist",
"=",
"[",
"]",
"for",
"key",
"in",
"bucket_lister",
"(",
"self",
".",
"bucket",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"Key",
")",
":",
"nmapreportjson",... | https://github.com/savon-noir/python-libnmap/blob/8f442747a7a16969309d6f7653ad1b13a3a99bae/libnmap/plugins/s3.py#L117-L129 | |
savio-code/fern-wifi-cracker | 0da03aba988c66dfa131a45824568abb84b7704a | Fern-Wifi-Cracker/core/wpa.py | python | wpa_attack_dialog.wpa_key_found | (self) | [] | def wpa_key_found(self):
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("%s/resources/wifi_4.png"%(os.getcwd())))
self.attack_button.setIcon(icon)
self.attack_button.setText('Attack')
self.new_automate_key()
wpa_key_read = reader('/tmp/fern-log/WPA-DUMP/wpa_key.txt')
self.finished_label.setEnabled(True)
self.finished_label.setText('<font color=yellow>Finished</font>')
self.key_label.setEnabled(True)
self.cancel_wpa_attack()
self.key_label.setVisible(True)
self.key_label.setText('<font color=red>WPA KEY: %s</font>'%(wpa_key_read))
self.set_Progressbar_color("green")
if self.wpa_key_commit == 0:
set_key_entries(variables.victim_access_point,variables.victim_mac,'WPA',wpa_key_read,variables.victim_channel) #Add WPA Key to Database Here
self.update_database_label_signal.emit()
self.wpa_key_commit += 1
self.isfinished = True
self.tip_display() | [
"def",
"wpa_key_found",
"(",
"self",
")",
":",
"icon",
"=",
"QtGui",
".",
"QIcon",
"(",
")",
"icon",
".",
"addPixmap",
"(",
"QtGui",
".",
"QPixmap",
"(",
"\"%s/resources/wifi_4.png\"",
"%",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
")",
")",
"self",
"... | https://github.com/savio-code/fern-wifi-cracker/blob/0da03aba988c66dfa131a45824568abb84b7704a/Fern-Wifi-Cracker/core/wpa.py#L429-L452 | ||||
mila-iqia/myia | 56774a39579b4ec4123f44843ad4ca688acc859b | myia/abstract/ref.py | python | Context.__init__ | (self, parent, g, argkey) | Initialize the Context. | Initialize the Context. | [
"Initialize",
"the",
"Context",
"."
] | def __init__(self, parent, g, argkey):
"""Initialize the Context."""
assert argkey is not None
self.parent = parent
self.graph = g
self.argkey = argkey
self.parent_cache = dict(parent.parent_cache) if parent else {}
self.parent_cache[g] = self
self._hash = hash((self.parent, self.graph, self.argkey)) | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"g",
",",
"argkey",
")",
":",
"assert",
"argkey",
"is",
"not",
"None",
"self",
".",
"parent",
"=",
"parent",
"self",
".",
"graph",
"=",
"g",
"self",
".",
"argkey",
"=",
"argkey",
"self",
".",
"par... | https://github.com/mila-iqia/myia/blob/56774a39579b4ec4123f44843ad4ca688acc859b/myia/abstract/ref.py#L26-L34 | ||
fastnlp/fastNLP | fb645d370f4cc1b00c7dbb16c1ff4542327c46e5 | fastNLP/modules/encoder/_elmo.py | python | ElmobiLm.forward | (self, inputs, seq_len) | return output | r"""
:param inputs: batch_size x max_len x embed_size
:param seq_len: batch_size
:return: torch.FloatTensor. num_layers x batch_size x max_len x hidden_size | r""" | [
"r"
] | def forward(self, inputs, seq_len):
r"""
:param inputs: batch_size x max_len x embed_size
:param seq_len: batch_size
:return: torch.FloatTensor. num_layers x batch_size x max_len x hidden_size
"""
max_len = inputs.size(1)
sort_lens, sort_idx = torch.sort(seq_len, dim=0, descending=True)
inputs = inputs[sort_idx]
inputs = nn.utils.rnn.pack_padded_sequence(inputs, sort_lens.cpu(), batch_first=True)
output, _ = self._lstm_forward(inputs, None)
_, unsort_idx = torch.sort(sort_idx, dim=0, descending=False)
output = output[:, unsort_idx]
return output | [
"def",
"forward",
"(",
"self",
",",
"inputs",
",",
"seq_len",
")",
":",
"max_len",
"=",
"inputs",
".",
"size",
"(",
"1",
")",
"sort_lens",
",",
"sort_idx",
"=",
"torch",
".",
"sort",
"(",
"seq_len",
",",
"dim",
"=",
"0",
",",
"descending",
"=",
"Tr... | https://github.com/fastnlp/fastNLP/blob/fb645d370f4cc1b00c7dbb16c1ff4542327c46e5/fastNLP/modules/encoder/_elmo.py#L309-L323 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/lib2to3/pytree.py | python | Leaf._prefix_getter | (self) | return self._prefix | The whitespace and comments preceding this token in the input. | The whitespace and comments preceding this token in the input. | [
"The",
"whitespace",
"and",
"comments",
"preceding",
"this",
"token",
"in",
"the",
"input",
"."
] | def _prefix_getter(self):
"""
The whitespace and comments preceding this token in the input.
"""
return self._prefix | [
"def",
"_prefix_getter",
"(",
"self",
")",
":",
"return",
"self",
".",
"_prefix"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/lib2to3/pytree.py#L417-L421 | |
magenta/magenta | be6558f1a06984faff6d6949234f5fe9ad0ffdb5 | magenta/models/gansynth/lib/data_normalizer.py | python | SpecgramsSimpleNormalizer.compute | (self, data_np) | return np.asarray([m_a, m_b, p_a, p_b]) | [] | def compute(self, data_np):
m_a, m_b = _range_normalizer(data_np[:, :, :, 0], self._margin)
p_a, p_b = _range_normalizer(data_np[:, :, :, 1], self._margin)
return np.asarray([m_a, m_b, p_a, p_b]) | [
"def",
"compute",
"(",
"self",
",",
"data_np",
")",
":",
"m_a",
",",
"m_b",
"=",
"_range_normalizer",
"(",
"data_np",
"[",
":",
",",
":",
",",
":",
",",
"0",
"]",
",",
"self",
".",
"_margin",
")",
"p_a",
",",
"p_b",
"=",
"_range_normalizer",
"(",
... | https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/gansynth/lib/data_normalizer.py#L154-L157 | |||
sukeesh/Jarvis | 2dc2a550b59ea86cca5dfb965661b6fc4cabd434 | jarviscli/plugins/converted.py | python | do_umbrella | (self, s) | will inform you if you might need an umbrella or not. | will inform you if you might need an umbrella or not. | [
"will",
"inform",
"you",
"if",
"you",
"might",
"need",
"an",
"umbrella",
"or",
"not",
"."
] | def do_umbrella(self, s):
"""will inform you if you might need an umbrella or not."""
self = self._jarvis
s = 'umbrella'
weather_pinpoint.main(self.memory, self, s) | [
"def",
"do_umbrella",
"(",
"self",
",",
"s",
")",
":",
"self",
"=",
"self",
".",
"_jarvis",
"s",
"=",
"'umbrella'",
"weather_pinpoint",
".",
"main",
"(",
"self",
".",
"memory",
",",
"self",
",",
"s",
")"
] | https://github.com/sukeesh/Jarvis/blob/2dc2a550b59ea86cca5dfb965661b6fc4cabd434/jarviscli/plugins/converted.py#L82-L87 | ||
tdeboissiere/DeepLearningImplementations | 5c4094880fc6992cca2d6e336463b2525026f6e2 | DeconvNet/KerasDeconv.py | python | DeconvNet.get_layers | (self) | return list_layers_name | Returns the layers of the network
:returns: returns the layers of the network
:rtype: list | Returns the layers of the network | [
"Returns",
"the",
"layers",
"of",
"the",
"network"
] | def get_layers(self):
"""Returns the layers of the network
:returns: returns the layers of the network
:rtype: list
"""
list_layers = self.model.layers
list_layers_name = [l.name for l in list_layers]
return list_layers_name | [
"def",
"get_layers",
"(",
"self",
")",
":",
"list_layers",
"=",
"self",
".",
"model",
".",
"layers",
"list_layers_name",
"=",
"[",
"l",
".",
"name",
"for",
"l",
"in",
"list_layers",
"]",
"return",
"list_layers_name"
] | https://github.com/tdeboissiere/DeepLearningImplementations/blob/5c4094880fc6992cca2d6e336463b2525026f6e2/DeconvNet/KerasDeconv.py#L156-L165 | |
presslabs/gitfs | 12886ec5b9c7e103bfcab0cd37a8333873382fae | gitfs/views/current.py | python | CurrentView.mkdir | (self, path, mode) | return result | [] | def mkdir(self, path, mode):
result = super(CurrentView, self).mkdir(path, mode)
keep_path = "{}/.keep".format(path)
full_path = self.repo._full_path(keep_path)
if not os.path.exists(keep_path):
global writers
fh = os.open(full_path, os.O_WRONLY | os.O_CREAT)
writers += 1
log.info("CurrentView: Open %s for write", full_path)
super(CurrentView, self).chmod(keep_path, 0o644)
self.dirty[fh] = {
"message": "Create the {} directory".format(path),
"stage": True,
}
self.release(keep_path, fh)
log.debug("CurrentView: Created directory %s with mode %s", path, mode)
return result | [
"def",
"mkdir",
"(",
"self",
",",
"path",
",",
"mode",
")",
":",
"result",
"=",
"super",
"(",
"CurrentView",
",",
"self",
")",
".",
"mkdir",
"(",
"path",
",",
"mode",
")",
"keep_path",
"=",
"\"{}/.keep\"",
".",
"format",
"(",
"path",
")",
"full_path"... | https://github.com/presslabs/gitfs/blob/12886ec5b9c7e103bfcab0cd37a8333873382fae/gitfs/views/current.py#L109-L131 | |||
kpreid/shinysdr | 25022d36903ff67e036e82a22b6555a12a4d8e8a | shinysdr/math.py | python | to_dB | (x) | return 10 * log10(x) | Convert multiplicative value to dB value. | Convert multiplicative value to dB value. | [
"Convert",
"multiplicative",
"value",
"to",
"dB",
"value",
"."
] | def to_dB(x):
"""Convert multiplicative value to dB value."""
return 10 * log10(x) | [
"def",
"to_dB",
"(",
"x",
")",
":",
"return",
"10",
"*",
"log10",
"(",
"x",
")"
] | https://github.com/kpreid/shinysdr/blob/25022d36903ff67e036e82a22b6555a12a4d8e8a/shinysdr/math.py#L37-L39 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/app_manager/models.py | python | LoadUpdateAction.get_paths | (self) | [] | def get_paths(self):
for path in super(LoadUpdateAction, self).get_paths():
yield path
for path in self.preload.keys():
yield path | [
"def",
"get_paths",
"(",
"self",
")",
":",
"for",
"path",
"in",
"super",
"(",
"LoadUpdateAction",
",",
"self",
")",
".",
"get_paths",
"(",
")",
":",
"yield",
"path",
"for",
"path",
"in",
"self",
".",
"preload",
".",
"keys",
"(",
")",
":",
"yield",
... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/models.py#L552-L557 | ||||
django-cms/django-cms | 272d62ced15a86c9d34eb21700e6358bb08388ea | cms/utils/placeholder.py | python | get_placeholder_conf | (setting, placeholder, template=None, default=None) | return default | Returns the placeholder configuration for a given setting. The key would for
example be 'plugins' or 'name'.
Resulting value will be the last from:
CMS_PLACEHOLDER_CONF[None] (global)
CMS_PLACEHOLDER_CONF['template'] (if template is given)
CMS_PLACEHOLDER_CONF['placeholder']
CMS_PLACEHOLDER_CONF['template placeholder'] (if template is given) | Returns the placeholder configuration for a given setting. The key would for
example be 'plugins' or 'name'. | [
"Returns",
"the",
"placeholder",
"configuration",
"for",
"a",
"given",
"setting",
".",
"The",
"key",
"would",
"for",
"example",
"be",
"plugins",
"or",
"name",
"."
] | def get_placeholder_conf(setting, placeholder, template=None, default=None):
"""
Returns the placeholder configuration for a given setting. The key would for
example be 'plugins' or 'name'.
Resulting value will be the last from:
CMS_PLACEHOLDER_CONF[None] (global)
CMS_PLACEHOLDER_CONF['template'] (if template is given)
CMS_PLACEHOLDER_CONF['placeholder']
CMS_PLACEHOLDER_CONF['template placeholder'] (if template is given)
"""
if placeholder:
keys = []
placeholder_conf = get_cms_setting('PLACEHOLDER_CONF')
# 1st level
if template:
keys.append(u'%s %s' % (template, placeholder))
# 2nd level
keys.append(placeholder)
# 3rd level
if template:
keys.append(template)
# 4th level
keys.append(None)
for key in keys:
try:
conf = placeholder_conf[key]
value = conf.get(setting, None)
if value is not None:
return value
inherit = conf.get('inherit')
if inherit:
if ' ' in inherit:
inherit = inherit.split(' ')
else:
inherit = (None, inherit)
value = get_placeholder_conf(setting, inherit[1], inherit[0], default)
if value is not None:
return value
except KeyError:
continue
return default | [
"def",
"get_placeholder_conf",
"(",
"setting",
",",
"placeholder",
",",
"template",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"placeholder",
":",
"keys",
"=",
"[",
"]",
"placeholder_conf",
"=",
"get_cms_setting",
"(",
"'PLACEHOLDER_CONF'",
")",... | https://github.com/django-cms/django-cms/blob/272d62ced15a86c9d34eb21700e6358bb08388ea/cms/utils/placeholder.py#L35-L78 | |
ReceiptManager/receipt-parser-legacy | 3da117b993311e296860fc1b08aab51d7afcefaa | receipt_parser_core/enhancer.py | python | find_images | (folder) | :param folder: str
Path to folder to search
:return: generator of str
List of images in folder | :param folder: str
Path to folder to search
:return: generator of str
List of images in folder | [
":",
"param",
"folder",
":",
"str",
"Path",
"to",
"folder",
"to",
"search",
":",
"return",
":",
"generator",
"of",
"str",
"List",
"of",
"images",
"in",
"folder"
] | def find_images(folder):
"""
:param folder: str
Path to folder to search
:return: generator of str
List of images in folder
"""
for file in os.listdir(folder):
full_path = os.path.join(folder, file)
if os.path.isfile(full_path):
try:
_ = Image.open(full_path) # if constructor succeeds
yield file
except:
pass | [
"def",
"find_images",
"(",
"folder",
")",
":",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"folder",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"file",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fu... | https://github.com/ReceiptManager/receipt-parser-legacy/blob/3da117b993311e296860fc1b08aab51d7afcefaa/receipt_parser_core/enhancer.py#L52-L67 | ||
ChunyuanLI/Optimus | f63f4a7ca10aea022978500a37d72dd53a37a576 | code/examples/big_ae/run_lm_vae_pretraining.py | python | train | (args, train_dataloader, model_vae, encoder_tokenizer, decoder_tokenizer, table_name) | return global_step, tr_loss / global_step | Train the model | Train the model | [
"Train",
"the",
"model"
] | def train(args, train_dataloader, model_vae, encoder_tokenizer, decoder_tokenizer, table_name):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
# train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
# train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
if args.max_steps > 0:
t_total = args.max_steps
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
else:
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
# Prepare optimizer and schedule (linear warmup and decay)
# model_encoder, model_decoder, model_connector = model_vae.encoder, model_vae.decoder, model_vae.linear
no_decay = ['bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in model_vae.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
{'params': [p for n, p in model_vae.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = WarmupLinearSchedule(optimizer, warmup_steps=args.warmup_steps, t_total=t_total)
if args.fp16:
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model_vae, optimizer = amp.initialize(model_vae, optimizer, opt_level=args.fp16_opt_level)
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model_vae = torch.nn.DataParallel(model_vae, device_ids=range(args.n_gpu)).to(args.device)
# Distributed training (should be after apex fp16 initialization)
if args.local_rank != -1:
model_vae = torch.nn.parallel.DistributedDataParallel(model_vae, device_ids=[args.local_rank],
output_device=args.local_rank,
find_unused_parameters=True)
files = Path(args.train_data_file)
num_files = len(list(files.glob('*seq64*.json')))
# Train!
logger.info("***** Running training *****")
logger.info(" Num files = %d", num_files)
logger.info(" Num examples of first file = %d", train_dataloader.num_examples)
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size * args.gradient_accumulation_steps * (torch.distributed.get_world_size() if args.local_rank != -1 else 1))
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 0
tr_loss, logging_loss = 0.0, 0.0
model_vae.zero_grad()
num_train_epochs_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0])
n_iter = int(args.num_train_epochs) * len(train_dataloader)
beta_t_list = frange_cycle_zero_linear(n_iter, start=0.0, stop=args.beta, n_cycle=1, ratio_increase=args.ratio_increase, ratio_zero=args.ratio_zero)
tmp_list = []
dict_token_length = defaultdict(int)
set_seed(args) # Added here for reproducibility (even between python 2 and 3)
for epoch in num_train_epochs_iterator:
train_dataloader.reset()
for idx_file in range(num_files-1):
logger.info(f"Epoch {epoch}, File idx {train_dataloader.file_idx}")
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
for step, batch in enumerate(epoch_iterator):
tokenized_text0, tokenized_text1, tokenized_text_lengths = batch
dict_token_length[ tokenized_text_lengths[0,0].item() ] += 1
# continue
# tokenized_text0 = tokenized_text0.to(args.device)
# tokenized_text1 = tokenized_text1.to(args.device)
# prepare input-output data for reconstruction
inputs, labels = mask_tokens(tokenized_text0, encoder_tokenizer, args) if args.mlm else (tokenized_text0, tokenized_text1)
labels = tokenized_text1
tokenized_text1 = tokenized_text1.to(args.device)
inputs = inputs.to(args.device)
labels = labels.to(args.device)
model_vae.train()
beta_t = 0.0 # beta_t_list[step + epoch*len(epoch_iterator)]
model_vae.module.args.beta = beta_t
if beta_t == 0.0:
model_vae.module.args.fb_mode = 0
else:
model_vae.module.args.fb_mode = 1
if args.use_deterministic_connect:
model_vae.module.args.fb_mode = 2
loss_rec, loss_kl, loss = model_vae(inputs, labels)
loss_rec = loss_rec.mean() # mean() to average on multi-gpu parallel training
loss_kl = loss_kl.mean()
loss = loss.mean()
if args.use_philly:
print("PROGRESS: {}%".format(round(100 * (step + epoch*len(epoch_iterator) ) /(int(args.num_train_epochs) * len(epoch_iterator)) , 4)))
print("EVALERR: {}%".format(loss_rec))
epoch_iterator.set_description(
(
f'iter: {step + epoch*len(epoch_iterator) }; file:{idx_file}; loss: {loss.item():.3f}; '
f'loss_rec: {loss_rec.item():.3f}; loss_kl: {loss_kl.item():.3f}; '
f'beta: {model_vae.module.args.beta:.3f}'
)
)
# if global_step % 5 == 0:
# row = {
# 'PartitionKey': 'MILU_Rule_Rule_Template',
# 'RowKey': str(datetime.now()),
# 'ExpName' : args.ExpName,
# 'iter': str( step + epoch*len(epoch_iterator) ),
# 'loss': str( loss.item()),
# 'loss_rec': str(loss_rec.item()),
# 'loss_kl': str(loss_kl.item()),
# 'beta': str(model_vae.args.beta)
# }
# # pdb.set_trace()
# ts.insert_entity(table_name, row)
# pdb.set_trace()
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
tr_loss += loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.fp16:
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
else:
torch.nn.utils.clip_grad_norm_(model_vae.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step() # Update learning rate schedule
model_vae.zero_grad()
global_step += 1
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
# Log metrics
if args.local_rank == -1 and args.evaluate_during_training: # Only evaluate when single GPU otherwise metrics may not average well
results = evaluate(args, model_vae, encoder_tokenizer, decoder_tokenizer)
for key, value in results.items():
tb_writer.add_scalar('eval_{}'.format(key), value, global_step)
tb_writer.add_scalar('lr', scheduler.get_lr()[0], global_step)
tb_writer.add_scalar('loss', (tr_loss - logging_loss)/args.logging_steps, global_step)
logging_loss = tr_loss
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
# Save encoder model checkpoint
output_encoder_dir = os.path.join(args.output_dir, 'checkpoint-encoder-{}'.format(global_step))
if not os.path.exists(output_encoder_dir):
os.makedirs(output_encoder_dir)
model_encoder_to_save = model_vae.module.encoder if hasattr(model_vae, 'module') else model_vae.encoder # Take care of distributed/parallel training
if args.use_philly:
save_solid = False
while not save_solid:
try:
model_encoder_to_save.save_pretrained(output_encoder_dir)
torch.save(args, os.path.join(output_encoder_dir, 'training_args.bin'))
logger.info("Saving model checkpoint to %s", output_encoder_dir)
save_solid = True
except:
pass
else:
model_encoder_to_save.save_pretrained(output_encoder_dir)
torch.save(args, os.path.join(output_encoder_dir, 'training_args.bin'))
logger.info("Saving model checkpoint to %s", output_encoder_dir)
# Save decoder model checkpoint
output_decoder_dir = os.path.join(args.output_dir, 'checkpoint-decoder-{}'.format(global_step))
if not os.path.exists(output_decoder_dir):
os.makedirs(output_decoder_dir)
model_decoder_to_save = model_vae.module.decoder if hasattr(model_vae, 'module') else model_vae.decoder # Take care of distributed/parallel training
if args.use_philly:
save_solid = False
while not save_solid:
try:
model_decoder_to_save.save_pretrained(output_decoder_dir)
torch.save(args, os.path.join(output_decoder_dir, 'training_args.bin'))
logger.info("Saving model checkpoint to %s", output_decoder_dir)
save_solid = True
except:
pass
else:
model_decoder_to_save.save_pretrained(output_decoder_dir)
torch.save(args, os.path.join(output_decoder_dir, 'training_args.bin'))
logger.info("Saving model checkpoint to %s", output_decoder_dir)
if args.max_steps > 0 and global_step > args.max_steps:
epoch_iterator.close()
break
if args.max_steps > 0 and global_step > args.max_steps:
train_iterator.close()
break
# print(dict_token_length)
# with open('wikipedia_stats.json', 'w') as fp:
# json.dump(dict_token_length, fp)
if args.local_rank in [-1, 0]:
tb_writer.close()
return global_step, tr_loss / global_step | [
"def",
"train",
"(",
"args",
",",
"train_dataloader",
",",
"model_vae",
",",
"encoder_tokenizer",
",",
"decoder_tokenizer",
",",
"table_name",
")",
":",
"if",
"args",
".",
"local_rank",
"in",
"[",
"-",
"1",
",",
"0",
"]",
":",
"tb_writer",
"=",
"SummaryWri... | https://github.com/ChunyuanLI/Optimus/blob/f63f4a7ca10aea022978500a37d72dd53a37a576/code/examples/big_ae/run_lm_vae_pretraining.py#L122-L372 | |
etetoolkit/ete | 2b207357dc2a40ccad7bfd8f54964472c72e4726 | ete3/phyloxml/_phyloxml.py | python | Accession.exportLiteral | (self, outfile, level, name_='Accession') | [] | def exportLiteral(self, outfile, level, name_='Accession'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) | [
"def",
"exportLiteral",
"(",
"self",
",",
"outfile",
",",
"level",
",",
"name_",
"=",
"'Accession'",
")",
":",
"level",
"+=",
"1",
"self",
".",
"exportLiteralAttributes",
"(",
"outfile",
",",
"level",
",",
"[",
"]",
",",
"name_",
")",
"if",
"self",
"."... | https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/phyloxml/_phyloxml.py#L1783-L1789 | ||||
sphinx-doc/sphinx | e79681c76843c1339863b365747079b2d662d0c1 | sphinx/util/inspect.py | python | evaluate_signature | (sig: inspect.Signature, globalns: Dict = None, localns: Dict = None
) | return sig.replace(parameters=parameters, return_annotation=return_annotation) | Evaluate unresolved type annotations in a signature object. | Evaluate unresolved type annotations in a signature object. | [
"Evaluate",
"unresolved",
"type",
"annotations",
"in",
"a",
"signature",
"object",
"."
] | def evaluate_signature(sig: inspect.Signature, globalns: Dict = None, localns: Dict = None
) -> inspect.Signature:
"""Evaluate unresolved type annotations in a signature object."""
def evaluate_forwardref(ref: ForwardRef, globalns: Dict, localns: Dict) -> Any:
"""Evaluate a forward reference."""
if sys.version_info > (3, 9):
return ref._evaluate(globalns, localns, frozenset())
else:
return ref._evaluate(globalns, localns)
def evaluate(annotation: Any, globalns: Dict, localns: Dict) -> Any:
"""Evaluate unresolved type annotation."""
try:
if isinstance(annotation, str):
ref = ForwardRef(annotation, True)
annotation = evaluate_forwardref(ref, globalns, localns)
if isinstance(annotation, ForwardRef):
annotation = evaluate_forwardref(ref, globalns, localns)
elif isinstance(annotation, str):
# might be a ForwardRef'ed annotation in overloaded functions
ref = ForwardRef(annotation, True)
annotation = evaluate_forwardref(ref, globalns, localns)
except (NameError, TypeError):
# failed to evaluate type. skipped.
pass
return annotation
if globalns is None:
globalns = {}
if localns is None:
localns = globalns
parameters = list(sig.parameters.values())
for i, param in enumerate(parameters):
if param.annotation:
annotation = evaluate(param.annotation, globalns, localns)
parameters[i] = param.replace(annotation=annotation)
return_annotation = sig.return_annotation
if return_annotation:
return_annotation = evaluate(return_annotation, globalns, localns)
return sig.replace(parameters=parameters, return_annotation=return_annotation) | [
"def",
"evaluate_signature",
"(",
"sig",
":",
"inspect",
".",
"Signature",
",",
"globalns",
":",
"Dict",
"=",
"None",
",",
"localns",
":",
"Dict",
"=",
"None",
")",
"->",
"inspect",
".",
"Signature",
":",
"def",
"evaluate_forwardref",
"(",
"ref",
":",
"F... | https://github.com/sphinx-doc/sphinx/blob/e79681c76843c1339863b365747079b2d662d0c1/sphinx/util/inspect.py#L699-L743 | |
pytroll/satpy | 09e51f932048f98cce7919a4ff8bd2ec01e1ae98 | satpy/readers/modis_l2.py | python | ModisL2HDFFileHandler.is_imapp_mask_byte1 | (self) | return "mask_byte1" in self.filetype_info["file_type"] | Get if this file is the IMAPP 'mask_byte1' file type. | Get if this file is the IMAPP 'mask_byte1' file type. | [
"Get",
"if",
"this",
"file",
"is",
"the",
"IMAPP",
"mask_byte1",
"file",
"type",
"."
] | def is_imapp_mask_byte1(self):
"""Get if this file is the IMAPP 'mask_byte1' file type."""
return "mask_byte1" in self.filetype_info["file_type"] | [
"def",
"is_imapp_mask_byte1",
"(",
"self",
")",
":",
"return",
"\"mask_byte1\"",
"in",
"self",
".",
"filetype_info",
"[",
"\"file_type\"",
"]"
] | https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/modis_l2.py#L73-L75 | |
cournape/Bento | 37de23d784407a7c98a4a15770ffc570d5f32d70 | bento/commands/dependency.py | python | CommandDataProvider.__getitem__ | (self, command_name) | return self._data[command_name] | [] | def __getitem__(self, command_name):
return self._data[command_name] | [
"def",
"__getitem__",
"(",
"self",
",",
"command_name",
")",
":",
"return",
"self",
".",
"_data",
"[",
"command_name",
"]"
] | https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/commands/dependency.py#L94-L95 | |||
cyrozap/python-vipaccess | 787ac6ee1e0b80f35fb7710c17f2fe6b3329882b | vipaccess/utils.py | python | get_token_from_response | (response_xml) | Retrieve relevant token details from Symantec's provisioning
response. | Retrieve relevant token details from Symantec's provisioning
response. | [
"Retrieve",
"relevant",
"token",
"details",
"from",
"Symantec",
"s",
"provisioning",
"response",
"."
] | def get_token_from_response(response_xml):
'''Retrieve relevant token details from Symantec's provisioning
response.'''
# Define an arbitrary namespace "vipservice" because xpath doesn't like it
# when it's "None"
namespace = {'vipservice':'http://www.verisign.com/2006/08/vipservice'}
tree = etree.fromstring(response_xml)
result = tree.xpath(
'//vipservice:Status/vipservice:StatusMessage',
namespaces=namespace
)[0].text
if result == 'Success':
token = {}
container = tree.xpath(
'//vipservice:SecretContainer',
namespaces=namespace
)[0]
encryption_method = container.xpath(
'//vipservice:EncryptionMethod',
namespaces=namespace
)[0]
token['salt'] = base64.b64decode(
encryption_method.xpath('//vipservice:PBESalt',
namespaces=namespace
)[0].text
)
token['iteration_count'] = int(
encryption_method.xpath(
'//vipservice:PBEIterationCount',
namespaces=namespace
)[0].text
)
token['iv'] = base64.b64decode(
encryption_method.xpath(
'//vipservice:IV',
namespaces=namespace
)[0].text
)
device = container.xpath('//vipservice:Device', namespaces=namespace)[0]
secret = device.xpath('//vipservice:Secret', namespaces=namespace)[0]
data = secret.xpath('//vipservice:Data', namespaces=namespace)[0]
expiry = secret.xpath('//vipservice:Expiry', namespaces=namespace)[0]
token['id'] = secret.attrib['Id']
token['cipher'] = base64.b64decode(
data.xpath(
'//vipservice:Cipher',
namespaces=namespace
)[0].text
)
token['digest'] = base64.b64decode(
data.xpath(
'//vipservice:Digest',
namespaces=namespace
)[0].text
)
token['expiry'] = expiry.text
return token | [
"def",
"get_token_from_response",
"(",
"response_xml",
")",
":",
"# Define an arbitrary namespace \"vipservice\" because xpath doesn't like it",
"# when it's \"None\"",
"namespace",
"=",
"{",
"'vipservice'",
":",
"'http://www.verisign.com/2006/08/vipservice'",
"}",
"tree",
"=",
"et... | https://github.com/cyrozap/python-vipaccess/blob/787ac6ee1e0b80f35fb7710c17f2fe6b3329882b/vipaccess/utils.py#L149-L210 | ||
w3h/isf | 6faf0a3df185465ec17369c90ccc16e2a03a1870 | lib/thirdparty/nmap/nmap.py | python | PortScannerHostDict.sctp | (self, port) | return self['sctp'][port] | :returns: info for sctp port | :returns: info for sctp port | [
":",
"returns",
":",
"info",
"for",
"sctp",
"port"
] | def sctp(self, port):
"""
:returns: info for sctp port
"""
assert type(port) is int, 'Wrong type for [port], should be an int [was {0}]'.format(type(port))
return self['sctp'][port] | [
"def",
"sctp",
"(",
"self",
",",
"port",
")",
":",
"assert",
"type",
"(",
"port",
")",
"is",
"int",
",",
"'Wrong type for [port], should be an int [was {0}]'",
".",
"format",
"(",
"type",
"(",
"port",
")",
")",
"return",
"self",
"[",
"'sctp'",
"]",
"[",
... | https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/nmap/nmap.py#L1035-L1042 | |
lmco/laikaboss | eb04b4c4fe7bf3fc86c26b8a37451d99e6fc9c17 | laikaboss/util.py | python | get_module_arguments | (sm) | return module, arg_dict | Extracts arguments from scan module declarations inside the yara dispatcher.
Format is:
SCAN_MODULE(arg1=value1,arg2=value2, arg3=value3)
Arguments:
sm --- a string in the format above
Returns:
A tuple containing the module name and a dictionary containing key value pairs. | Extracts arguments from scan module declarations inside the yara dispatcher.
Format is:
SCAN_MODULE(arg1=value1,arg2=value2, arg3=value3)
Arguments:
sm --- a string in the format above | [
"Extracts",
"arguments",
"from",
"scan",
"module",
"declarations",
"inside",
"the",
"yara",
"dispatcher",
".",
"Format",
"is",
":",
"SCAN_MODULE",
"(",
"arg1",
"=",
"value1",
"arg2",
"=",
"value2",
"arg3",
"=",
"value3",
")",
"Arguments",
":",
"sm",
"---",
... | def get_module_arguments(sm):
'''
Extracts arguments from scan module declarations inside the yara dispatcher.
Format is:
SCAN_MODULE(arg1=value1,arg2=value2, arg3=value3)
Arguments:
sm --- a string in the format above
Returns:
A tuple containing the module name and a dictionary containing key value pairs.
'''
# Set default values
arg_dict = {}
module = ""
# Look for parentheses, indicating arguments exist
open_paren = sm.find('(')
try:
if open_paren > 0:
# Get the name of the module
module = sm[:open_paren]
logging.debug("si_dispatch,util - Attempting to extract arguments from %s" % sm)
args_string = sm[open_paren + 1:len(sm) - 1]
args_list = args_string.split(',')
for arg in args_list:
kvp = arg.split('=')
arg_dict[kvp[0].strip()] = kvp[1].strip()
else:
module = sm
except (QuitScanException, GlobalScanTimeoutError, GlobalModuleTimeoutError):
raise
except Exception as e:
logging.exception("error parsing module arguments, details below: ")
return module, arg_dict | [
"def",
"get_module_arguments",
"(",
"sm",
")",
":",
"# Set default values",
"arg_dict",
"=",
"{",
"}",
"module",
"=",
"\"\"",
"# Look for parentheses, indicating arguments exist",
"open_paren",
"=",
"sm",
".",
"find",
"(",
"'('",
")",
"try",
":",
"if",
"open_paren... | https://github.com/lmco/laikaboss/blob/eb04b4c4fe7bf3fc86c26b8a37451d99e6fc9c17/laikaboss/util.py#L450-L483 | |
pyamg/pyamg | e3fb6feaad2358e681f2f4affae3205bfe9a2350 | pyamg/relaxation/smoothing.py | python | setup_cgnr | (lvl, tol=1e-12, maxiter=1, M=None, callback=None,
residuals=None) | return smoother | Set up CGNR smoothing. | Set up CGNR smoothing. | [
"Set",
"up",
"CGNR",
"smoothing",
"."
] | def setup_cgnr(lvl, tol=1e-12, maxiter=1, M=None, callback=None,
residuals=None):
"""Set up CGNR smoothing."""
def smoother(A, x, b):
x[:] = (
cgnr(
A,
b,
x0=x,
tol=tol,
maxiter=maxiter,
M=M,
callback=callback,
residuals=residuals)[0]).reshape(
x.shape)
return smoother | [
"def",
"setup_cgnr",
"(",
"lvl",
",",
"tol",
"=",
"1e-12",
",",
"maxiter",
"=",
"1",
",",
"M",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"residuals",
"=",
"None",
")",
":",
"def",
"smoother",
"(",
"A",
",",
"x",
",",
"b",
")",
":",
"x",
... | https://github.com/pyamg/pyamg/blob/e3fb6feaad2358e681f2f4affae3205bfe9a2350/pyamg/relaxation/smoothing.py#L668-L683 | |
smicallef/spiderfoot | fd4bf9394c9ab3ecc90adc3115c56349fb23165b | sfscan.py | python | SpiderFootScanner.__init__ | (self, scanName, scanId, targetValue, targetType, moduleList, globalOpts, start=True) | Initialize SpiderFootScanner object.
Args:
scanName (str): name of the scan
scanId (str): unique ID of the scan
targetValue (str): scan target
targetType (str): scan target type
moduleList (list): list of modules to run
globalOpts (dict): scan options
start (bool): start the scan immediately
Raises:
TypeError: arg type was invalid
ValueError: arg value was invalid
Todo:
Eventually change this to be able to control multiple scan instances | Initialize SpiderFootScanner object. | [
"Initialize",
"SpiderFootScanner",
"object",
"."
] | def __init__(self, scanName, scanId, targetValue, targetType, moduleList, globalOpts, start=True):
"""Initialize SpiderFootScanner object.
Args:
scanName (str): name of the scan
scanId (str): unique ID of the scan
targetValue (str): scan target
targetType (str): scan target type
moduleList (list): list of modules to run
globalOpts (dict): scan options
start (bool): start the scan immediately
Raises:
TypeError: arg type was invalid
ValueError: arg value was invalid
Todo:
Eventually change this to be able to control multiple scan instances
"""
if not isinstance(globalOpts, dict):
raise TypeError(f"globalOpts is {type(globalOpts)}; expected dict()")
if not globalOpts:
raise ValueError("globalOpts is empty")
self.__config = deepcopy(globalOpts)
self.__dbh = SpiderFootDb(self.__config)
if not isinstance(scanName, str):
raise TypeError(f"scanName is {type(scanName)}; expected str()")
if not scanName:
raise ValueError("scanName value is blank")
self.__scanName = scanName
if not isinstance(scanId, str):
raise TypeError(f"scanId is {type(scanId)}; expected str()")
if not scanId:
raise ValueError("scanId value is blank")
if not isinstance(targetValue, str):
raise TypeError(f"targetValue is {type(targetValue)}; expected str()")
if not targetValue:
raise ValueError("targetValue value is blank")
self.__targetValue = targetValue
if not isinstance(targetType, str):
raise TypeError(f"targetType is {type(targetType)}; expected str()")
if not targetType:
raise ValueError("targetType value is blank")
self.__targetType = targetType
if not isinstance(moduleList, list):
raise TypeError(f"moduleList is {type(moduleList)}; expected list()")
if not moduleList:
raise ValueError("moduleList is empty")
self.__moduleList = moduleList
self.__sf = SpiderFoot(self.__config)
self.__sf.dbh = self.__dbh
# Create a unique ID for this scan in the back-end DB.
if scanId:
self.__scanId = scanId
else:
self.__scanId = SpiderFootHelpers.genScanInstanceId()
self.__sf.scanId = self.__scanId
self.__dbh.scanInstanceCreate(self.__scanId, self.__scanName, self.__targetValue)
# Create our target
try:
self.__target = SpiderFootTarget(self.__targetValue, self.__targetType)
except (TypeError, ValueError) as e:
self.__sf.status(f"Scan [{self.__scanId}] failed: {e}")
self.__setStatus("ERROR-FAILED", None, time.time() * 1000)
raise ValueError(f"Invalid target: {e}")
# Save the config current set for this scan
self.__config['_modulesenabled'] = self.__moduleList
self.__dbh.scanConfigSet(self.__scanId, self.__sf.configSerialize(deepcopy(self.__config)))
# Process global options that point to other places for data
# If a proxy server was specified, set it up
proxy_type = self.__config.get('_socks1type')
if proxy_type:
# TODO: allow DNS lookup to be configurable when using a proxy
# - proxy DNS lookup: socks5h:// and socks4a://
# - local DNS lookup: socks5:// and socks4://
if proxy_type == '4':
proxy_proto = 'socks4://'
elif proxy_type == '5':
proxy_proto = 'socks5://'
elif proxy_type == 'HTTP':
proxy_proto = 'http://'
elif proxy_type == 'TOR':
proxy_proto = 'socks5h://'
else:
self.__sf.status(f"Scan [{self.__scanId}] failed: Invalid proxy type: {proxy_type}")
self.__setStatus("ERROR-FAILED", None, time.time() * 1000)
raise ValueError(f"Invalid proxy type: {proxy_type}")
proxy_host = self.__config.get('_socks2addr', '')
if not proxy_host:
self.__sf.status(f"Scan [{self.__scanId}] failed: Proxy type is set ({proxy_type}) but proxy address value is blank")
self.__setStatus("ERROR-FAILED", None, time.time() * 1000)
raise ValueError(f"Proxy type is set ({proxy_type}) but proxy address value is blank")
proxy_port = int(self.__config.get('_socks3port') or 0)
if not proxy_port:
if proxy_type in ['4', '5']:
proxy_port = 1080
elif proxy_type.upper() == 'HTTP':
proxy_port = 8080
elif proxy_type.upper() == 'TOR':
proxy_port = 9050
proxy_username = self.__config.get('_socks4user', '')
proxy_password = self.__config.get('_socks5pwd', '')
if proxy_username or proxy_password:
proxy_auth = f"{proxy_username}:{proxy_password}"
proxy = f"{proxy_proto}{proxy_auth}@{proxy_host}:{proxy_port}"
else:
proxy = f"{proxy_proto}{proxy_host}:{proxy_port}"
self.__sf.debug(f"Using proxy: {proxy}")
self.__sf.socksProxy = proxy
else:
self.__sf.socksProxy = None
# Override the default DNS server
if self.__config['_dnsserver']:
res = dns.resolver.Resolver()
res.nameservers = [self.__config['_dnsserver']]
dns.resolver.override_system_resolver(res)
else:
dns.resolver.restore_system_resolver()
# Set the user agent
self.__config['_useragent'] = self.__sf.optValueToData(self.__config['_useragent'])
# Get internet TLDs
tlddata = self.__sf.cacheGet("internet_tlds", self.__config['_internettlds_cache'])
# If it wasn't loadable from cache, load it from scratch
if tlddata is None:
self.__config['_internettlds'] = self.__sf.optValueToData(self.__config['_internettlds'])
self.__sf.cachePut("internet_tlds", self.__config['_internettlds'])
else:
self.__config["_internettlds"] = tlddata.splitlines()
self.__setStatus("INITIALIZING", time.time() * 1000, None)
self.__sharedThreadPool = SpiderFootThreadPool(threads=self.__config.get("_maxthreads", 3), name='sharedThreadPool')
# Used when module threading is enabled
self.eventQueue = None
if start:
self.__startScan() | [
"def",
"__init__",
"(",
"self",
",",
"scanName",
",",
"scanId",
",",
"targetValue",
",",
"targetType",
",",
"moduleList",
",",
"globalOpts",
",",
"start",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"globalOpts",
",",
"dict",
")",
":",
"raise"... | https://github.com/smicallef/spiderfoot/blob/fd4bf9394c9ab3ecc90adc3115c56349fb23165b/sfscan.py#L54-L219 | ||
IdentityPython/pysaml2 | 6badb32d212257bd83ffcc816f9b625f68281b47 | src/saml2/samlp.py | python | new_id_from_string | (xml_string) | return saml2.create_class_from_xml_string(NewID, xml_string) | [] | def new_id_from_string(xml_string):
return saml2.create_class_from_xml_string(NewID, xml_string) | [
"def",
"new_id_from_string",
"(",
"xml_string",
")",
":",
"return",
"saml2",
".",
"create_class_from_xml_string",
"(",
"NewID",
",",
"xml_string",
")"
] | https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/samlp.py#L247-L248 | |||
tenpy/tenpy | bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff | tenpy/networks/mps.py | python | MPSEnvironment.get_RP | (self, i, store=True) | return RP | Calculate RP at given site from nearest available one.
The returned ``RP_i`` corresponds to the following contraction,
where the M's and the N's are in the 'B' form::
| 'vL' ->---M[i+1]-- ... --M[L-1]----.
| | | |
| | | RP[L-1]
| | | |
| 'vL*' -<---N[i+1]*- ... --N[L-1]*---.
Parameters
----------
i : int
The returned `RP` will contain the contraction *strictly* right of site `i`.
store : bool
Wheter to store the calculated `RP` in `self` (``True``) or discard them (``False``).
Returns
-------
RP_i : :class:`~tenpy.linalg.np_conserved.Array`
Contraction of everything left of site `i`,
with labels ``'vL', 'vL*'`` for `ket`, `bra`. | Calculate RP at given site from nearest available one. | [
"Calculate",
"RP",
"at",
"given",
"site",
"from",
"nearest",
"available",
"one",
"."
] | def get_RP(self, i, store=True):
"""Calculate RP at given site from nearest available one.
The returned ``RP_i`` corresponds to the following contraction,
where the M's and the N's are in the 'B' form::
| 'vL' ->---M[i+1]-- ... --M[L-1]----.
| | | |
| | | RP[L-1]
| | | |
| 'vL*' -<---N[i+1]*- ... --N[L-1]*---.
Parameters
----------
i : int
The returned `RP` will contain the contraction *strictly* right of site `i`.
store : bool
Wheter to store the calculated `RP` in `self` (``True``) or discard them (``False``).
Returns
-------
RP_i : :class:`~tenpy.linalg.np_conserved.Array`
Contraction of everything left of site `i`,
with labels ``'vL', 'vL*'`` for `ket`, `bra`.
"""
# find nearest available RP to the right.
for i0 in range(i, i + self.L):
key = self._RP_keys[self._to_valid_index(i0)]
RP = self.cache.get(key, None)
if RP is not None:
break
# (for finite, RP[-1] should always be set, so we should abort at latest with i0=L-1)
else: # no break called
raise ValueError("No right part in the system???")
age = self.get_RP_age(i0)
for j in range(i0, i, -1):
RP = self._contract_RP(j, RP)
age = age + 1
if store:
self.set_RP(j - 1, RP, age=age)
return RP | [
"def",
"get_RP",
"(",
"self",
",",
"i",
",",
"store",
"=",
"True",
")",
":",
"# find nearest available RP to the right.",
"for",
"i0",
"in",
"range",
"(",
"i",
",",
"i",
"+",
"self",
".",
"L",
")",
":",
"key",
"=",
"self",
".",
"_RP_keys",
"[",
"self... | https://github.com/tenpy/tenpy/blob/bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff/tenpy/networks/mps.py#L4287-L4328 | |
coin-or/rbfopt | 3ba5320a23f04ac3729eff7b55527f2f1e6f9fdd | src/rbfopt/rbfopt_user_black_box.py | python | RbfoptUserBlackBox.get_var_upper | (self) | return self.var_upper | Return the array of upper bounds on the variables.
Returns
-------
List[float]
Upper bounds of the decision variables. | Return the array of upper bounds on the variables. | [
"Return",
"the",
"array",
"of",
"upper",
"bounds",
"on",
"the",
"variables",
"."
] | def get_var_upper(self):
"""Return the array of upper bounds on the variables.
Returns
-------
List[float]
Upper bounds of the decision variables.
"""
return self.var_upper | [
"def",
"get_var_upper",
"(",
"self",
")",
":",
"return",
"self",
".",
"var_upper"
] | https://github.com/coin-or/rbfopt/blob/3ba5320a23f04ac3729eff7b55527f2f1e6f9fdd/src/rbfopt/rbfopt_user_black_box.py#L106-L114 | |
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/op2/op2.py | python | OP2._is_op2_case_equal | (self, table_type: str,
key, a_obj, b_obj,
stop_on_failure: bool=True, debug: bool=False) | return True | Helper method for ``assert_op2_equal``
Parameters
----------
table_type : str
the type of table (e.g., ``displacements``)
key : subcase_id / tuple_obj
subcase_id : int
the subcase_id
tuple_obj : Tuple(???, ???, ...)
the fancy tuple thingy that you see in single subcase buckling...
subcase_id : int
the subcase_id
sort_code : int
1 : SORT1
2 : SORT2
title??? : str
the case title
subtitle??? : str
the case subtitle
superelement_id : str???
the superelement
other terms???
TODO: document better
a_obj : Op2Object()
a RealDisplacementArray, ComplexDisplacementArray, RealSolidStressArray, etc.
for the self model
b_obj : Op2Object()
a RealDisplacementArray, ComplexDisplacementArray, RealSolidStressArray, etc.
for the comparison model
stop_on_failure : bool; default=True
True : Crashes if they're not equal
False : Go to the next object
debug : bool; default=False
give slightly more debugging messages
Returns
-------
is_equal : bool
are the objects equal?
Raises
------
AssertionError/ValueError : stop_on_failure=True and and error occurred
NotImplementedError : this is a sign of an unsupported object | Helper method for ``assert_op2_equal`` | [
"Helper",
"method",
"for",
"assert_op2_equal"
] | def _is_op2_case_equal(self, table_type: str,
key, a_obj, b_obj,
stop_on_failure: bool=True, debug: bool=False) -> bool:
"""
Helper method for ``assert_op2_equal``
Parameters
----------
table_type : str
the type of table (e.g., ``displacements``)
key : subcase_id / tuple_obj
subcase_id : int
the subcase_id
tuple_obj : Tuple(???, ???, ...)
the fancy tuple thingy that you see in single subcase buckling...
subcase_id : int
the subcase_id
sort_code : int
1 : SORT1
2 : SORT2
title??? : str
the case title
subtitle??? : str
the case subtitle
superelement_id : str???
the superelement
other terms???
TODO: document better
a_obj : Op2Object()
a RealDisplacementArray, ComplexDisplacementArray, RealSolidStressArray, etc.
for the self model
b_obj : Op2Object()
a RealDisplacementArray, ComplexDisplacementArray, RealSolidStressArray, etc.
for the comparison model
stop_on_failure : bool; default=True
True : Crashes if they're not equal
False : Go to the next object
debug : bool; default=False
give slightly more debugging messages
Returns
-------
is_equal : bool
are the objects equal?
Raises
------
AssertionError/ValueError : stop_on_failure=True and and error occurred
NotImplementedError : this is a sign of an unsupported object
"""
# check the name (e.g., RealDisplacementArray vs. ComplexDisplacementArray)
aname = a_obj.__class__.__name__
bname = b_obj.__class__.__name__
if not aname == bname:
self.log.warning(f'type(a)={aname} type(b)={bname}')
return False
if aname == 'PARAM': # TODO: update this
return True
# does this ever hit?
if not any(word in aname for word in ['Array', 'Eigenvalues', 'GridPointWeight']):
msg = f'{aname} is not an Array ... assume equal'
self.log.warning(msg)
raise NotImplementedError(f'{aname} __eq__')
#continue
# use the array methods to check for equality
# TODO: this can crash
try:
is_not_equal = a_obj != b_obj
except ValueError:
if stop_on_failure:
raise
if is_not_equal:
self.log.warning(f'key={key} table_type={table_type!r} are not equal; class_name={aname!r}')
return False
return True | [
"def",
"_is_op2_case_equal",
"(",
"self",
",",
"table_type",
":",
"str",
",",
"key",
",",
"a_obj",
",",
"b_obj",
",",
"stop_on_failure",
":",
"bool",
"=",
"True",
",",
"debug",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"# check the name (e.g., Rea... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/op2.py#L251-L331 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_env.py | python | Yedit.process_edits | (edits, yamlfile) | return {'changed': len(results) > 0, 'results': results} | run through a list of edits and process them one-by-one | run through a list of edits and process them one-by-one | [
"run",
"through",
"a",
"list",
"of",
"edits",
"and",
"process",
"them",
"one",
"-",
"by",
"-",
"one"
] | def process_edits(edits, yamlfile):
'''run through a list of edits and process them one-by-one'''
results = []
for edit in edits:
value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
if edit.get('action') == 'update':
# pylint: disable=line-too-long
curr_value = Yedit.get_curr_value(
Yedit.parse_value(edit.get('curr_value')),
edit.get('curr_value_format'))
rval = yamlfile.update(edit['key'],
value,
edit.get('index'),
curr_value)
elif edit.get('action') == 'append':
rval = yamlfile.append(edit['key'], value)
else:
rval = yamlfile.put(edit['key'], value)
if rval[0]:
results.append({'key': edit['key'], 'edit': rval[1]})
return {'changed': len(results) > 0, 'results': results} | [
"def",
"process_edits",
"(",
"edits",
",",
"yamlfile",
")",
":",
"results",
"=",
"[",
"]",
"for",
"edit",
"in",
"edits",
":",
"value",
"=",
"Yedit",
".",
"parse_value",
"(",
"edit",
"[",
"'value'",
"]",
",",
"edit",
".",
"get",
"(",
"'value_type'",
"... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_env.py#L715-L740 | |
beetbox/beets | 2fea53c34dd505ba391cb345424e0613901c8025 | beetsplug/beatport.py | python | BeatportPlugin.candidates | (self, items, artist, release, va_likely, extra_tags=None) | Returns a list of AlbumInfo objects for beatport search results
matching release and artist (if not various). | Returns a list of AlbumInfo objects for beatport search results
matching release and artist (if not various). | [
"Returns",
"a",
"list",
"of",
"AlbumInfo",
"objects",
"for",
"beatport",
"search",
"results",
"matching",
"release",
"and",
"artist",
"(",
"if",
"not",
"various",
")",
"."
] | def candidates(self, items, artist, release, va_likely, extra_tags=None):
"""Returns a list of AlbumInfo objects for beatport search results
matching release and artist (if not various).
"""
if va_likely:
query = release
else:
query = f'{artist} {release}'
try:
return self._get_releases(query)
except BeatportAPIError as e:
self._log.debug('API Error: {0} (query: {1})', e, query)
return [] | [
"def",
"candidates",
"(",
"self",
",",
"items",
",",
"artist",
",",
"release",
",",
"va_likely",
",",
"extra_tags",
"=",
"None",
")",
":",
"if",
"va_likely",
":",
"query",
"=",
"release",
"else",
":",
"query",
"=",
"f'{artist} {release}'",
"try",
":",
"r... | https://github.com/beetbox/beets/blob/2fea53c34dd505ba391cb345424e0613901c8025/beetsplug/beatport.py#L353-L365 | ||
fossasia/x-mario-center | fe67afe28d995dcf4e2498e305825a4859566172 | softwarecenter/ui/gtk3/panes/availablepane.py | python | AvailablePane.on_db_reopen | (self, db) | Called when the database is reopened. | Called when the database is reopened. | [
"Called",
"when",
"the",
"database",
"is",
"reopened",
"."
] | def on_db_reopen(self, db):
"""Called when the database is reopened."""
super(AvailablePane, self).on_db_reopen(db)
self.refresh_apps()
if self.app_details_view:
self.app_details_view.refresh_app() | [
"def",
"on_db_reopen",
"(",
"self",
",",
"db",
")",
":",
"super",
"(",
"AvailablePane",
",",
"self",
")",
".",
"on_db_reopen",
"(",
"db",
")",
"self",
".",
"refresh_apps",
"(",
")",
"if",
"self",
".",
"app_details_view",
":",
"self",
".",
"app_details_vi... | https://github.com/fossasia/x-mario-center/blob/fe67afe28d995dcf4e2498e305825a4859566172/softwarecenter/ui/gtk3/panes/availablepane.py#L599-L604 | ||
Antergos/Cnchi | 13ac2209da9432d453e0097cf48a107640b563a9 | src/pages/wireless.py | python | Wireless.state_changed | (self, _unused, state) | State has changed | State has changed | [
"State",
"has",
"changed"
] | def state_changed(self, _unused, state):
""" State has changed """
print("state_changed")
self.state = state
if not self.use_wireless.get_active():
return
if state != nm.NM_STATE_CONNECTING:
# TODO: Hide and stop spinner
pass
else:
pass
# TODO: Show and start spinner
# self.spinner.show()
# self.spinner.start()
self.selection_changed(None) | [
"def",
"state_changed",
"(",
"self",
",",
"_unused",
",",
"state",
")",
":",
"print",
"(",
"\"state_changed\"",
")",
"self",
".",
"state",
"=",
"state",
"if",
"not",
"self",
".",
"use_wireless",
".",
"get_active",
"(",
")",
":",
"return",
"if",
"state",
... | https://github.com/Antergos/Cnchi/blob/13ac2209da9432d453e0097cf48a107640b563a9/src/pages/wireless.py#L133-L148 | ||
brainiak/brainiak | ee093597c6c11597b0a59e95b48d2118e40394a5 | brainiak/fcma/classifier.py | python | Classifier._generate_training_data | (self, X1, X2, num_training_samples) | return data | Generate training data for the classifier.
Compute the correlation, do the normalization if necessary,
and compute the kernel matrix if the classifier is
sklearn.svm.SVC with precomputed kernel.
Parameters
----------
X1: a list of numpy array in shape [num_TRs, num_voxels]
X1 contains the activity data filtered by ROIs
and prepared for correlation computation.
All elements of X1 must have the same num_voxels value,
X2: a list of numpy array in shape [num_TRs, num_voxels]
len(X1) equals len(X2).
All elements of X2 must have the same num_voxels value.
X2 can be identical to X1; if not, X1 must have more voxels
than X2 (guaranteed by self.fit).
num_training_samples: Optional[int]
Default None.
The number of samples used in the training,
which is set when the kernel matrix is constructed
portion by portion so the similarity vectors of the
test data have to be computed here.
This is ONLY set when sklearn.svm.SVC with
precomputed kernel is used.
If it is set, only those samples will be used to fit the model.
Returns
-------
data: 2D numpy array
If the classifier is sklearn.svm.SVC with precomputed kernel,
data is the kenrl matrix in shape [num_samples, num_samples];
otherwise, data is in shape [num_samples, num_features] as
the training data. | Generate training data for the classifier. | [
"Generate",
"training",
"data",
"for",
"the",
"classifier",
"."
] | def _generate_training_data(self, X1, X2, num_training_samples):
"""Generate training data for the classifier.
Compute the correlation, do the normalization if necessary,
and compute the kernel matrix if the classifier is
sklearn.svm.SVC with precomputed kernel.
Parameters
----------
X1: a list of numpy array in shape [num_TRs, num_voxels]
X1 contains the activity data filtered by ROIs
and prepared for correlation computation.
All elements of X1 must have the same num_voxels value,
X2: a list of numpy array in shape [num_TRs, num_voxels]
len(X1) equals len(X2).
All elements of X2 must have the same num_voxels value.
X2 can be identical to X1; if not, X1 must have more voxels
than X2 (guaranteed by self.fit).
num_training_samples: Optional[int]
Default None.
The number of samples used in the training,
which is set when the kernel matrix is constructed
portion by portion so the similarity vectors of the
test data have to be computed here.
This is ONLY set when sklearn.svm.SVC with
precomputed kernel is used.
If it is set, only those samples will be used to fit the model.
Returns
-------
data: 2D numpy array
If the classifier is sklearn.svm.SVC with precomputed kernel,
data is the kenrl matrix in shape [num_samples, num_samples];
otherwise, data is in shape [num_samples, num_features] as
the training data.
"""
if not (isinstance(self.clf, sklearn.svm.SVC)
and self.clf.kernel == 'precomputed'):
# correlation computation
corr_data = self._prepare_corerelation_data(X1, X2)
# normalization
normalized_corr_data = self._normalize_correlation_data(
corr_data,
self.epochs_per_subj)
# training data prepare
data = normalized_corr_data.reshape(self.num_samples_,
self.num_features_)
self.training_data_ = None
else: # SVM with precomputed kernel
if self.num_processed_voxels < self.num_voxels_:
if num_training_samples is None:
raise RuntimeError('the kernel matrix will be '
'computed portion by portion, '
'the test samples must be predefined '
'by specifying '
'num_training_samples')
if num_training_samples >= self.num_samples_:
raise ValueError('the number of training samples '
'must be smaller than '
'the number of total samples')
data, normalized_corr_data = \
self._compute_kernel_matrix_in_portion(X1, X2)
if self.num_processed_voxels >= self.num_voxels_:
# training data is in shape
# [num_samples, num_voxels * num_voxels]
self.training_data_ = normalized_corr_data.reshape(
self.num_samples_,
self.num_features_)
else:
# do not store training data because it was partially computed
self.training_data_ = None
logger.debug(
'kernel computation done'
)
return data | [
"def",
"_generate_training_data",
"(",
"self",
",",
"X1",
",",
"X2",
",",
"num_training_samples",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"self",
".",
"clf",
",",
"sklearn",
".",
"svm",
".",
"SVC",
")",
"and",
"self",
".",
"clf",
".",
"kernel",
... | https://github.com/brainiak/brainiak/blob/ee093597c6c11597b0a59e95b48d2118e40394a5/brainiak/fcma/classifier.py#L350-L424 | |
tensorflow/datasets | 2e496976d7d45550508395fb2f35cf958c8a3414 | tensorflow_datasets/image_classification/mnist.py | python | MNIST._split_generators | (self, dl_manager) | return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs=dict(
num_examples=_TRAIN_EXAMPLES,
data_path=mnist_files["train_data"],
label_path=mnist_files["train_labels"],
)),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs=dict(
num_examples=_TEST_EXAMPLES,
data_path=mnist_files["test_data"],
label_path=mnist_files["test_labels"],
)),
] | Returns SplitGenerators. | Returns SplitGenerators. | [
"Returns",
"SplitGenerators",
"."
] | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# Download the full MNIST Database
filenames = {
"train_data": _MNIST_TRAIN_DATA_FILENAME,
"train_labels": _MNIST_TRAIN_LABELS_FILENAME,
"test_data": _MNIST_TEST_DATA_FILENAME,
"test_labels": _MNIST_TEST_LABELS_FILENAME,
}
mnist_files = dl_manager.download_and_extract(
{k: urllib.parse.urljoin(self.URL, v) for k, v in filenames.items()})
# MNIST provides TRAIN and TEST splits, not a VALIDATION split, so we only
# write the TRAIN and TEST splits to disk.
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs=dict(
num_examples=_TRAIN_EXAMPLES,
data_path=mnist_files["train_data"],
label_path=mnist_files["train_labels"],
)),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs=dict(
num_examples=_TEST_EXAMPLES,
data_path=mnist_files["test_data"],
label_path=mnist_files["test_labels"],
)),
] | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"# Download the full MNIST Database",
"filenames",
"=",
"{",
"\"train_data\"",
":",
"_MNIST_TRAIN_DATA_FILENAME",
",",
"\"train_labels\"",
":",
"_MNIST_TRAIN_LABELS_FILENAME",
",",
"\"test_data\"",
":",
... | https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/image_classification/mnist.py#L109-L138 | |
hydroshare/hydroshare | 7ba563b55412f283047fb3ef6da367d41dec58c6 | hs_tools_resource/models.py | python | SupportedSharingStatus._add_sharing_status | (cls, meta_instance, sharing_status_list) | [] | def _add_sharing_status(cls, meta_instance, sharing_status_list):
for sharing_status in sharing_status_list:
# there are three possibilities for res_type_str values:
# list of SupportedSharingStatusChoices object or
# list of string (during normal create or update) or
# integer (during creating new version of the resource)
if isinstance(sharing_status, SupportedSharingStatusChoices):
meta_instance.sharing_status.add(sharing_status)
elif isinstance(sharing_status, int):
# "copy res" or "create a new version"
qs = SupportedSharingStatusChoices.objects.filter(id=sharing_status)
if not qs.exists():
raise ObjectDoesNotExist('Sharing status {0} is not supported').format(
sharing_status)
meta_instance.sharing_status.add(qs[0])
elif isinstance(sharing_status, str):
# create or update res
qs = SupportedSharingStatusChoices.objects. \
filter(description__iexact=sharing_status)
if qs.exists():
meta_instance.sharing_status.add(qs[0])
else:
meta_instance.sharing_status.create(description=sharing_status)
else:
raise ValidationError("No sharing_status parameter "
"was found in the **kwargs list") | [
"def",
"_add_sharing_status",
"(",
"cls",
",",
"meta_instance",
",",
"sharing_status_list",
")",
":",
"for",
"sharing_status",
"in",
"sharing_status_list",
":",
"# there are three possibilities for res_type_str values:",
"# list of SupportedSharingStatusChoices object or",
"# list ... | https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_tools_resource/models.py#L392-L418 | ||||
PlasmaPy/PlasmaPy | 78d63e341216475ce3318e1409296480407c9019 | plasmapy/formulary/parameters.py | python | thermal_pressure | (T: u.K, n: u.m ** -3) | return n * k_B * T | r"""
Return the thermal pressure for a Maxwellian distribution.
**Aliases:** `pth_`
Parameters
----------
T : `~astropy.units.Quantity`
The particle temperature in either kelvin or energy per particle.
n : `~astropy.units.Quantity`
The particle number density in units convertible to m\ :sup:`-3`\ .
Examples
--------
>>> import astropy.units as u
>>> thermal_pressure(1*u.eV, 1e20/u.m**3)
<Quantity 16.021... Pa>
>>> thermal_pressure(10*u.eV, 1e20/u.m**3)
<Quantity 160.21... Pa>
Returns
-------
p_th : `~astropy.units.Quantity`
Thermal pressure.
Raises
------
`TypeError`
The temperature or number density is not a `~astropy.units.Quantity`.
`~astropy.units.UnitConversionError`
If the particle temperature is not in units of temperature or
energy per particle.
Notes
-----
The thermal pressure is given by:
.. math::
T_{th} = n k_B T | r"""
Return the thermal pressure for a Maxwellian distribution. | [
"r",
"Return",
"the",
"thermal",
"pressure",
"for",
"a",
"Maxwellian",
"distribution",
"."
] | def thermal_pressure(T: u.K, n: u.m ** -3) -> u.Pa:
r"""
Return the thermal pressure for a Maxwellian distribution.
**Aliases:** `pth_`
Parameters
----------
T : `~astropy.units.Quantity`
The particle temperature in either kelvin or energy per particle.
n : `~astropy.units.Quantity`
The particle number density in units convertible to m\ :sup:`-3`\ .
Examples
--------
>>> import astropy.units as u
>>> thermal_pressure(1*u.eV, 1e20/u.m**3)
<Quantity 16.021... Pa>
>>> thermal_pressure(10*u.eV, 1e20/u.m**3)
<Quantity 160.21... Pa>
Returns
-------
p_th : `~astropy.units.Quantity`
Thermal pressure.
Raises
------
`TypeError`
The temperature or number density is not a `~astropy.units.Quantity`.
`~astropy.units.UnitConversionError`
If the particle temperature is not in units of temperature or
energy per particle.
Notes
-----
The thermal pressure is given by:
.. math::
T_{th} = n k_B T
"""
return n * k_B * T | [
"def",
"thermal_pressure",
"(",
"T",
":",
"u",
".",
"K",
",",
"n",
":",
"u",
".",
"m",
"**",
"-",
"3",
")",
"->",
"u",
".",
"Pa",
":",
"return",
"n",
"*",
"k_B",
"*",
"T"
] | https://github.com/PlasmaPy/PlasmaPy/blob/78d63e341216475ce3318e1409296480407c9019/plasmapy/formulary/parameters.py#L697-L740 | |
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/v5_1/extension_management/extension_management_client.py | python | ExtensionManagementClient.uninstall_extension_by_name | (self, publisher_name, extension_name, reason=None, reason_code=None) | UninstallExtensionByName.
[Preview API] Uninstall the specified extension from the account / project collection.
:param str publisher_name: Name of the publisher. Example: "fabrikam".
:param str extension_name: Name of the extension. Example: "ops-tools".
:param str reason:
:param str reason_code: | UninstallExtensionByName.
[Preview API] Uninstall the specified extension from the account / project collection.
:param str publisher_name: Name of the publisher. Example: "fabrikam".
:param str extension_name: Name of the extension. Example: "ops-tools".
:param str reason:
:param str reason_code: | [
"UninstallExtensionByName",
".",
"[",
"Preview",
"API",
"]",
"Uninstall",
"the",
"specified",
"extension",
"from",
"the",
"account",
"/",
"project",
"collection",
".",
":",
"param",
"str",
"publisher_name",
":",
"Name",
"of",
"the",
"publisher",
".",
"Example",
... | def uninstall_extension_by_name(self, publisher_name, extension_name, reason=None, reason_code=None):
"""UninstallExtensionByName.
[Preview API] Uninstall the specified extension from the account / project collection.
:param str publisher_name: Name of the publisher. Example: "fabrikam".
:param str extension_name: Name of the extension. Example: "ops-tools".
:param str reason:
:param str reason_code:
"""
route_values = {}
if publisher_name is not None:
route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str')
if extension_name is not None:
route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str')
query_parameters = {}
if reason is not None:
query_parameters['reason'] = self._serialize.query('reason', reason, 'str')
if reason_code is not None:
query_parameters['reasonCode'] = self._serialize.query('reason_code', reason_code, 'str')
self._send(http_method='DELETE',
location_id='fb0da285-f23e-4b56-8b53-3ef5f9f6de66',
version='5.1-preview.1',
route_values=route_values,
query_parameters=query_parameters) | [
"def",
"uninstall_extension_by_name",
"(",
"self",
",",
"publisher_name",
",",
"extension_name",
",",
"reason",
"=",
"None",
",",
"reason_code",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"publisher_name",
"is",
"not",
"None",
":",
"route_valu... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v5_1/extension_management/extension_management_client.py#L111-L133 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/sql/schema.py | python | Index.bind | (self) | return self.table.bind | Return the connectable associated with this Index. | Return the connectable associated with this Index. | [
"Return",
"the",
"connectable",
"associated",
"with",
"this",
"Index",
"."
] | def bind(self):
"""Return the connectable associated with this Index."""
return self.table.bind | [
"def",
"bind",
"(",
"self",
")",
":",
"return",
"self",
".",
"table",
".",
"bind"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/sql/schema.py#L3814-L3817 | |
dropbox/dropbox-sdk-python | 015437429be224732990041164a21a0501235db1 | dropbox/team_log.py | python | EventDetails.get_emm_create_usage_report_details | (self) | return self._value | Only call this if :meth:`is_emm_create_usage_report_details` is true.
:rtype: EmmCreateUsageReportDetails | Only call this if :meth:`is_emm_create_usage_report_details` is true. | [
"Only",
"call",
"this",
"if",
":",
"meth",
":",
"is_emm_create_usage_report_details",
"is",
"true",
"."
] | def get_emm_create_usage_report_details(self):
"""
Only call this if :meth:`is_emm_create_usage_report_details` is true.
:rtype: EmmCreateUsageReportDetails
"""
if not self.is_emm_create_usage_report_details():
raise AttributeError("tag 'emm_create_usage_report_details' not set")
return self._value | [
"def",
"get_emm_create_usage_report_details",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_emm_create_usage_report_details",
"(",
")",
":",
"raise",
"AttributeError",
"(",
"\"tag 'emm_create_usage_report_details' not set\"",
")",
"return",
"self",
".",
"_value"
] | https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L19309-L19317 | |
electricitymap/electricitymap-contrib | 3099e873e1da4c95c7c86f7b14a4e2ac13094cc8 | parsers/CA_NB.py | python | fetch_exchange | (zone_key1, zone_key2, session=None, target_datetime=None, logger=None) | return data | Requests the last known power exchange (in MW) between two regions. | Requests the last known power exchange (in MW) between two regions. | [
"Requests",
"the",
"last",
"known",
"power",
"exchange",
"(",
"in",
"MW",
")",
"between",
"two",
"regions",
"."
] | def fetch_exchange(zone_key1, zone_key2, session=None, target_datetime=None, logger=None) -> dict:
"""Requests the last known power exchange (in MW) between two regions."""
if target_datetime:
raise NotImplementedError('This parser is not yet able to parse past dates')
sorted_zone_keys = '->'.join(sorted([zone_key1, zone_key2]))
requests_obj = session or requests.session()
flows = _get_new_brunswick_flows(requests_obj)
# In this source, positive values are exports and negative are imports.
# In expected result, "net" represents an export.
# So these can be used directly.
if sorted_zone_keys == 'CA-NB->CA-QC':
value = flows['QUEBEC']
elif sorted_zone_keys == 'CA-NB->US-NE-ISNE':
# all of these exports are to Maine
# (see https://www.nbpower.com/en/about-us/our-energy/system-map/),
# currently this is mapped to ISO-NE
value = flows['EMEC'] + flows['ISO-NE'] + flows['MPS']
elif sorted_zone_keys == 'CA-NB->CA-NS':
value = flows['NOVA SCOTIA']
elif sorted_zone_keys == 'CA-NB->CA-PE':
value = flows['PEI']
else:
raise NotImplementedError('This exchange pair is not implemented')
data = {
'datetime': arrow.utcnow().floor('minute').datetime,
'sortedZoneKeys': sorted_zone_keys,
'netFlow': value,
'source': 'tso.nbpower.com'
}
return data | [
"def",
"fetch_exchange",
"(",
"zone_key1",
",",
"zone_key2",
",",
"session",
"=",
"None",
",",
"target_datetime",
"=",
"None",
",",
"logger",
"=",
"None",
")",
"->",
"dict",
":",
"if",
"target_datetime",
":",
"raise",
"NotImplementedError",
"(",
"'This parser ... | https://github.com/electricitymap/electricitymap-contrib/blob/3099e873e1da4c95c7c86f7b14a4e2ac13094cc8/parsers/CA_NB.py#L78-L113 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/ckafka/v20190819/ckafka_client.py | python | CkafkaClient.DescribeInstancesDetail | (self, request) | 用户账户下获取实例列表详情
:param request: Request instance for DescribeInstancesDetail.
:type request: :class:`tencentcloud.ckafka.v20190819.models.DescribeInstancesDetailRequest`
:rtype: :class:`tencentcloud.ckafka.v20190819.models.DescribeInstancesDetailResponse` | 用户账户下获取实例列表详情 | [
"用户账户下获取实例列表详情"
] | def DescribeInstancesDetail(self, request):
"""用户账户下获取实例列表详情
:param request: Request instance for DescribeInstancesDetail.
:type request: :class:`tencentcloud.ckafka.v20190819.models.DescribeInstancesDetailRequest`
:rtype: :class:`tencentcloud.ckafka.v20190819.models.DescribeInstancesDetailResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeInstancesDetail", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeInstancesDetailResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message) | [
"def",
"DescribeInstancesDetail",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"params",
"=",
"request",
".",
"_serialize",
"(",
")",
"body",
"=",
"self",
".",
"call",
"(",
"\"DescribeInstancesDetail\"",
",",
"params",
")",
"response",
"=",
"json",
"... | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ckafka/v20190819/ckafka_client.py#L729-L754 | ||
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | research/attention_ocr/python/data_provider.py | python | preprocess_image | (image, augment=False, central_crop_size=None,
num_towers=4) | return image | Normalizes image to have values in a narrow range around zero.
Args:
image: a [H x W x 3] uint8 tensor.
augment: optional, if True do random image distortion.
central_crop_size: A tuple (crop_width, crop_height).
num_towers: optional, number of shots of the same image in the input image.
Returns:
A float32 tensor of shape [H x W x 3] with RGB values in the required
range. | Normalizes image to have values in a narrow range around zero. | [
"Normalizes",
"image",
"to",
"have",
"values",
"in",
"a",
"narrow",
"range",
"around",
"zero",
"."
] | def preprocess_image(image, augment=False, central_crop_size=None,
num_towers=4):
"""Normalizes image to have values in a narrow range around zero.
Args:
image: a [H x W x 3] uint8 tensor.
augment: optional, if True do random image distortion.
central_crop_size: A tuple (crop_width, crop_height).
num_towers: optional, number of shots of the same image in the input image.
Returns:
A float32 tensor of shape [H x W x 3] with RGB values in the required
range.
"""
with tf.compat.v1.variable_scope('PreprocessImage'):
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
if augment or central_crop_size:
if num_towers == 1:
images = [image]
else:
images = tf.split(value=image, num_or_size_splits=num_towers, axis=1)
if central_crop_size:
view_crop_size = (int(central_crop_size[0] / num_towers),
central_crop_size[1])
images = [central_crop(img, view_crop_size) for img in images]
if augment:
images = [augment_image(img) for img in images]
image = tf.concat(images, 1)
return image | [
"def",
"preprocess_image",
"(",
"image",
",",
"augment",
"=",
"False",
",",
"central_crop_size",
"=",
"None",
",",
"num_towers",
"=",
"4",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"variable_scope",
"(",
"'PreprocessImage'",
")",
":",
"image",... | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/attention_ocr/python/data_provider.py#L119-L148 | |
modoboa/modoboa | 9065b7a5679fee149fc6f6f0e1760699c194cf89 | modoboa/transport/forms.py | python | TransportForm.__init__ | (self, *args, **kwargs) | Set backend list. | Set backend list. | [
"Set",
"backend",
"list",
"."
] | def __init__(self, *args, **kwargs):
"""Set backend list."""
super(TransportForm, self).__init__(*args, **kwargs)
self.fields["service"].choices = backends.manager.get_backend_list()
settings = backends.manager.get_all_backend_settings()
for name, backend_settings in settings.items():
self.inject_backend_settings(name, backend_settings) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"TransportForm",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"fields",
"[",
"\"service\"",
"]",
... | https://github.com/modoboa/modoboa/blob/9065b7a5679fee149fc6f6f0e1760699c194cf89/modoboa/transport/forms.py#L65-L71 | ||
brython-dev/brython | 9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3 | www/src/Lib/uuid.py | python | _netbios_getnode | () | return _windll_getnode() | [DEPRECATED] Get the hardware address on Windows. | [DEPRECATED] Get the hardware address on Windows. | [
"[",
"DEPRECATED",
"]",
"Get",
"the",
"hardware",
"address",
"on",
"Windows",
"."
] | def _netbios_getnode():
"""[DEPRECATED] Get the hardware address on Windows."""
# bpo-40501: UuidCreateSequential() is now the only supported approach
return _windll_getnode() | [
"def",
"_netbios_getnode",
"(",
")",
":",
"# bpo-40501: UuidCreateSequential() is now the only supported approach",
"return",
"_windll_getnode",
"(",
")"
] | https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/uuid.py#L564-L567 | |
sdispater/orator | 0666e522be914db285b6936e3c36801fc1a9c2e7 | orator/query/builder.py | python | QueryBuilder.lock_for_update | (self) | return self.lock(True) | Lock the selected rows in the table for updating.
:return: The current QueryBuilder instance
:rtype: QueryBuilder | Lock the selected rows in the table for updating. | [
"Lock",
"the",
"selected",
"rows",
"in",
"the",
"table",
"for",
"updating",
"."
] | def lock_for_update(self):
"""
Lock the selected rows in the table for updating.
:return: The current QueryBuilder instance
:rtype: QueryBuilder
"""
return self.lock(True) | [
"def",
"lock_for_update",
"(",
"self",
")",
":",
"return",
"self",
".",
"lock",
"(",
"True",
")"
] | https://github.com/sdispater/orator/blob/0666e522be914db285b6936e3c36801fc1a9c2e7/orator/query/builder.py#L952-L959 | |
SickChill/SickChill | 01020f3636d01535f60b83464d8127ea0efabfc7 | sickchill/views/api/webapi.py | python | CMDFailed.run | (self) | return _responds(RESULT_SUCCESS, sql_results) | Get the failed downloads | Get the failed downloads | [
"Get",
"the",
"failed",
"downloads"
] | def run(self):
"""Get the failed downloads"""
failed_db_con = db.DBConnection("failed.db", row_type="dict")
u_limit = min(int(self.limit), 100)
if u_limit == 0:
sql_results = failed_db_con.select("SELECT * FROM failed")
else:
sql_results = failed_db_con.select("SELECT * FROM failed LIMIT ?", [u_limit])
return _responds(RESULT_SUCCESS, sql_results) | [
"def",
"run",
"(",
"self",
")",
":",
"failed_db_con",
"=",
"db",
".",
"DBConnection",
"(",
"\"failed.db\"",
",",
"row_type",
"=",
"\"dict\"",
")",
"u_limit",
"=",
"min",
"(",
"int",
"(",
"self",
".",
"limit",
")",
",",
"100",
")",
"if",
"u_limit",
"=... | https://github.com/SickChill/SickChill/blob/01020f3636d01535f60b83464d8127ea0efabfc7/sickchill/views/api/webapi.py#L1200-L1211 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/groupby/groupby.py | python | _GroupBy.groups | (self) | return self.grouper.groups | Dict {group name -> group labels}. | Dict {group name -> group labels}. | [
"Dict",
"{",
"group",
"name",
"-",
">",
"group",
"labels",
"}",
"."
] | def groups(self):
"""
Dict {group name -> group labels}.
"""
self._assure_grouper()
return self.grouper.groups | [
"def",
"groups",
"(",
"self",
")",
":",
"self",
".",
"_assure_grouper",
"(",
")",
"return",
"self",
".",
"grouper",
".",
"groups"
] | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/groupby/groupby.py#L385-L390 | |
yoda-pa/yoda | e6b4325737b877488af4d1bf0b86eb1d98b88aed | modules/diary.py | python | today_entry_check | () | check if today's diary entry file exists. If not, create | check if today's diary entry file exists. If not, create | [
"check",
"if",
"today",
"s",
"diary",
"entry",
"file",
"exists",
".",
"If",
"not",
"create"
] | def today_entry_check():
"""
check if today's diary entry file exists. If not, create
"""
if not os.path.exists(DIARY_CONFIG_FOLDER_PATH):
try:
os.makedirs(DIARY_CONFIG_FOLDER_PATH)
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise | [
"def",
"today_entry_check",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"DIARY_CONFIG_FOLDER_PATH",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"DIARY_CONFIG_FOLDER_PATH",
")",
"except",
"OSError",
"as",
"exc",
":",
"# Guard agai... | https://github.com/yoda-pa/yoda/blob/e6b4325737b877488af4d1bf0b86eb1d98b88aed/modules/diary.py#L90-L99 | ||
wakatime/komodo-wakatime | 8923c04ded9fa64d7374fadd8cde3a6fadfe053d | components/wakatime/packages/urllib3/fields.py | python | RequestField._render_part | (self, name, value) | return format_header_param(name, value) | Overridable helper function to format a single header parameter.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string. | Overridable helper function to format a single header parameter. | [
"Overridable",
"helper",
"function",
"to",
"format",
"a",
"single",
"header",
"parameter",
"."
] | def _render_part(self, name, value):
"""
Overridable helper function to format a single header parameter.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string.
"""
return format_header_param(name, value) | [
"def",
"_render_part",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"return",
"format_header_param",
"(",
"name",
",",
"value",
")"
] | https://github.com/wakatime/komodo-wakatime/blob/8923c04ded9fa64d7374fadd8cde3a6fadfe053d/components/wakatime/packages/urllib3/fields.py#L105-L114 | |
openstack/openstacksdk | 58384268487fa854f21c470b101641ab382c9897 | openstack/image/v2/_proxy.py | python | Proxy.get_image | (self, image) | return self._get(_image.Image, image) | Get a single image
:param image: The value can be the ID of a image or a
:class:`~openstack.image.v2.image.Image` instance.
:returns: One :class:`~openstack.image.v2.image.Image`
:raises: :class:`~openstack.exceptions.ResourceNotFound`
when no resource can be found. | Get a single image | [
"Get",
"a",
"single",
"image"
] | def get_image(self, image):
"""Get a single image
:param image: The value can be the ID of a image or a
:class:`~openstack.image.v2.image.Image` instance.
:returns: One :class:`~openstack.image.v2.image.Image`
:raises: :class:`~openstack.exceptions.ResourceNotFound`
when no resource can be found.
"""
return self._get(_image.Image, image) | [
"def",
"get_image",
"(",
"self",
",",
"image",
")",
":",
"return",
"self",
".",
"_get",
"(",
"_image",
".",
"Image",
",",
"image",
")"
] | https://github.com/openstack/openstacksdk/blob/58384268487fa854f21c470b101641ab382c9897/openstack/image/v2/_proxy.py#L482-L492 | |
Shunichi09/PythonLinearNonlinearControl | eb0bf0c78251e372a9db9fa6a888583a11d0ee12 | PythonLinearNonlinearControl/envs/env.py | python | Env.reset | (self, init_x=None) | return self.curr_x, {} | reset state
Returns:
init_x (numpy.ndarray): initial state, shape(state_size, )
info (dict): information | reset state
Returns:
init_x (numpy.ndarray): initial state, shape(state_size, )
info (dict): information | [
"reset",
"state",
"Returns",
":",
"init_x",
"(",
"numpy",
".",
"ndarray",
")",
":",
"initial",
"state",
"shape",
"(",
"state_size",
")",
"info",
"(",
"dict",
")",
":",
"information"
] | def reset(self, init_x=None):
""" reset state
Returns:
init_x (numpy.ndarray): initial state, shape(state_size, )
info (dict): information
"""
self.step_count = 0
self.curr_x = np.zeros(self.config["state_size"])
if init_x is not None:
self.curr_x = init_x
# clear memory
self.history_x = []
self.history_g_x = []
return self.curr_x, {} | [
"def",
"reset",
"(",
"self",
",",
"init_x",
"=",
"None",
")",
":",
"self",
".",
"step_count",
"=",
"0",
"self",
".",
"curr_x",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"config",
"[",
"\"state_size\"",
"]",
")",
"if",
"init_x",
"is",
"not",
"None"... | https://github.com/Shunichi09/PythonLinearNonlinearControl/blob/eb0bf0c78251e372a9db9fa6a888583a11d0ee12/PythonLinearNonlinearControl/envs/env.py#L23-L40 | |
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | cpython/Lib/numbers.py | python | Complex.imag | (self) | Retrieve the imaginary component of this number.
This should subclass Real. | Retrieve the imaginary component of this number. | [
"Retrieve",
"the",
"imaginary",
"component",
"of",
"this",
"number",
"."
] | def imag(self):
"""Retrieve the imaginary component of this number.
This should subclass Real.
"""
raise NotImplementedError | [
"def",
"imag",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/numbers.py#L65-L70 | ||
leo-editor/leo-editor | 383d6776d135ef17d73d935a2f0ecb3ac0e99494 | leo/plugins/obsolete/tkGui.py | python | leoTkinterMenu.add_separator | (self,menu) | Wrapper for the Tkinter add_separator menu method. | Wrapper for the Tkinter add_separator menu method. | [
"Wrapper",
"for",
"the",
"Tkinter",
"add_separator",
"menu",
"method",
"."
] | def add_separator(self,menu):
"""Wrapper for the Tkinter add_separator menu method."""
if menu:
menu.add_separator() | [
"def",
"add_separator",
"(",
"self",
",",
"menu",
")",
":",
"if",
"menu",
":",
"menu",
".",
"add_separator",
"(",
")"
] | https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/obsolete/tkGui.py#L5974-L5979 | ||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/distutils/dist.py | python | DistributionMetadata.get_author | (self) | return self.author or "UNKNOWN" | [] | def get_author(self):
return self.author or "UNKNOWN" | [
"def",
"get_author",
"(",
"self",
")",
":",
"return",
"self",
".",
"author",
"or",
"\"UNKNOWN\""
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/distutils/dist.py#L1159-L1160 | |||
lsbardel/python-stdnet | 78db5320bdedc3f28c5e4f38cda13a4469e35db7 | stdnet/backends/__init__.py | python | get_connection_string | (scheme, address, params) | return scheme + '://' + address | [] | def get_connection_string(scheme, address, params):
if address:
address = ':'.join((str(b) for b in address))
else:
address = ''
if params:
address += '?' + urlencode(params)
return scheme + '://' + address | [
"def",
"get_connection_string",
"(",
"scheme",
",",
"address",
",",
"params",
")",
":",
"if",
"address",
":",
"address",
"=",
"':'",
".",
"join",
"(",
"(",
"str",
"(",
"b",
")",
"for",
"b",
"in",
"address",
")",
")",
"else",
":",
"address",
"=",
"'... | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/backends/__init__.py#L60-L67 | |||
mushorg/glastopf | d17fcb6d8d5fb082af7ea3ef1abbe173895568d9 | distribute_setup.py | python | _build_install_args | (options) | return install_args | Build the arguments to 'python setup.py install' on the distribute package | Build the arguments to 'python setup.py install' on the distribute package | [
"Build",
"the",
"arguments",
"to",
"python",
"setup",
".",
"py",
"install",
"on",
"the",
"distribute",
"package"
] | def _build_install_args(options):
"""
Build the arguments to 'python setup.py install' on the distribute package
"""
install_args = []
if options.user_install:
if sys.version_info < (2, 6):
log.warn("--user requires Python 2.6 or later")
raise SystemExit(1)
install_args.append('--user')
return install_args | [
"def",
"_build_install_args",
"(",
"options",
")",
":",
"install_args",
"=",
"[",
"]",
"if",
"options",
".",
"user_install",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"6",
")",
":",
"log",
".",
"warn",
"(",
"\"--user requires Python 2.6 or... | https://github.com/mushorg/glastopf/blob/d17fcb6d8d5fb082af7ea3ef1abbe173895568d9/distribute_setup.py#L511-L521 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/axes/_base.py | python | _AxesBase._on_units_changed | (self, scalex=False, scaley=False) | Callback for processing changes to axis units.
Currently forces updates of data limits and view limits. | Callback for processing changes to axis units. | [
"Callback",
"for",
"processing",
"changes",
"to",
"axis",
"units",
"."
] | def _on_units_changed(self, scalex=False, scaley=False):
"""
Callback for processing changes to axis units.
Currently forces updates of data limits and view limits.
"""
self.relim()
self.autoscale_view(scalex=scalex, scaley=scaley) | [
"def",
"_on_units_changed",
"(",
"self",
",",
"scalex",
"=",
"False",
",",
"scaley",
"=",
"False",
")",
":",
"self",
".",
"relim",
"(",
")",
"self",
".",
"autoscale_view",
"(",
"scalex",
"=",
"scalex",
",",
"scaley",
"=",
"scaley",
")"
] | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/axes/_base.py#L2035-L2042 | ||
ales-tsurko/cells | 4cf7e395cd433762bea70cdc863a346f3a6fe1d0 | packaging/macos/python/lib/python3.7/tkinter/__init__.py | python | Misc.winfo_ismapped | (self) | return self.tk.getint(
self.tk.call('winfo', 'ismapped', self._w)) | Return true if this widget is mapped. | Return true if this widget is mapped. | [
"Return",
"true",
"if",
"this",
"widget",
"is",
"mapped",
"."
] | def winfo_ismapped(self):
"""Return true if this widget is mapped."""
return self.tk.getint(
self.tk.call('winfo', 'ismapped', self._w)) | [
"def",
"winfo_ismapped",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'ismapped'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/tkinter/__init__.py#L1008-L1011 | |
jimmysong/pb-exercises | c5e64075c47503a40063aa836c06a452af14246d | session5/complete/tx.py | python | TxOut.serialize | (self) | return result | Returns the byte serialization of the transaction output | Returns the byte serialization of the transaction output | [
"Returns",
"the",
"byte",
"serialization",
"of",
"the",
"transaction",
"output"
] | def serialize(self):
'''Returns the byte serialization of the transaction output'''
# serialize amount, 8 bytes, little endian
result = int_to_little_endian(self.amount, 8)
# serialize the script_pubkey
result += self.script_pubkey.serialize()
return result | [
"def",
"serialize",
"(",
"self",
")",
":",
"# serialize amount, 8 bytes, little endian",
"result",
"=",
"int_to_little_endian",
"(",
"self",
".",
"amount",
",",
"8",
")",
"# serialize the script_pubkey",
"result",
"+=",
"self",
".",
"script_pubkey",
".",
"serialize",
... | https://github.com/jimmysong/pb-exercises/blob/c5e64075c47503a40063aa836c06a452af14246d/session5/complete/tx.py#L317-L323 | |
ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | digsby/src/msn/MSNConversation.py | python | MSNConversation.send_typing_status | (self, status) | Status can be None, 'typed' or 'typing'. But, for MSN
only 'typing' is understood. | Status can be None, 'typed' or 'typing'. But, for MSN
only 'typing' is understood. | [
"Status",
"can",
"be",
"None",
"typed",
"or",
"typing",
".",
"But",
"for",
"MSN",
"only",
"typing",
"is",
"understood",
"."
] | def send_typing_status(self, status):
"""
Status can be None, 'typed' or 'typing'. But, for MSN
only 'typing' is understood.
"""
self._stop_exit_timer()
getattr(self, 'send_typing_status_%s' % self.type, self.send_typing_status_im)(status) | [
"def",
"send_typing_status",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"_stop_exit_timer",
"(",
")",
"getattr",
"(",
"self",
",",
"'send_typing_status_%s'",
"%",
"self",
".",
"type",
",",
"self",
".",
"send_typing_status_im",
")",
"(",
"status",
")"... | https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/msn/MSNConversation.py#L812-L818 | ||
biopython/biopython | 2dd97e71762af7b046d7f7f8a4f1e38db6b06c86 | Bio/SearchIO/HmmerIO/hmmer3_text.py | python | Hmmer3TextParser._parse_qresult | (self) | Parse a HMMER3 query block (PRIVATE). | Parse a HMMER3 query block (PRIVATE). | [
"Parse",
"a",
"HMMER3",
"query",
"block",
"(",
"PRIVATE",
")",
"."
] | def _parse_qresult(self):
"""Parse a HMMER3 query block (PRIVATE)."""
self._read_until(lambda line: line.startswith("Query:"))
while self.line:
regx = re.search(_QRE_ID_LEN, self.line)
while not regx:
self.line = read_forward(self.handle)
regx = re.search(_QRE_ID_LEN, self.line)
# get query id and length
qid = regx.group(1).strip()
# store qresult attributes
qresult_attrs = {
"seq_len": int(regx.group(2)),
"program": self._meta.get("program"),
"version": self._meta.get("version"),
"target": self._meta.get("target"),
}
# get description and accession, if they exist
qdesc = "<unknown description>" # placeholder
while not self.line.startswith("Scores for "):
self.line = read_forward(self.handle)
if self.line.startswith("Accession:"):
acc = self.line.strip().split(" ", 1)[1]
qresult_attrs["accession"] = acc.strip()
elif self.line.startswith("Description:"):
qdesc = self.line.strip().split(" ", 1)[1].strip()
qresult_attrs["description"] = qdesc
# parse the query hits
while self.line and "//" not in self.line:
hit_list = self._parse_hit(qid, qdesc)
# read through the statistics summary
# TODO: parse and store this information?
if self.line.startswith("Internal pipeline"):
while self.line and "//" not in self.line:
self.line = read_forward(self.handle)
# create qresult, set its attributes and yield
# not initializing hit_list directly to handle empty hits
# (i.e. need to set its query description manually)
qresult = QueryResult(id=qid, hits=hit_list)
for attr, value in qresult_attrs.items():
setattr(qresult, attr, value)
yield qresult
self.line = read_forward(self.handle)
# Skip line beginning with '# Alignment of', which are output
# when running phmmer with the '-A' flag.
if self.line.startswith("#"):
self.line = self.handle.readline()
# HMMER >= 3.1 outputs '[ok]' at the end of all results file,
# which means we can break the main loop when we see the line
if "[ok]" in self.line:
break | [
"def",
"_parse_qresult",
"(",
"self",
")",
":",
"self",
".",
"_read_until",
"(",
"lambda",
"line",
":",
"line",
".",
"startswith",
"(",
"\"Query:\"",
")",
")",
"while",
"self",
".",
"line",
":",
"regx",
"=",
"re",
".",
"search",
"(",
"_QRE_ID_LEN",
","... | https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/SearchIO/HmmerIO/hmmer3_text.py#L98-L158 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.