repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
IdentityPython/SATOSA | src/satosa/backends/saml2.py | SAMLBackend.authn_request | def authn_request(self, context, entity_id):
"""
Do an authorization request on idp with given entity id.
This is the start of the authorization.
:type context: satosa.context.Context
:type entity_id: str
:rtype: satosa.response.Response
:param context: The current context
:param entity_id: Target IDP entity id
:return: response to the user agent
"""
# If IDP blacklisting is enabled and the selected IDP is blacklisted,
# stop here
if self.idp_blacklist_file:
with open(self.idp_blacklist_file) as blacklist_file:
blacklist_array = json.load(blacklist_file)['blacklist']
if entity_id in blacklist_array:
satosa_logging(logger, logging.DEBUG, "IdP with EntityID {} is blacklisted".format(entity_id), context.state, exc_info=False)
raise SATOSAAuthenticationError(context.state, "Selected IdP is blacklisted for this backend")
kwargs = {}
authn_context = self.construct_requested_authn_context(entity_id)
if authn_context:
kwargs['requested_authn_context'] = authn_context
try:
binding, destination = self.sp.pick_binding(
"single_sign_on_service", None, "idpsso", entity_id=entity_id)
satosa_logging(logger, logging.DEBUG, "binding: %s, destination: %s" % (binding, destination),
context.state)
acs_endp, response_binding = self.sp.config.getattr("endpoints", "sp")["assertion_consumer_service"][0]
req_id, req = self.sp.create_authn_request(
destination, binding=response_binding, **kwargs)
relay_state = util.rndstr()
ht_args = self.sp.apply_binding(binding, "%s" % req, destination, relay_state=relay_state)
satosa_logging(logger, logging.DEBUG, "ht_args: %s" % ht_args, context.state)
except Exception as exc:
satosa_logging(logger, logging.DEBUG, "Failed to construct the AuthnRequest for state", context.state,
exc_info=True)
raise SATOSAAuthenticationError(context.state, "Failed to construct the AuthnRequest") from exc
if self.sp.config.getattr('allow_unsolicited', 'sp') is False:
if req_id in self.outstanding_queries:
errmsg = "Request with duplicate id {}".format(req_id)
satosa_logging(logger, logging.DEBUG, errmsg, context.state)
raise SATOSAAuthenticationError(context.state, errmsg)
self.outstanding_queries[req_id] = req
context.state[self.name] = {"relay_state": relay_state}
return make_saml_response(binding, ht_args) | python | def authn_request(self, context, entity_id):
"""
Do an authorization request on idp with given entity id.
This is the start of the authorization.
:type context: satosa.context.Context
:type entity_id: str
:rtype: satosa.response.Response
:param context: The current context
:param entity_id: Target IDP entity id
:return: response to the user agent
"""
# If IDP blacklisting is enabled and the selected IDP is blacklisted,
# stop here
if self.idp_blacklist_file:
with open(self.idp_blacklist_file) as blacklist_file:
blacklist_array = json.load(blacklist_file)['blacklist']
if entity_id in blacklist_array:
satosa_logging(logger, logging.DEBUG, "IdP with EntityID {} is blacklisted".format(entity_id), context.state, exc_info=False)
raise SATOSAAuthenticationError(context.state, "Selected IdP is blacklisted for this backend")
kwargs = {}
authn_context = self.construct_requested_authn_context(entity_id)
if authn_context:
kwargs['requested_authn_context'] = authn_context
try:
binding, destination = self.sp.pick_binding(
"single_sign_on_service", None, "idpsso", entity_id=entity_id)
satosa_logging(logger, logging.DEBUG, "binding: %s, destination: %s" % (binding, destination),
context.state)
acs_endp, response_binding = self.sp.config.getattr("endpoints", "sp")["assertion_consumer_service"][0]
req_id, req = self.sp.create_authn_request(
destination, binding=response_binding, **kwargs)
relay_state = util.rndstr()
ht_args = self.sp.apply_binding(binding, "%s" % req, destination, relay_state=relay_state)
satosa_logging(logger, logging.DEBUG, "ht_args: %s" % ht_args, context.state)
except Exception as exc:
satosa_logging(logger, logging.DEBUG, "Failed to construct the AuthnRequest for state", context.state,
exc_info=True)
raise SATOSAAuthenticationError(context.state, "Failed to construct the AuthnRequest") from exc
if self.sp.config.getattr('allow_unsolicited', 'sp') is False:
if req_id in self.outstanding_queries:
errmsg = "Request with duplicate id {}".format(req_id)
satosa_logging(logger, logging.DEBUG, errmsg, context.state)
raise SATOSAAuthenticationError(context.state, errmsg)
self.outstanding_queries[req_id] = req
context.state[self.name] = {"relay_state": relay_state}
return make_saml_response(binding, ht_args) | [
"def",
"authn_request",
"(",
"self",
",",
"context",
",",
"entity_id",
")",
":",
"# If IDP blacklisting is enabled and the selected IDP is blacklisted,",
"# stop here",
"if",
"self",
".",
"idp_blacklist_file",
":",
"with",
"open",
"(",
"self",
".",
"idp_blacklist_file",
")",
"as",
"blacklist_file",
":",
"blacklist_array",
"=",
"json",
".",
"load",
"(",
"blacklist_file",
")",
"[",
"'blacklist'",
"]",
"if",
"entity_id",
"in",
"blacklist_array",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"IdP with EntityID {} is blacklisted\"",
".",
"format",
"(",
"entity_id",
")",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"False",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"context",
".",
"state",
",",
"\"Selected IdP is blacklisted for this backend\"",
")",
"kwargs",
"=",
"{",
"}",
"authn_context",
"=",
"self",
".",
"construct_requested_authn_context",
"(",
"entity_id",
")",
"if",
"authn_context",
":",
"kwargs",
"[",
"'requested_authn_context'",
"]",
"=",
"authn_context",
"try",
":",
"binding",
",",
"destination",
"=",
"self",
".",
"sp",
".",
"pick_binding",
"(",
"\"single_sign_on_service\"",
",",
"None",
",",
"\"idpsso\"",
",",
"entity_id",
"=",
"entity_id",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"binding: %s, destination: %s\"",
"%",
"(",
"binding",
",",
"destination",
")",
",",
"context",
".",
"state",
")",
"acs_endp",
",",
"response_binding",
"=",
"self",
".",
"sp",
".",
"config",
".",
"getattr",
"(",
"\"endpoints\"",
",",
"\"sp\"",
")",
"[",
"\"assertion_consumer_service\"",
"]",
"[",
"0",
"]",
"req_id",
",",
"req",
"=",
"self",
".",
"sp",
".",
"create_authn_request",
"(",
"destination",
",",
"binding",
"=",
"response_binding",
",",
"*",
"*",
"kwargs",
")",
"relay_state",
"=",
"util",
".",
"rndstr",
"(",
")",
"ht_args",
"=",
"self",
".",
"sp",
".",
"apply_binding",
"(",
"binding",
",",
"\"%s\"",
"%",
"req",
",",
"destination",
",",
"relay_state",
"=",
"relay_state",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"ht_args: %s\"",
"%",
"ht_args",
",",
"context",
".",
"state",
")",
"except",
"Exception",
"as",
"exc",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Failed to construct the AuthnRequest for state\"",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"context",
".",
"state",
",",
"\"Failed to construct the AuthnRequest\"",
")",
"from",
"exc",
"if",
"self",
".",
"sp",
".",
"config",
".",
"getattr",
"(",
"'allow_unsolicited'",
",",
"'sp'",
")",
"is",
"False",
":",
"if",
"req_id",
"in",
"self",
".",
"outstanding_queries",
":",
"errmsg",
"=",
"\"Request with duplicate id {}\"",
".",
"format",
"(",
"req_id",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"errmsg",
",",
"context",
".",
"state",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"context",
".",
"state",
",",
"errmsg",
")",
"self",
".",
"outstanding_queries",
"[",
"req_id",
"]",
"=",
"req",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"=",
"{",
"\"relay_state\"",
":",
"relay_state",
"}",
"return",
"make_saml_response",
"(",
"binding",
",",
"ht_args",
")"
] | Do an authorization request on idp with given entity id.
This is the start of the authorization.
:type context: satosa.context.Context
:type entity_id: str
:rtype: satosa.response.Response
:param context: The current context
:param entity_id: Target IDP entity id
:return: response to the user agent | [
"Do",
"an",
"authorization",
"request",
"on",
"idp",
"with",
"given",
"entity",
"id",
".",
"This",
"is",
"the",
"start",
"of",
"the",
"authorization",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L143-L195 | train | 231,900 |
IdentityPython/SATOSA | src/satosa/backends/saml2.py | SAMLBackend.disco_response | def disco_response(self, context):
"""
Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
info = context.request
state = context.state
try:
entity_id = info["entityID"]
except KeyError as err:
satosa_logging(logger, logging.DEBUG, "No IDP chosen for state", state, exc_info=True)
raise SATOSAAuthenticationError(state, "No IDP chosen") from err
return self.authn_request(context, entity_id) | python | def disco_response(self, context):
"""
Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
info = context.request
state = context.state
try:
entity_id = info["entityID"]
except KeyError as err:
satosa_logging(logger, logging.DEBUG, "No IDP chosen for state", state, exc_info=True)
raise SATOSAAuthenticationError(state, "No IDP chosen") from err
return self.authn_request(context, entity_id) | [
"def",
"disco_response",
"(",
"self",
",",
"context",
")",
":",
"info",
"=",
"context",
".",
"request",
"state",
"=",
"context",
".",
"state",
"try",
":",
"entity_id",
"=",
"info",
"[",
"\"entityID\"",
"]",
"except",
"KeyError",
"as",
"err",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"No IDP chosen for state\"",
",",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"state",
",",
"\"No IDP chosen\"",
")",
"from",
"err",
"return",
"self",
".",
"authn_request",
"(",
"context",
",",
"entity_id",
")"
] | Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response | [
"Endpoint",
"for",
"the",
"discovery",
"server",
"response"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L240-L259 | train | 231,901 |
IdentityPython/SATOSA | src/satosa/backends/saml2.py | SAMLBackend._translate_response | def _translate_response(self, response, state):
"""
Translates a saml authorization response to an internal response
:type response: saml2.response.AuthnResponse
:rtype: satosa.internal.InternalData
:param response: The saml authorization response
:return: A translated internal response
"""
# The response may have been encrypted by the IdP so if we have an
# encryption key, try it.
if self.encryption_keys:
response.parse_assertion(self.encryption_keys)
authn_info = response.authn_info()[0]
auth_class_ref = authn_info[0]
timestamp = response.assertion.authn_statement[0].authn_instant
issuer = response.response.issuer.text
auth_info = AuthenticationInformation(
auth_class_ref, timestamp, issuer,
)
# The SAML response may not include a NameID.
subject = response.get_subject()
name_id = subject.text if subject else None
name_id_format = subject.format if subject else None
attributes = self.converter.to_internal(
self.attribute_profile, response.ava,
)
internal_resp = InternalData(
auth_info=auth_info,
attributes=attributes,
subject_type=name_id_format,
subject_id=name_id,
)
satosa_logging(logger, logging.DEBUG,
"backend received attributes:\n%s" %
json.dumps(response.ava, indent=4), state)
return internal_resp | python | def _translate_response(self, response, state):
"""
Translates a saml authorization response to an internal response
:type response: saml2.response.AuthnResponse
:rtype: satosa.internal.InternalData
:param response: The saml authorization response
:return: A translated internal response
"""
# The response may have been encrypted by the IdP so if we have an
# encryption key, try it.
if self.encryption_keys:
response.parse_assertion(self.encryption_keys)
authn_info = response.authn_info()[0]
auth_class_ref = authn_info[0]
timestamp = response.assertion.authn_statement[0].authn_instant
issuer = response.response.issuer.text
auth_info = AuthenticationInformation(
auth_class_ref, timestamp, issuer,
)
# The SAML response may not include a NameID.
subject = response.get_subject()
name_id = subject.text if subject else None
name_id_format = subject.format if subject else None
attributes = self.converter.to_internal(
self.attribute_profile, response.ava,
)
internal_resp = InternalData(
auth_info=auth_info,
attributes=attributes,
subject_type=name_id_format,
subject_id=name_id,
)
satosa_logging(logger, logging.DEBUG,
"backend received attributes:\n%s" %
json.dumps(response.ava, indent=4), state)
return internal_resp | [
"def",
"_translate_response",
"(",
"self",
",",
"response",
",",
"state",
")",
":",
"# The response may have been encrypted by the IdP so if we have an",
"# encryption key, try it.",
"if",
"self",
".",
"encryption_keys",
":",
"response",
".",
"parse_assertion",
"(",
"self",
".",
"encryption_keys",
")",
"authn_info",
"=",
"response",
".",
"authn_info",
"(",
")",
"[",
"0",
"]",
"auth_class_ref",
"=",
"authn_info",
"[",
"0",
"]",
"timestamp",
"=",
"response",
".",
"assertion",
".",
"authn_statement",
"[",
"0",
"]",
".",
"authn_instant",
"issuer",
"=",
"response",
".",
"response",
".",
"issuer",
".",
"text",
"auth_info",
"=",
"AuthenticationInformation",
"(",
"auth_class_ref",
",",
"timestamp",
",",
"issuer",
",",
")",
"# The SAML response may not include a NameID.",
"subject",
"=",
"response",
".",
"get_subject",
"(",
")",
"name_id",
"=",
"subject",
".",
"text",
"if",
"subject",
"else",
"None",
"name_id_format",
"=",
"subject",
".",
"format",
"if",
"subject",
"else",
"None",
"attributes",
"=",
"self",
".",
"converter",
".",
"to_internal",
"(",
"self",
".",
"attribute_profile",
",",
"response",
".",
"ava",
",",
")",
"internal_resp",
"=",
"InternalData",
"(",
"auth_info",
"=",
"auth_info",
",",
"attributes",
"=",
"attributes",
",",
"subject_type",
"=",
"name_id_format",
",",
"subject_id",
"=",
"name_id",
",",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"backend received attributes:\\n%s\"",
"%",
"json",
".",
"dumps",
"(",
"response",
".",
"ava",
",",
"indent",
"=",
"4",
")",
",",
"state",
")",
"return",
"internal_resp"
] | Translates a saml authorization response to an internal response
:type response: saml2.response.AuthnResponse
:rtype: satosa.internal.InternalData
:param response: The saml authorization response
:return: A translated internal response | [
"Translates",
"a",
"saml",
"authorization",
"response",
"to",
"an",
"internal",
"response"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L261-L304 | train | 231,902 |
IdentityPython/SATOSA | src/satosa/attribute_mapping.py | AttributeMapper.to_internal_filter | def to_internal_filter(self, attribute_profile, external_attribute_names):
"""
Converts attribute names from external "type" to internal
:type attribute_profile: str
:type external_attribute_names: list[str]
:type case_insensitive: bool
:rtype: list[str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_attribute_names: A list of attribute names
:param case_insensitive: Create a case insensitive filter
:return: A list of attribute names in the internal format
"""
try:
profile_mapping = self.to_internal_attributes[attribute_profile]
except KeyError:
logger.warn("no attribute mapping found for the given attribute profile '%s'", attribute_profile)
# no attributes since the given profile is not configured
return []
internal_attribute_names = set() # use set to ensure only unique values
for external_attribute_name in external_attribute_names:
try:
internal_attribute_name = profile_mapping[external_attribute_name]
internal_attribute_names.add(internal_attribute_name)
except KeyError:
pass
return list(internal_attribute_names) | python | def to_internal_filter(self, attribute_profile, external_attribute_names):
"""
Converts attribute names from external "type" to internal
:type attribute_profile: str
:type external_attribute_names: list[str]
:type case_insensitive: bool
:rtype: list[str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_attribute_names: A list of attribute names
:param case_insensitive: Create a case insensitive filter
:return: A list of attribute names in the internal format
"""
try:
profile_mapping = self.to_internal_attributes[attribute_profile]
except KeyError:
logger.warn("no attribute mapping found for the given attribute profile '%s'", attribute_profile)
# no attributes since the given profile is not configured
return []
internal_attribute_names = set() # use set to ensure only unique values
for external_attribute_name in external_attribute_names:
try:
internal_attribute_name = profile_mapping[external_attribute_name]
internal_attribute_names.add(internal_attribute_name)
except KeyError:
pass
return list(internal_attribute_names) | [
"def",
"to_internal_filter",
"(",
"self",
",",
"attribute_profile",
",",
"external_attribute_names",
")",
":",
"try",
":",
"profile_mapping",
"=",
"self",
".",
"to_internal_attributes",
"[",
"attribute_profile",
"]",
"except",
"KeyError",
":",
"logger",
".",
"warn",
"(",
"\"no attribute mapping found for the given attribute profile '%s'\"",
",",
"attribute_profile",
")",
"# no attributes since the given profile is not configured",
"return",
"[",
"]",
"internal_attribute_names",
"=",
"set",
"(",
")",
"# use set to ensure only unique values",
"for",
"external_attribute_name",
"in",
"external_attribute_names",
":",
"try",
":",
"internal_attribute_name",
"=",
"profile_mapping",
"[",
"external_attribute_name",
"]",
"internal_attribute_names",
".",
"add",
"(",
"internal_attribute_name",
")",
"except",
"KeyError",
":",
"pass",
"return",
"list",
"(",
"internal_attribute_names",
")"
] | Converts attribute names from external "type" to internal
:type attribute_profile: str
:type external_attribute_names: list[str]
:type case_insensitive: bool
:rtype: list[str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_attribute_names: A list of attribute names
:param case_insensitive: Create a case insensitive filter
:return: A list of attribute names in the internal format | [
"Converts",
"attribute",
"names",
"from",
"external",
"type",
"to",
"internal"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/attribute_mapping.py#L44-L73 | train | 231,903 |
IdentityPython/SATOSA | src/satosa/attribute_mapping.py | AttributeMapper.to_internal | def to_internal(self, attribute_profile, external_dict):
"""
Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_dict: Attributes in the external format
:return: Attributes in the internal format
"""
internal_dict = {}
for internal_attribute_name, mapping in self.from_internal_attributes.items():
if attribute_profile not in mapping:
logger.debug("no attribute mapping found for internal attribute '%s' the attribute profile '%s'" % (
internal_attribute_name, attribute_profile))
# skip this internal attribute if we have no mapping in the specified profile
continue
external_attribute_name = mapping[attribute_profile]
attribute_values = self._collate_attribute_values_by_priority_order(external_attribute_name,
external_dict)
if attribute_values: # Only insert key if it has some values
logger.debug("backend attribute '%s' mapped to %s" % (external_attribute_name,
internal_attribute_name))
internal_dict[internal_attribute_name] = attribute_values
else:
logger.debug("skipped backend attribute '%s': no value found", external_attribute_name)
internal_dict = self._handle_template_attributes(attribute_profile, internal_dict)
return internal_dict | python | def to_internal(self, attribute_profile, external_dict):
"""
Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_dict: Attributes in the external format
:return: Attributes in the internal format
"""
internal_dict = {}
for internal_attribute_name, mapping in self.from_internal_attributes.items():
if attribute_profile not in mapping:
logger.debug("no attribute mapping found for internal attribute '%s' the attribute profile '%s'" % (
internal_attribute_name, attribute_profile))
# skip this internal attribute if we have no mapping in the specified profile
continue
external_attribute_name = mapping[attribute_profile]
attribute_values = self._collate_attribute_values_by_priority_order(external_attribute_name,
external_dict)
if attribute_values: # Only insert key if it has some values
logger.debug("backend attribute '%s' mapped to %s" % (external_attribute_name,
internal_attribute_name))
internal_dict[internal_attribute_name] = attribute_values
else:
logger.debug("skipped backend attribute '%s': no value found", external_attribute_name)
internal_dict = self._handle_template_attributes(attribute_profile, internal_dict)
return internal_dict | [
"def",
"to_internal",
"(",
"self",
",",
"attribute_profile",
",",
"external_dict",
")",
":",
"internal_dict",
"=",
"{",
"}",
"for",
"internal_attribute_name",
",",
"mapping",
"in",
"self",
".",
"from_internal_attributes",
".",
"items",
"(",
")",
":",
"if",
"attribute_profile",
"not",
"in",
"mapping",
":",
"logger",
".",
"debug",
"(",
"\"no attribute mapping found for internal attribute '%s' the attribute profile '%s'\"",
"%",
"(",
"internal_attribute_name",
",",
"attribute_profile",
")",
")",
"# skip this internal attribute if we have no mapping in the specified profile",
"continue",
"external_attribute_name",
"=",
"mapping",
"[",
"attribute_profile",
"]",
"attribute_values",
"=",
"self",
".",
"_collate_attribute_values_by_priority_order",
"(",
"external_attribute_name",
",",
"external_dict",
")",
"if",
"attribute_values",
":",
"# Only insert key if it has some values",
"logger",
".",
"debug",
"(",
"\"backend attribute '%s' mapped to %s\"",
"%",
"(",
"external_attribute_name",
",",
"internal_attribute_name",
")",
")",
"internal_dict",
"[",
"internal_attribute_name",
"]",
"=",
"attribute_values",
"else",
":",
"logger",
".",
"debug",
"(",
"\"skipped backend attribute '%s': no value found\"",
",",
"external_attribute_name",
")",
"internal_dict",
"=",
"self",
".",
"_handle_template_attributes",
"(",
"attribute_profile",
",",
"internal_dict",
")",
"return",
"internal_dict"
] | Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_dict: Attributes in the external format
:return: Attributes in the internal format | [
"Converts",
"the",
"external",
"data",
"from",
"type",
"to",
"internal"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/attribute_mapping.py#L75-L107 | train | 231,904 |
IdentityPython/SATOSA | src/satosa/attribute_mapping.py | AttributeMapper.from_internal | def from_internal(self, attribute_profile, internal_dict):
"""
Converts the internal data to "type"
:type attribute_profile: str
:type internal_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: To which external type to convert (ex: oidc, saml, ...)
:param internal_dict: attributes to map
:return: attribute values and names in the specified "profile"
"""
external_dict = {}
for internal_attribute_name in internal_dict:
try:
attribute_mapping = self.from_internal_attributes[internal_attribute_name]
except KeyError:
logger.debug("no attribute mapping found for the internal attribute '%s'", internal_attribute_name)
continue
if attribute_profile not in attribute_mapping:
# skip this internal attribute if we have no mapping in the specified profile
logger.debug("no mapping found for '%s' in attribute profile '%s'" %
(internal_attribute_name,
attribute_profile))
continue
external_attribute_names = self.from_internal_attributes[internal_attribute_name][attribute_profile]
# select the first attribute name
external_attribute_name = external_attribute_names[0]
logger.debug("frontend attribute %s mapped from %s" % (external_attribute_name,
internal_attribute_name))
if self.separator in external_attribute_name:
nested_attribute_names = external_attribute_name.split(self.separator)
nested_dict = self._create_nested_attribute_value(nested_attribute_names[1:],
internal_dict[internal_attribute_name])
external_dict[nested_attribute_names[0]] = nested_dict
else:
external_dict[external_attribute_name] = internal_dict[internal_attribute_name]
return external_dict | python | def from_internal(self, attribute_profile, internal_dict):
"""
Converts the internal data to "type"
:type attribute_profile: str
:type internal_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: To which external type to convert (ex: oidc, saml, ...)
:param internal_dict: attributes to map
:return: attribute values and names in the specified "profile"
"""
external_dict = {}
for internal_attribute_name in internal_dict:
try:
attribute_mapping = self.from_internal_attributes[internal_attribute_name]
except KeyError:
logger.debug("no attribute mapping found for the internal attribute '%s'", internal_attribute_name)
continue
if attribute_profile not in attribute_mapping:
# skip this internal attribute if we have no mapping in the specified profile
logger.debug("no mapping found for '%s' in attribute profile '%s'" %
(internal_attribute_name,
attribute_profile))
continue
external_attribute_names = self.from_internal_attributes[internal_attribute_name][attribute_profile]
# select the first attribute name
external_attribute_name = external_attribute_names[0]
logger.debug("frontend attribute %s mapped from %s" % (external_attribute_name,
internal_attribute_name))
if self.separator in external_attribute_name:
nested_attribute_names = external_attribute_name.split(self.separator)
nested_dict = self._create_nested_attribute_value(nested_attribute_names[1:],
internal_dict[internal_attribute_name])
external_dict[nested_attribute_names[0]] = nested_dict
else:
external_dict[external_attribute_name] = internal_dict[internal_attribute_name]
return external_dict | [
"def",
"from_internal",
"(",
"self",
",",
"attribute_profile",
",",
"internal_dict",
")",
":",
"external_dict",
"=",
"{",
"}",
"for",
"internal_attribute_name",
"in",
"internal_dict",
":",
"try",
":",
"attribute_mapping",
"=",
"self",
".",
"from_internal_attributes",
"[",
"internal_attribute_name",
"]",
"except",
"KeyError",
":",
"logger",
".",
"debug",
"(",
"\"no attribute mapping found for the internal attribute '%s'\"",
",",
"internal_attribute_name",
")",
"continue",
"if",
"attribute_profile",
"not",
"in",
"attribute_mapping",
":",
"# skip this internal attribute if we have no mapping in the specified profile",
"logger",
".",
"debug",
"(",
"\"no mapping found for '%s' in attribute profile '%s'\"",
"%",
"(",
"internal_attribute_name",
",",
"attribute_profile",
")",
")",
"continue",
"external_attribute_names",
"=",
"self",
".",
"from_internal_attributes",
"[",
"internal_attribute_name",
"]",
"[",
"attribute_profile",
"]",
"# select the first attribute name",
"external_attribute_name",
"=",
"external_attribute_names",
"[",
"0",
"]",
"logger",
".",
"debug",
"(",
"\"frontend attribute %s mapped from %s\"",
"%",
"(",
"external_attribute_name",
",",
"internal_attribute_name",
")",
")",
"if",
"self",
".",
"separator",
"in",
"external_attribute_name",
":",
"nested_attribute_names",
"=",
"external_attribute_name",
".",
"split",
"(",
"self",
".",
"separator",
")",
"nested_dict",
"=",
"self",
".",
"_create_nested_attribute_value",
"(",
"nested_attribute_names",
"[",
"1",
":",
"]",
",",
"internal_dict",
"[",
"internal_attribute_name",
"]",
")",
"external_dict",
"[",
"nested_attribute_names",
"[",
"0",
"]",
"]",
"=",
"nested_dict",
"else",
":",
"external_dict",
"[",
"external_attribute_name",
"]",
"=",
"internal_dict",
"[",
"internal_attribute_name",
"]",
"return",
"external_dict"
] | Converts the internal data to "type"
:type attribute_profile: str
:type internal_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: To which external type to convert (ex: oidc, saml, ...)
:param internal_dict: attributes to map
:return: attribute values and names in the specified "profile" | [
"Converts",
"the",
"internal",
"data",
"to",
"type"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/attribute_mapping.py#L167-L208 | train | 231,905 |
c4urself/bump2version | bumpversion/version_part.py | VersionConfig._serialize | def _serialize(self, version, serialize_format, context, raise_if_incomplete=False):
"""
Attempts to serialize a version with the given serialization format.
Raises MissingValueForSerializationException if not serializable
"""
values = context.copy()
for k in version:
values[k] = version[k]
# TODO dump complete context on debug level
try:
# test whether all parts required in the format have values
serialized = serialize_format.format(**values)
except KeyError as e:
missing_key = getattr(e, "message", e.args[0])
raise MissingValueForSerializationException(
"Did not find key {} in {} when serializing version number".format(
repr(missing_key), repr(version)
)
)
keys_needing_representation = set()
found_required = False
for k in self.order():
v = values[k]
if not isinstance(v, VersionPart):
# values coming from environment variables don't need
# representation
continue
if not v.is_optional():
found_required = True
keys_needing_representation.add(k)
elif not found_required:
keys_needing_representation.add(k)
required_by_format = set(self._labels_for_format(serialize_format))
# try whether all parsed keys are represented
if raise_if_incomplete:
if not (keys_needing_representation <= required_by_format):
raise IncompleteVersionRepresentationException(
"Could not represent '{}' in format '{}'".format(
"', '".join(keys_needing_representation ^ required_by_format),
serialize_format,
)
)
return serialized | python | def _serialize(self, version, serialize_format, context, raise_if_incomplete=False):
"""
Attempts to serialize a version with the given serialization format.
Raises MissingValueForSerializationException if not serializable
"""
values = context.copy()
for k in version:
values[k] = version[k]
# TODO dump complete context on debug level
try:
# test whether all parts required in the format have values
serialized = serialize_format.format(**values)
except KeyError as e:
missing_key = getattr(e, "message", e.args[0])
raise MissingValueForSerializationException(
"Did not find key {} in {} when serializing version number".format(
repr(missing_key), repr(version)
)
)
keys_needing_representation = set()
found_required = False
for k in self.order():
v = values[k]
if not isinstance(v, VersionPart):
# values coming from environment variables don't need
# representation
continue
if not v.is_optional():
found_required = True
keys_needing_representation.add(k)
elif not found_required:
keys_needing_representation.add(k)
required_by_format = set(self._labels_for_format(serialize_format))
# try whether all parsed keys are represented
if raise_if_incomplete:
if not (keys_needing_representation <= required_by_format):
raise IncompleteVersionRepresentationException(
"Could not represent '{}' in format '{}'".format(
"', '".join(keys_needing_representation ^ required_by_format),
serialize_format,
)
)
return serialized | [
"def",
"_serialize",
"(",
"self",
",",
"version",
",",
"serialize_format",
",",
"context",
",",
"raise_if_incomplete",
"=",
"False",
")",
":",
"values",
"=",
"context",
".",
"copy",
"(",
")",
"for",
"k",
"in",
"version",
":",
"values",
"[",
"k",
"]",
"=",
"version",
"[",
"k",
"]",
"# TODO dump complete context on debug level",
"try",
":",
"# test whether all parts required in the format have values",
"serialized",
"=",
"serialize_format",
".",
"format",
"(",
"*",
"*",
"values",
")",
"except",
"KeyError",
"as",
"e",
":",
"missing_key",
"=",
"getattr",
"(",
"e",
",",
"\"message\"",
",",
"e",
".",
"args",
"[",
"0",
"]",
")",
"raise",
"MissingValueForSerializationException",
"(",
"\"Did not find key {} in {} when serializing version number\"",
".",
"format",
"(",
"repr",
"(",
"missing_key",
")",
",",
"repr",
"(",
"version",
")",
")",
")",
"keys_needing_representation",
"=",
"set",
"(",
")",
"found_required",
"=",
"False",
"for",
"k",
"in",
"self",
".",
"order",
"(",
")",
":",
"v",
"=",
"values",
"[",
"k",
"]",
"if",
"not",
"isinstance",
"(",
"v",
",",
"VersionPart",
")",
":",
"# values coming from environment variables don't need",
"# representation",
"continue",
"if",
"not",
"v",
".",
"is_optional",
"(",
")",
":",
"found_required",
"=",
"True",
"keys_needing_representation",
".",
"add",
"(",
"k",
")",
"elif",
"not",
"found_required",
":",
"keys_needing_representation",
".",
"add",
"(",
"k",
")",
"required_by_format",
"=",
"set",
"(",
"self",
".",
"_labels_for_format",
"(",
"serialize_format",
")",
")",
"# try whether all parsed keys are represented",
"if",
"raise_if_incomplete",
":",
"if",
"not",
"(",
"keys_needing_representation",
"<=",
"required_by_format",
")",
":",
"raise",
"IncompleteVersionRepresentationException",
"(",
"\"Could not represent '{}' in format '{}'\"",
".",
"format",
"(",
"\"', '\"",
".",
"join",
"(",
"keys_needing_representation",
"^",
"required_by_format",
")",
",",
"serialize_format",
",",
")",
")",
"return",
"serialized"
] | Attempts to serialize a version with the given serialization format.
Raises MissingValueForSerializationException if not serializable | [
"Attempts",
"to",
"serialize",
"a",
"version",
"with",
"the",
"given",
"serialization",
"format",
"."
] | 22d981ebfb94a7d26716e2b936f932a58883aa30 | https://github.com/c4urself/bump2version/blob/22d981ebfb94a7d26716e2b936f932a58883aa30/bumpversion/version_part.py#L194-L247 | train | 231,906 |
lawsie/guizero | guizero/ButtonGroup.py | ButtonGroup.value_text | def value_text(self):
"""
Sets or returns the option selected in a ButtonGroup by its text value.
"""
search = self._selected.get() # a string containing the selected option
# This is a bit nasty - suggestions welcome
for item in self._rbuttons:
if item.value == search:
return item.text
return "" | python | def value_text(self):
"""
Sets or returns the option selected in a ButtonGroup by its text value.
"""
search = self._selected.get() # a string containing the selected option
# This is a bit nasty - suggestions welcome
for item in self._rbuttons:
if item.value == search:
return item.text
return "" | [
"def",
"value_text",
"(",
"self",
")",
":",
"search",
"=",
"self",
".",
"_selected",
".",
"get",
"(",
")",
"# a string containing the selected option",
"# This is a bit nasty - suggestions welcome",
"for",
"item",
"in",
"self",
".",
"_rbuttons",
":",
"if",
"item",
".",
"value",
"==",
"search",
":",
"return",
"item",
".",
"text",
"return",
"\"\""
] | Sets or returns the option selected in a ButtonGroup by its text value. | [
"Sets",
"or",
"returns",
"the",
"option",
"selected",
"in",
"a",
"ButtonGroup",
"by",
"its",
"text",
"value",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L171-L180 | train | 231,907 |
lawsie/guizero | guizero/ButtonGroup.py | ButtonGroup.append | def append(self, option):
"""
Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.append(self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height) | python | def append(self, option):
"""
Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.append(self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height) | [
"def",
"append",
"(",
"self",
",",
"option",
")",
":",
"self",
".",
"_options",
".",
"append",
"(",
"self",
".",
"_parse_option",
"(",
"option",
")",
")",
"self",
".",
"_refresh_options",
"(",
")",
"self",
".",
"resize",
"(",
"self",
".",
"_width",
",",
"self",
".",
"_height",
")"
] | Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value. | [
"Appends",
"a",
"new",
"option",
"to",
"the",
"end",
"of",
"the",
"ButtonGroup",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L235-L245 | train | 231,908 |
lawsie/guizero | guizero/ButtonGroup.py | ButtonGroup.insert | def insert(self, index, option):
"""
Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.insert(index, self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height) | python | def insert(self, index, option):
"""
Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.insert(index, self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"option",
")",
":",
"self",
".",
"_options",
".",
"insert",
"(",
"index",
",",
"self",
".",
"_parse_option",
"(",
"option",
")",
")",
"self",
".",
"_refresh_options",
"(",
")",
"self",
".",
"resize",
"(",
"self",
".",
"_width",
",",
"self",
".",
"_height",
")"
] | Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value. | [
"Insert",
"a",
"new",
"option",
"in",
"the",
"ButtonGroup",
"at",
"index",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L247-L260 | train | 231,909 |
lawsie/guizero | guizero/ButtonGroup.py | ButtonGroup.remove | def remove(self, option):
"""
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
"""
for existing_option in self._options:
if existing_option[1] == option:
self._options.remove(existing_option)
self._refresh_options()
return True
return False | python | def remove(self, option):
"""
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
"""
for existing_option in self._options:
if existing_option[1] == option:
self._options.remove(existing_option)
self._refresh_options()
return True
return False | [
"def",
"remove",
"(",
"self",
",",
"option",
")",
":",
"for",
"existing_option",
"in",
"self",
".",
"_options",
":",
"if",
"existing_option",
"[",
"1",
"]",
"==",
"option",
":",
"self",
".",
"_options",
".",
"remove",
"(",
"existing_option",
")",
"self",
".",
"_refresh_options",
"(",
")",
"return",
"True",
"return",
"False"
] | Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup. | [
"Removes",
"the",
"first",
"option",
"from",
"the",
"ButtonGroup",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L262-L276 | train | 231,910 |
lawsie/guizero | guizero/ButtonGroup.py | ButtonGroup.update_command | def update_command(self, command, args=None):
"""
Updates the callback command which is called when the ButtonGroup
changes.
Setting to `None` stops the callback.
:param callback command:
The callback function to call.
:param callback args:
A list of arguments to pass to the widgets `command`, defaults to
`None`.
"""
if command is None:
self._command = lambda: None
else:
if args is None:
self._command = command
else:
self._command = utils.with_args(command, *args) | python | def update_command(self, command, args=None):
"""
Updates the callback command which is called when the ButtonGroup
changes.
Setting to `None` stops the callback.
:param callback command:
The callback function to call.
:param callback args:
A list of arguments to pass to the widgets `command`, defaults to
`None`.
"""
if command is None:
self._command = lambda: None
else:
if args is None:
self._command = command
else:
self._command = utils.with_args(command, *args) | [
"def",
"update_command",
"(",
"self",
",",
"command",
",",
"args",
"=",
"None",
")",
":",
"if",
"command",
"is",
"None",
":",
"self",
".",
"_command",
"=",
"lambda",
":",
"None",
"else",
":",
"if",
"args",
"is",
"None",
":",
"self",
".",
"_command",
"=",
"command",
"else",
":",
"self",
".",
"_command",
"=",
"utils",
".",
"with_args",
"(",
"command",
",",
"*",
"args",
")"
] | Updates the callback command which is called when the ButtonGroup
changes.
Setting to `None` stops the callback.
:param callback command:
The callback function to call.
:param callback args:
A list of arguments to pass to the widgets `command`, defaults to
`None`. | [
"Updates",
"the",
"callback",
"command",
"which",
"is",
"called",
"when",
"the",
"ButtonGroup",
"changes",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L290-L310 | train | 231,911 |
lawsie/guizero | guizero/Combo.py | Combo.insert | def insert(self, index, option):
"""
Insert a new `option` in the Combo at `index`.
:param int option:
The index of where to insert the option.
:param string option:
The option to insert into to the Combo.
"""
option = str(option)
self._options.insert(index, option)
# if this is the first option, set it.
if len(self._options) == 1:
self.value = option
self._refresh_options() | python | def insert(self, index, option):
"""
Insert a new `option` in the Combo at `index`.
:param int option:
The index of where to insert the option.
:param string option:
The option to insert into to the Combo.
"""
option = str(option)
self._options.insert(index, option)
# if this is the first option, set it.
if len(self._options) == 1:
self.value = option
self._refresh_options() | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"option",
")",
":",
"option",
"=",
"str",
"(",
"option",
")",
"self",
".",
"_options",
".",
"insert",
"(",
"index",
",",
"option",
")",
"# if this is the first option, set it.",
"if",
"len",
"(",
"self",
".",
"_options",
")",
"==",
"1",
":",
"self",
".",
"value",
"=",
"option",
"self",
".",
"_refresh_options",
"(",
")"
] | Insert a new `option` in the Combo at `index`.
:param int option:
The index of where to insert the option.
:param string option:
The option to insert into to the Combo. | [
"Insert",
"a",
"new",
"option",
"in",
"the",
"Combo",
"at",
"index",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L204-L220 | train | 231,912 |
lawsie/guizero | guizero/Combo.py | Combo.remove | def remove(self, option):
"""
Removes the first `option` from the Combo.
Returns `True` if an item was removed.
:param string option:
The option to remove from the Combo.
"""
if option in self._options:
if len(self._options) == 1:
# this is the last option in the list so clear it
self.clear()
else:
self._options.remove(option)
self._refresh_options()
# have we just removed the selected option?
# if so set it to the first option
if option == self.value:
self._set_option(self._options[0])
return True
else:
return False | python | def remove(self, option):
"""
Removes the first `option` from the Combo.
Returns `True` if an item was removed.
:param string option:
The option to remove from the Combo.
"""
if option in self._options:
if len(self._options) == 1:
# this is the last option in the list so clear it
self.clear()
else:
self._options.remove(option)
self._refresh_options()
# have we just removed the selected option?
# if so set it to the first option
if option == self.value:
self._set_option(self._options[0])
return True
else:
return False | [
"def",
"remove",
"(",
"self",
",",
"option",
")",
":",
"if",
"option",
"in",
"self",
".",
"_options",
":",
"if",
"len",
"(",
"self",
".",
"_options",
")",
"==",
"1",
":",
"# this is the last option in the list so clear it",
"self",
".",
"clear",
"(",
")",
"else",
":",
"self",
".",
"_options",
".",
"remove",
"(",
"option",
")",
"self",
".",
"_refresh_options",
"(",
")",
"# have we just removed the selected option?",
"# if so set it to the first option",
"if",
"option",
"==",
"self",
".",
"value",
":",
"self",
".",
"_set_option",
"(",
"self",
".",
"_options",
"[",
"0",
"]",
")",
"return",
"True",
"else",
":",
"return",
"False"
] | Removes the first `option` from the Combo.
Returns `True` if an item was removed.
:param string option:
The option to remove from the Combo. | [
"Removes",
"the",
"first",
"option",
"from",
"the",
"Combo",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L222-L244 | train | 231,913 |
lawsie/guizero | guizero/Combo.py | Combo.clear | def clear(self):
"""
Clears all the options in a Combo
"""
self._options = []
self._combo_menu.tk.delete(0, END)
self._selected.set("") | python | def clear(self):
"""
Clears all the options in a Combo
"""
self._options = []
self._combo_menu.tk.delete(0, END)
self._selected.set("") | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_options",
"=",
"[",
"]",
"self",
".",
"_combo_menu",
".",
"tk",
".",
"delete",
"(",
"0",
",",
"END",
")",
"self",
".",
"_selected",
".",
"set",
"(",
"\"\"",
")"
] | Clears all the options in a Combo | [
"Clears",
"all",
"the",
"options",
"in",
"a",
"Combo"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L247-L253 | train | 231,914 |
lawsie/guizero | guizero/Combo.py | Combo._set_option | def _set_option(self, value):
"""
Sets a single option in the Combo, returning True if it was able too.
"""
if len(self._options) > 0:
if value in self._options:
self._selected.set(value)
return True
else:
return False
else:
return False | python | def _set_option(self, value):
"""
Sets a single option in the Combo, returning True if it was able too.
"""
if len(self._options) > 0:
if value in self._options:
self._selected.set(value)
return True
else:
return False
else:
return False | [
"def",
"_set_option",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"self",
".",
"_options",
")",
">",
"0",
":",
"if",
"value",
"in",
"self",
".",
"_options",
":",
"self",
".",
"_selected",
".",
"set",
"(",
"value",
")",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"return",
"False"
] | Sets a single option in the Combo, returning True if it was able too. | [
"Sets",
"a",
"single",
"option",
"in",
"the",
"Combo",
"returning",
"True",
"if",
"it",
"was",
"able",
"too",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L271-L282 | train | 231,915 |
lawsie/guizero | guizero/Combo.py | Combo._set_option_by_index | def _set_option_by_index(self, index):
"""
Sets a single option in the Combo by its index, returning True if it was able too.
"""
if index < len(self._options):
self._selected.set(self._options[index])
return True
else:
return False | python | def _set_option_by_index(self, index):
"""
Sets a single option in the Combo by its index, returning True if it was able too.
"""
if index < len(self._options):
self._selected.set(self._options[index])
return True
else:
return False | [
"def",
"_set_option_by_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"<",
"len",
"(",
"self",
".",
"_options",
")",
":",
"self",
".",
"_selected",
".",
"set",
"(",
"self",
".",
"_options",
"[",
"index",
"]",
")",
"return",
"True",
"else",
":",
"return",
"False"
] | Sets a single option in the Combo by its index, returning True if it was able too. | [
"Sets",
"a",
"single",
"option",
"in",
"the",
"Combo",
"by",
"its",
"index",
"returning",
"True",
"if",
"it",
"was",
"able",
"too",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L284-L292 | train | 231,916 |
lawsie/guizero | guizero/tkmixins.py | ScheduleMixin.after | def after(self, time, function, args = []):
"""Call `function` after `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, False] | python | def after(self, time, function, args = []):
"""Call `function` after `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, False] | [
"def",
"after",
"(",
"self",
",",
"time",
",",
"function",
",",
"args",
"=",
"[",
"]",
")",
":",
"callback_id",
"=",
"self",
".",
"tk",
".",
"after",
"(",
"time",
",",
"self",
".",
"_call_wrapper",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
"self",
".",
"_callback",
"[",
"function",
"]",
"=",
"[",
"callback_id",
",",
"False",
"]"
] | Call `function` after `time` milliseconds. | [
"Call",
"function",
"after",
"time",
"milliseconds",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L8-L11 | train | 231,917 |
lawsie/guizero | guizero/tkmixins.py | ScheduleMixin.repeat | def repeat(self, time, function, args = []):
"""Repeat `function` every `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, True] | python | def repeat(self, time, function, args = []):
"""Repeat `function` every `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, True] | [
"def",
"repeat",
"(",
"self",
",",
"time",
",",
"function",
",",
"args",
"=",
"[",
"]",
")",
":",
"callback_id",
"=",
"self",
".",
"tk",
".",
"after",
"(",
"time",
",",
"self",
".",
"_call_wrapper",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
"self",
".",
"_callback",
"[",
"function",
"]",
"=",
"[",
"callback_id",
",",
"True",
"]"
] | Repeat `function` every `time` milliseconds. | [
"Repeat",
"function",
"every",
"time",
"milliseconds",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L13-L16 | train | 231,918 |
lawsie/guizero | guizero/tkmixins.py | ScheduleMixin.cancel | def cancel(self, function):
"""Cancel the scheduled `function` calls."""
if function in self._callback.keys():
callback_id = self._callback[function][0]
self.tk.after_cancel(callback_id)
self._callback.pop(function)
else:
utils.error_format("Could not cancel function - it doesnt exist, it may have already run") | python | def cancel(self, function):
"""Cancel the scheduled `function` calls."""
if function in self._callback.keys():
callback_id = self._callback[function][0]
self.tk.after_cancel(callback_id)
self._callback.pop(function)
else:
utils.error_format("Could not cancel function - it doesnt exist, it may have already run") | [
"def",
"cancel",
"(",
"self",
",",
"function",
")",
":",
"if",
"function",
"in",
"self",
".",
"_callback",
".",
"keys",
"(",
")",
":",
"callback_id",
"=",
"self",
".",
"_callback",
"[",
"function",
"]",
"[",
"0",
"]",
"self",
".",
"tk",
".",
"after_cancel",
"(",
"callback_id",
")",
"self",
".",
"_callback",
".",
"pop",
"(",
"function",
")",
"else",
":",
"utils",
".",
"error_format",
"(",
"\"Could not cancel function - it doesnt exist, it may have already run\"",
")"
] | Cancel the scheduled `function` calls. | [
"Cancel",
"the",
"scheduled",
"function",
"calls",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L18-L25 | train | 231,919 |
lawsie/guizero | guizero/tkmixins.py | ScheduleMixin._call_wrapper | def _call_wrapper(self, time, function, *args):
"""Fired by tk.after, gets the callback and either executes the function and cancels or repeats"""
# execute the function
function(*args)
if function in self._callback.keys():
repeat = self._callback[function][1]
if repeat:
# setup the call back again and update the id
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function][0] = callback_id
else:
# remove it from the call back dictionary
self._callback.pop(function) | python | def _call_wrapper(self, time, function, *args):
"""Fired by tk.after, gets the callback and either executes the function and cancels or repeats"""
# execute the function
function(*args)
if function in self._callback.keys():
repeat = self._callback[function][1]
if repeat:
# setup the call back again and update the id
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function][0] = callback_id
else:
# remove it from the call back dictionary
self._callback.pop(function) | [
"def",
"_call_wrapper",
"(",
"self",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
":",
"# execute the function",
"function",
"(",
"*",
"args",
")",
"if",
"function",
"in",
"self",
".",
"_callback",
".",
"keys",
"(",
")",
":",
"repeat",
"=",
"self",
".",
"_callback",
"[",
"function",
"]",
"[",
"1",
"]",
"if",
"repeat",
":",
"# setup the call back again and update the id",
"callback_id",
"=",
"self",
".",
"tk",
".",
"after",
"(",
"time",
",",
"self",
".",
"_call_wrapper",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
"self",
".",
"_callback",
"[",
"function",
"]",
"[",
"0",
"]",
"=",
"callback_id",
"else",
":",
"# remove it from the call back dictionary",
"self",
".",
"_callback",
".",
"pop",
"(",
"function",
")"
] | Fired by tk.after, gets the callback and either executes the function and cancels or repeats | [
"Fired",
"by",
"tk",
".",
"after",
"gets",
"the",
"callback",
"and",
"either",
"executes",
"the",
"function",
"and",
"cancels",
"or",
"repeats"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L27-L39 | train | 231,920 |
lawsie/guizero | guizero/event.py | EventCallback.rebind | def rebind(self, tks):
"""
Rebinds the tk event, only used if a widget has been destroyed
and recreated.
"""
self._tks = tks
for tk in self._tks:
tk.unbind_all(self._tk_event)
func_id = tk.bind(self._tk_event, self._event_callback)
self._func_ids.append(func_id) | python | def rebind(self, tks):
"""
Rebinds the tk event, only used if a widget has been destroyed
and recreated.
"""
self._tks = tks
for tk in self._tks:
tk.unbind_all(self._tk_event)
func_id = tk.bind(self._tk_event, self._event_callback)
self._func_ids.append(func_id) | [
"def",
"rebind",
"(",
"self",
",",
"tks",
")",
":",
"self",
".",
"_tks",
"=",
"tks",
"for",
"tk",
"in",
"self",
".",
"_tks",
":",
"tk",
".",
"unbind_all",
"(",
"self",
".",
"_tk_event",
")",
"func_id",
"=",
"tk",
".",
"bind",
"(",
"self",
".",
"_tk_event",
",",
"self",
".",
"_event_callback",
")",
"self",
".",
"_func_ids",
".",
"append",
"(",
"func_id",
")"
] | Rebinds the tk event, only used if a widget has been destroyed
and recreated. | [
"Rebinds",
"the",
"tk",
"event",
"only",
"used",
"if",
"a",
"widget",
"has",
"been",
"destroyed",
"and",
"recreated",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/event.py#L129-L138 | train | 231,921 |
lawsie/guizero | guizero/event.py | EventManager.rebind_events | def rebind_events(self, *tks):
"""
Rebinds all the tk events, only used if a tk widget has been destroyed
and recreated.
"""
for ref in self._refs:
self._refs[ref].rebind(tks) | python | def rebind_events(self, *tks):
"""
Rebinds all the tk events, only used if a tk widget has been destroyed
and recreated.
"""
for ref in self._refs:
self._refs[ref].rebind(tks) | [
"def",
"rebind_events",
"(",
"self",
",",
"*",
"tks",
")",
":",
"for",
"ref",
"in",
"self",
".",
"_refs",
":",
"self",
".",
"_refs",
"[",
"ref",
"]",
".",
"rebind",
"(",
"tks",
")"
] | Rebinds all the tk events, only used if a tk widget has been destroyed
and recreated. | [
"Rebinds",
"all",
"the",
"tk",
"events",
"only",
"used",
"if",
"a",
"tk",
"widget",
"has",
"been",
"destroyed",
"and",
"recreated",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/event.py#L200-L206 | train | 231,922 |
lawsie/guizero | guizero/Box.py | Box.set_border | def set_border(self, thickness, color="black"):
"""
Sets the border thickness and color.
:param int thickness:
The thickenss of the border.
:param str color:
The color of the border.
"""
self._set_tk_config("highlightthickness", thickness)
self._set_tk_config("highlightbackground", utils.convert_color(color)) | python | def set_border(self, thickness, color="black"):
"""
Sets the border thickness and color.
:param int thickness:
The thickenss of the border.
:param str color:
The color of the border.
"""
self._set_tk_config("highlightthickness", thickness)
self._set_tk_config("highlightbackground", utils.convert_color(color)) | [
"def",
"set_border",
"(",
"self",
",",
"thickness",
",",
"color",
"=",
"\"black\"",
")",
":",
"self",
".",
"_set_tk_config",
"(",
"\"highlightthickness\"",
",",
"thickness",
")",
"self",
".",
"_set_tk_config",
"(",
"\"highlightbackground\"",
",",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] | Sets the border thickness and color.
:param int thickness:
The thickenss of the border.
:param str color:
The color of the border. | [
"Sets",
"the",
"border",
"thickness",
"and",
"color",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Box.py#L87-L98 | train | 231,923 |
lawsie/guizero | guizero/Window.py | Window.hide | def hide(self):
"""Hide the window."""
self.tk.withdraw()
self._visible = False
if self._modal:
self.tk.grab_release() | python | def hide(self):
"""Hide the window."""
self.tk.withdraw()
self._visible = False
if self._modal:
self.tk.grab_release() | [
"def",
"hide",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"withdraw",
"(",
")",
"self",
".",
"_visible",
"=",
"False",
"if",
"self",
".",
"_modal",
":",
"self",
".",
"tk",
".",
"grab_release",
"(",
")"
] | Hide the window. | [
"Hide",
"the",
"window",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Window.py#L32-L37 | train | 231,924 |
lawsie/guizero | guizero/Window.py | Window.show | def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set() | python | def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set() | [
"def",
"show",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"self",
".",
"tk",
".",
"deiconify",
"(",
")",
"self",
".",
"_visible",
"=",
"True",
"self",
".",
"_modal",
"=",
"wait",
"if",
"self",
".",
"_modal",
":",
"self",
".",
"tk",
".",
"grab_set",
"(",
")"
] | Show the window. | [
"Show",
"the",
"window",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Window.py#L39-L45 | train | 231,925 |
lawsie/guizero | guizero/App.py | App.destroy | def destroy(self):
"""
Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used.
"""
# if this is the main_app - set the _main_app class variable to `None`.
if self == App._main_app:
App._main_app = None
self.tk.destroy() | python | def destroy(self):
"""
Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used.
"""
# if this is the main_app - set the _main_app class variable to `None`.
if self == App._main_app:
App._main_app = None
self.tk.destroy() | [
"def",
"destroy",
"(",
"self",
")",
":",
"# if this is the main_app - set the _main_app class variable to `None`.",
"if",
"self",
"==",
"App",
".",
"_main_app",
":",
"App",
".",
"_main_app",
"=",
"None",
"self",
".",
"tk",
".",
"destroy",
"(",
")"
] | Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used. | [
"Destroy",
"and",
"close",
"the",
"App",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/App.py#L51-L64 | train | 231,926 |
lawsie/guizero | guizero/Drawing.py | Drawing.line | def line(self, x1, y1, x2, y2, color="black", width=1):
"""
Draws a line between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the line. Defaults to `"black"`.
:param int width:
The width of the line. Defaults to `1`.
:return:
The id of the line.
"""
return self.tk.create_line(
x1, y1, x2, y2,
width = width,
fill = "" if color is None else utils.convert_color(color)
) | python | def line(self, x1, y1, x2, y2, color="black", width=1):
"""
Draws a line between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the line. Defaults to `"black"`.
:param int width:
The width of the line. Defaults to `1`.
:return:
The id of the line.
"""
return self.tk.create_line(
x1, y1, x2, y2,
width = width,
fill = "" if color is None else utils.convert_color(color)
) | [
"def",
"line",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"color",
"=",
"\"black\"",
",",
"width",
"=",
"1",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_line",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"width",
"=",
"width",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] | Draws a line between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the line. Defaults to `"black"`.
:param int width:
The width of the line. Defaults to `1`.
:return:
The id of the line. | [
"Draws",
"a",
"line",
"between",
"2",
"points"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L49-L78 | train | 231,927 |
lawsie/guizero | guizero/Drawing.py | Drawing.oval | def oval(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws an oval between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_oval(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
) | python | def oval(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws an oval between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_oval(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
) | [
"def",
"oval",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_oval",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"outline",
"=",
"utils",
".",
"convert_color",
"(",
"outline_color",
")",
"if",
"outline",
"else",
"\"\"",
",",
"width",
"=",
"int",
"(",
"outline",
")",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] | Draws an oval between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape. | [
"Draws",
"an",
"oval",
"between",
"2",
"points"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L80-L113 | train | 231,928 |
lawsie/guizero | guizero/Drawing.py | Drawing.rectangle | def rectangle(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_rectangle(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
) | python | def rectangle(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_rectangle(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
) | [
"def",
"rectangle",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_rectangle",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"outline",
"=",
"utils",
".",
"convert_color",
"(",
"outline_color",
")",
"if",
"outline",
"else",
"\"\"",
",",
"width",
"=",
"int",
"(",
"outline",
")",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] | Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape. | [
"Draws",
"a",
"rectangle",
"between",
"2",
"points"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L115-L148 | train | 231,929 |
lawsie/guizero | guizero/Drawing.py | Drawing.polygon | def polygon(self, *coords, color="black", outline=False, outline_color="black"):
"""
Draws a polygon from an list of co-ordinates
:param int *coords:
Pairs of x and y positions which make up the polygon.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_polygon(
*coords,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
) | python | def polygon(self, *coords, color="black", outline=False, outline_color="black"):
"""
Draws a polygon from an list of co-ordinates
:param int *coords:
Pairs of x and y positions which make up the polygon.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_polygon(
*coords,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
) | [
"def",
"polygon",
"(",
"self",
",",
"*",
"coords",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_polygon",
"(",
"*",
"coords",
",",
"outline",
"=",
"utils",
".",
"convert_color",
"(",
"outline_color",
")",
"if",
"outline",
"else",
"\"\"",
",",
"width",
"=",
"int",
"(",
"outline",
")",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] | Draws a polygon from an list of co-ordinates
:param int *coords:
Pairs of x and y positions which make up the polygon.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape. | [
"Draws",
"a",
"polygon",
"from",
"an",
"list",
"of",
"co",
"-",
"ordinates"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L150-L174 | train | 231,930 |
lawsie/guizero | guizero/Drawing.py | Drawing.triangle | def triangle(self, x1, y1, x2, y2, x3, y3, color="black", outline=False, outline_color="black"):
"""
Draws a triangle between 3 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the middle point.
:param int y2:
The y position of the middle point.
:param int x3:
The x position of the end point.
:param int y3:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.polygon(
x1, y1, x2, y2, x3, y3,
color=color,
outline=outline,
outline_color=outline_color) | python | def triangle(self, x1, y1, x2, y2, x3, y3, color="black", outline=False, outline_color="black"):
"""
Draws a triangle between 3 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the middle point.
:param int y2:
The y position of the middle point.
:param int x3:
The x position of the end point.
:param int y3:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.polygon(
x1, y1, x2, y2, x3, y3,
color=color,
outline=outline,
outline_color=outline_color) | [
"def",
"triangle",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"polygon",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
",",
"color",
"=",
"color",
",",
"outline",
"=",
"outline",
",",
"outline_color",
"=",
"outline_color",
")"
] | Draws a triangle between 3 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the middle point.
:param int y2:
The y position of the middle point.
:param int x3:
The x position of the end point.
:param int y3:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape. | [
"Draws",
"a",
"triangle",
"between",
"3",
"points"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L176-L214 | train | 231,931 |
lawsie/guizero | guizero/base.py | Base._get_tk_config | def _get_tk_config(self, key, default=False):
"""
Gets the config from the widget's tk object.
:param string key:
The tk config key.
:param bool default:
Returns the default value for this key. Defaults to `False`.
"""
if default:
return self._tk_defaults[key]
else:
return self.tk[key] | python | def _get_tk_config(self, key, default=False):
"""
Gets the config from the widget's tk object.
:param string key:
The tk config key.
:param bool default:
Returns the default value for this key. Defaults to `False`.
"""
if default:
return self._tk_defaults[key]
else:
return self.tk[key] | [
"def",
"_get_tk_config",
"(",
"self",
",",
"key",
",",
"default",
"=",
"False",
")",
":",
"if",
"default",
":",
"return",
"self",
".",
"_tk_defaults",
"[",
"key",
"]",
"else",
":",
"return",
"self",
".",
"tk",
"[",
"key",
"]"
] | Gets the config from the widget's tk object.
:param string key:
The tk config key.
:param bool default:
Returns the default value for this key. Defaults to `False`. | [
"Gets",
"the",
"config",
"from",
"the",
"widget",
"s",
"tk",
"object",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L62-L75 | train | 231,932 |
lawsie/guizero | guizero/base.py | Base._set_tk_config | def _set_tk_config(self, keys, value):
"""
Gets the config from the widget's tk object
:param string/List keys:
The tk config key or a list of tk keys.
:param variable value:
The value to set. If the value is `None`, the config value will be
reset to its default.
"""
# if a single key is passed, convert to list
if isinstance(keys, str):
keys = [keys]
# loop through all the keys
for key in keys:
if key in self.tk.keys():
if value is None:
# reset to default
self.tk[key] = self._tk_defaults[key]
else:
self.tk[key] = value | python | def _set_tk_config(self, keys, value):
"""
Gets the config from the widget's tk object
:param string/List keys:
The tk config key or a list of tk keys.
:param variable value:
The value to set. If the value is `None`, the config value will be
reset to its default.
"""
# if a single key is passed, convert to list
if isinstance(keys, str):
keys = [keys]
# loop through all the keys
for key in keys:
if key in self.tk.keys():
if value is None:
# reset to default
self.tk[key] = self._tk_defaults[key]
else:
self.tk[key] = value | [
"def",
"_set_tk_config",
"(",
"self",
",",
"keys",
",",
"value",
")",
":",
"# if a single key is passed, convert to list",
"if",
"isinstance",
"(",
"keys",
",",
"str",
")",
":",
"keys",
"=",
"[",
"keys",
"]",
"# loop through all the keys",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"in",
"self",
".",
"tk",
".",
"keys",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"# reset to default",
"self",
".",
"tk",
"[",
"key",
"]",
"=",
"self",
".",
"_tk_defaults",
"[",
"key",
"]",
"else",
":",
"self",
".",
"tk",
"[",
"key",
"]",
"=",
"value"
] | Gets the config from the widget's tk object
:param string/List keys:
The tk config key or a list of tk keys.
:param variable value:
The value to set. If the value is `None`, the config value will be
reset to its default. | [
"Gets",
"the",
"config",
"from",
"the",
"widget",
"s",
"tk",
"object"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L77-L100 | train | 231,933 |
lawsie/guizero | guizero/base.py | Component.destroy | def destroy(self):
"""
Destroy the tk widget.
"""
# if this widget has a master remove the it from the master
if self.master is not None:
self.master._remove_child(self)
self.tk.destroy() | python | def destroy(self):
"""
Destroy the tk widget.
"""
# if this widget has a master remove the it from the master
if self.master is not None:
self.master._remove_child(self)
self.tk.destroy() | [
"def",
"destroy",
"(",
"self",
")",
":",
"# if this widget has a master remove the it from the master",
"if",
"self",
".",
"master",
"is",
"not",
"None",
":",
"self",
".",
"master",
".",
"_remove_child",
"(",
"self",
")",
"self",
".",
"tk",
".",
"destroy",
"(",
")"
] | Destroy the tk widget. | [
"Destroy",
"the",
"tk",
"widget",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L169-L177 | train | 231,934 |
lawsie/guizero | guizero/base.py | Container.add_tk_widget | def add_tk_widget(self, tk_widget, grid=None, align=None, visible=True, enabled=None, width=None, height=None):
"""
Adds a tk widget into a guizero container.
:param tkinter.Widget tk_widget:
The Container (App, Box, etc) the tk widget will belong too.
:param List grid:
Grid co-ordinates for the widget, required if the master layout
is 'grid', defaults to `None`.
:param string align:
How to align the widget within the grid, defaults to None.
:param bool visible:
If the widget should be visible, defaults to `True`.
:param bool enabled:
If the widget should be enabled, defaults to `None`. If `None`
the value is inherited from the master.
:param int width:
The starting width of the widget. Defaults to `None` and will auto
size.
:param int height:
The starting height of the widget. Defaults to `None` and will auto
size.
"""
return Widget(self, tk_widget, "tk widget", grid, align, visible, enabled, width, height) | python | def add_tk_widget(self, tk_widget, grid=None, align=None, visible=True, enabled=None, width=None, height=None):
"""
Adds a tk widget into a guizero container.
:param tkinter.Widget tk_widget:
The Container (App, Box, etc) the tk widget will belong too.
:param List grid:
Grid co-ordinates for the widget, required if the master layout
is 'grid', defaults to `None`.
:param string align:
How to align the widget within the grid, defaults to None.
:param bool visible:
If the widget should be visible, defaults to `True`.
:param bool enabled:
If the widget should be enabled, defaults to `None`. If `None`
the value is inherited from the master.
:param int width:
The starting width of the widget. Defaults to `None` and will auto
size.
:param int height:
The starting height of the widget. Defaults to `None` and will auto
size.
"""
return Widget(self, tk_widget, "tk widget", grid, align, visible, enabled, width, height) | [
"def",
"add_tk_widget",
"(",
"self",
",",
"tk_widget",
",",
"grid",
"=",
"None",
",",
"align",
"=",
"None",
",",
"visible",
"=",
"True",
",",
"enabled",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"return",
"Widget",
"(",
"self",
",",
"tk_widget",
",",
"\"tk widget\"",
",",
"grid",
",",
"align",
",",
"visible",
",",
"enabled",
",",
"width",
",",
"height",
")"
] | Adds a tk widget into a guizero container.
:param tkinter.Widget tk_widget:
The Container (App, Box, etc) the tk widget will belong too.
:param List grid:
Grid co-ordinates for the widget, required if the master layout
is 'grid', defaults to `None`.
:param string align:
How to align the widget within the grid, defaults to None.
:param bool visible:
If the widget should be visible, defaults to `True`.
:param bool enabled:
If the widget should be enabled, defaults to `None`. If `None`
the value is inherited from the master.
:param int width:
The starting width of the widget. Defaults to `None` and will auto
size.
:param int height:
The starting height of the widget. Defaults to `None` and will auto
size. | [
"Adds",
"a",
"tk",
"widget",
"into",
"a",
"guizero",
"container",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L289-L318 | train | 231,935 |
lawsie/guizero | guizero/base.py | Container.display_widgets | def display_widgets(self):
"""
Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded".
"""
# All widgets are removed and then recreated to ensure the order they
# were created is the order they are displayed.
for child in self.children:
if child.displayable:
# forget the widget
if self.layout != "grid":
child.tk.pack_forget()
else:
child.tk.grid_forget()
# display the widget
if child.visible:
if self.layout != "grid":
self._pack_widget(child)
else:
self._grid_widget(child) | python | def display_widgets(self):
"""
Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded".
"""
# All widgets are removed and then recreated to ensure the order they
# were created is the order they are displayed.
for child in self.children:
if child.displayable:
# forget the widget
if self.layout != "grid":
child.tk.pack_forget()
else:
child.tk.grid_forget()
# display the widget
if child.visible:
if self.layout != "grid":
self._pack_widget(child)
else:
self._grid_widget(child) | [
"def",
"display_widgets",
"(",
"self",
")",
":",
"# All widgets are removed and then recreated to ensure the order they",
"# were created is the order they are displayed.",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"child",
".",
"displayable",
":",
"# forget the widget",
"if",
"self",
".",
"layout",
"!=",
"\"grid\"",
":",
"child",
".",
"tk",
".",
"pack_forget",
"(",
")",
"else",
":",
"child",
".",
"tk",
".",
"grid_forget",
"(",
")",
"# display the widget",
"if",
"child",
".",
"visible",
":",
"if",
"self",
".",
"layout",
"!=",
"\"grid\"",
":",
"self",
".",
"_pack_widget",
"(",
"child",
")",
"else",
":",
"self",
".",
"_grid_widget",
"(",
"child",
")"
] | Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded". | [
"Displays",
"all",
"the",
"widgets",
"associated",
"with",
"this",
"Container",
"."
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L334-L358 | train | 231,936 |
lawsie/guizero | guizero/base.py | Container.disable | def disable(self):
"""
Disable all the widgets in this container
"""
self._enabled = False
for child in self.children:
if isinstance(child, (Container, Widget)):
child.disable() | python | def disable(self):
"""
Disable all the widgets in this container
"""
self._enabled = False
for child in self.children:
if isinstance(child, (Container, Widget)):
child.disable() | [
"def",
"disable",
"(",
"self",
")",
":",
"self",
".",
"_enabled",
"=",
"False",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"(",
"Container",
",",
"Widget",
")",
")",
":",
"child",
".",
"disable",
"(",
")"
] | Disable all the widgets in this container | [
"Disable",
"all",
"the",
"widgets",
"in",
"this",
"container"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L442-L449 | train | 231,937 |
lawsie/guizero | guizero/base.py | Container.enable | def enable(self):
"""
Enable all the widgets in this container
"""
self._enabled = True
for child in self.children:
if isinstance(child, (Container, Widget)):
child.enable() | python | def enable(self):
"""
Enable all the widgets in this container
"""
self._enabled = True
for child in self.children:
if isinstance(child, (Container, Widget)):
child.enable() | [
"def",
"enable",
"(",
"self",
")",
":",
"self",
".",
"_enabled",
"=",
"True",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"(",
"Container",
",",
"Widget",
")",
")",
":",
"child",
".",
"enable",
"(",
")"
] | Enable all the widgets in this container | [
"Enable",
"all",
"the",
"widgets",
"in",
"this",
"container"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L451-L458 | train | 231,938 |
lawsie/guizero | guizero/base.py | BaseWindow.exit_full_screen | def exit_full_screen(self):
"""Change from full screen to windowed mode and remove key binding"""
self.tk.attributes("-fullscreen", False)
self._full_screen = False
self.events.remove_event("<FullScreen.Escape>") | python | def exit_full_screen(self):
"""Change from full screen to windowed mode and remove key binding"""
self.tk.attributes("-fullscreen", False)
self._full_screen = False
self.events.remove_event("<FullScreen.Escape>") | [
"def",
"exit_full_screen",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"attributes",
"(",
"\"-fullscreen\"",
",",
"False",
")",
"self",
".",
"_full_screen",
"=",
"False",
"self",
".",
"events",
".",
"remove_event",
"(",
"\"<FullScreen.Escape>\"",
")"
] | Change from full screen to windowed mode and remove key binding | [
"Change",
"from",
"full",
"screen",
"to",
"windowed",
"mode",
"and",
"remove",
"key",
"binding"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L585-L589 | train | 231,939 |
lawsie/guizero | guizero/base.py | ContainerWidget._set_propagation | def _set_propagation(self, width, height):
"""
Set the propagation value of the tk widget dependent on the width and height
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
if width is None:
width = 0
if height is None:
height = 0
# set the propagate value
propagate_function = self.tk.pack_propagate
if self.layout == "grid":
propagate_function = self.tk.grid_propagate
propagate_value = True
# if height or width > 0 need to stop propagation
if isinstance(width, int):
if width > 0:
propagate_value = False
if isinstance(height, int):
if height > 0:
propagate_value = False
# if you specify a height or width you must specify they other
# (unless its a fill)
if isinstance(width, int) and isinstance(height, int):
if (width == 0 and height > 0) or (height == 0 and width > 0):
utils.error_format("You must specify a width and a height for {}".format(self.description))
propagate_function(propagate_value) | python | def _set_propagation(self, width, height):
"""
Set the propagation value of the tk widget dependent on the width and height
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
if width is None:
width = 0
if height is None:
height = 0
# set the propagate value
propagate_function = self.tk.pack_propagate
if self.layout == "grid":
propagate_function = self.tk.grid_propagate
propagate_value = True
# if height or width > 0 need to stop propagation
if isinstance(width, int):
if width > 0:
propagate_value = False
if isinstance(height, int):
if height > 0:
propagate_value = False
# if you specify a height or width you must specify they other
# (unless its a fill)
if isinstance(width, int) and isinstance(height, int):
if (width == 0 and height > 0) or (height == 0 and width > 0):
utils.error_format("You must specify a width and a height for {}".format(self.description))
propagate_function(propagate_value) | [
"def",
"_set_propagation",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"0",
"if",
"height",
"is",
"None",
":",
"height",
"=",
"0",
"# set the propagate value",
"propagate_function",
"=",
"self",
".",
"tk",
".",
"pack_propagate",
"if",
"self",
".",
"layout",
"==",
"\"grid\"",
":",
"propagate_function",
"=",
"self",
".",
"tk",
".",
"grid_propagate",
"propagate_value",
"=",
"True",
"# if height or width > 0 need to stop propagation",
"if",
"isinstance",
"(",
"width",
",",
"int",
")",
":",
"if",
"width",
">",
"0",
":",
"propagate_value",
"=",
"False",
"if",
"isinstance",
"(",
"height",
",",
"int",
")",
":",
"if",
"height",
">",
"0",
":",
"propagate_value",
"=",
"False",
"# if you specify a height or width you must specify they other",
"# (unless its a fill)",
"if",
"isinstance",
"(",
"width",
",",
"int",
")",
"and",
"isinstance",
"(",
"height",
",",
"int",
")",
":",
"if",
"(",
"width",
"==",
"0",
"and",
"height",
">",
"0",
")",
"or",
"(",
"height",
"==",
"0",
"and",
"width",
">",
"0",
")",
":",
"utils",
".",
"error_format",
"(",
"\"You must specify a width and a height for {}\"",
".",
"format",
"(",
"self",
".",
"description",
")",
")",
"propagate_function",
"(",
"propagate_value",
")"
] | Set the propagation value of the tk widget dependent on the width and height
:param int width:
The width of the widget.
:param int height:
The height of the widget. | [
"Set",
"the",
"propagation",
"value",
"of",
"the",
"tk",
"widget",
"dependent",
"on",
"the",
"width",
"and",
"height"
] | 84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2 | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L661-L698 | train | 231,940 |
angr/pyvex | pyvex/lifting/util/instr_helper.py | Instruction.load | def load(self, addr, ty):
"""
Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue
"""
rdt = self.irsb_c.load(addr.rdt, ty)
return VexValue(self.irsb_c, rdt) | python | def load(self, addr, ty):
"""
Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue
"""
rdt = self.irsb_c.load(addr.rdt, ty)
return VexValue(self.irsb_c, rdt) | [
"def",
"load",
"(",
"self",
",",
"addr",
",",
"ty",
")",
":",
"rdt",
"=",
"self",
".",
"irsb_c",
".",
"load",
"(",
"addr",
".",
"rdt",
",",
"ty",
")",
"return",
"VexValue",
"(",
"self",
".",
"irsb_c",
",",
"rdt",
")"
] | Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue | [
"Load",
"a",
"value",
"from",
"memory",
"into",
"a",
"VEX",
"temporary",
"register",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L207-L216 | train | 231,941 |
angr/pyvex | pyvex/lifting/util/instr_helper.py | Instruction.constant | def constant(self, val, ty):
"""
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
"""
if isinstance(val, VexValue) and not isinstance(val, IRExpr):
raise Exception('Constant cannot be made from VexValue or IRExpr')
rdt = self.irsb_c.mkconst(val, ty)
return VexValue(self.irsb_c, rdt) | python | def constant(self, val, ty):
"""
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
"""
if isinstance(val, VexValue) and not isinstance(val, IRExpr):
raise Exception('Constant cannot be made from VexValue or IRExpr')
rdt = self.irsb_c.mkconst(val, ty)
return VexValue(self.irsb_c, rdt) | [
"def",
"constant",
"(",
"self",
",",
"val",
",",
"ty",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"VexValue",
")",
"and",
"not",
"isinstance",
"(",
"val",
",",
"IRExpr",
")",
":",
"raise",
"Exception",
"(",
"'Constant cannot be made from VexValue or IRExpr'",
")",
"rdt",
"=",
"self",
".",
"irsb_c",
".",
"mkconst",
"(",
"val",
",",
"ty",
")",
"return",
"VexValue",
"(",
"self",
".",
"irsb_c",
",",
"rdt",
")"
] | Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue | [
"Creates",
"a",
"constant",
"as",
"a",
"VexValue"
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L218-L229 | train | 231,942 |
angr/pyvex | pyvex/lifting/util/instr_helper.py | Instruction.put | def put(self, val, reg):
"""
Puts a value from a VEX temporary register into a machine register.
This is how the results of operations done to registers get committed to the machine's state.
:param val: The VexValue to store (Want to store a constant? See Constant() first)
:param reg: The integer register number to store into, or register name
:return: None
"""
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val.rdt, offset) | python | def put(self, val, reg):
"""
Puts a value from a VEX temporary register into a machine register.
This is how the results of operations done to registers get committed to the machine's state.
:param val: The VexValue to store (Want to store a constant? See Constant() first)
:param reg: The integer register number to store into, or register name
:return: None
"""
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val.rdt, offset) | [
"def",
"put",
"(",
"self",
",",
"val",
",",
"reg",
")",
":",
"offset",
"=",
"self",
".",
"lookup_register",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
",",
"reg",
")",
"self",
".",
"irsb_c",
".",
"put",
"(",
"val",
".",
"rdt",
",",
"offset",
")"
] | Puts a value from a VEX temporary register into a machine register.
This is how the results of operations done to registers get committed to the machine's state.
:param val: The VexValue to store (Want to store a constant? See Constant() first)
:param reg: The integer register number to store into, or register name
:return: None | [
"Puts",
"a",
"value",
"from",
"a",
"VEX",
"temporary",
"register",
"into",
"a",
"machine",
"register",
".",
"This",
"is",
"how",
"the",
"results",
"of",
"operations",
"done",
"to",
"registers",
"get",
"committed",
"to",
"the",
"machine",
"s",
"state",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L255-L265 | train | 231,943 |
angr/pyvex | pyvex/lifting/util/instr_helper.py | Instruction.put_conditional | def put_conditional(self, cond, valiftrue, valiffalse, reg):
"""
Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, don't use this method!)
:param valiftrue: the VexValue to put in reg if cond evals as true
:param validfalse: the VexValue to put in reg if cond evals as false
:param reg: The integer register number to store into, or register name
:return: None
"""
val = self.irsb_c.ite(cond.rdt , valiftrue.rdt, valiffalse.rdt)
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val, offset) | python | def put_conditional(self, cond, valiftrue, valiffalse, reg):
"""
Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, don't use this method!)
:param valiftrue: the VexValue to put in reg if cond evals as true
:param validfalse: the VexValue to put in reg if cond evals as false
:param reg: The integer register number to store into, or register name
:return: None
"""
val = self.irsb_c.ite(cond.rdt , valiftrue.rdt, valiffalse.rdt)
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val, offset) | [
"def",
"put_conditional",
"(",
"self",
",",
"cond",
",",
"valiftrue",
",",
"valiffalse",
",",
"reg",
")",
":",
"val",
"=",
"self",
".",
"irsb_c",
".",
"ite",
"(",
"cond",
".",
"rdt",
",",
"valiftrue",
".",
"rdt",
",",
"valiffalse",
".",
"rdt",
")",
"offset",
"=",
"self",
".",
"lookup_register",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
",",
"reg",
")",
"self",
".",
"irsb_c",
".",
"put",
"(",
"val",
",",
"offset",
")"
] | Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, don't use this method!)
:param valiftrue: the VexValue to put in reg if cond evals as true
:param validfalse: the VexValue to put in reg if cond evals as false
:param reg: The integer register number to store into, or register name
:return: None | [
"Like",
"put",
"except",
"it",
"checks",
"a",
"condition",
"to",
"decide",
"what",
"to",
"put",
"in",
"the",
"destination",
"register",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L268-L283 | train | 231,944 |
angr/pyvex | pyvex/lifting/util/instr_helper.py | Instruction.store | def store(self, val, addr):
"""
Store a VexValue in memory at the specified loaction.
:param val: The VexValue of the value to store
:param addr: The VexValue of the address to store into
:return: None
"""
self.irsb_c.store(addr.rdt, val.rdt) | python | def store(self, val, addr):
"""
Store a VexValue in memory at the specified loaction.
:param val: The VexValue of the value to store
:param addr: The VexValue of the address to store into
:return: None
"""
self.irsb_c.store(addr.rdt, val.rdt) | [
"def",
"store",
"(",
"self",
",",
"val",
",",
"addr",
")",
":",
"self",
".",
"irsb_c",
".",
"store",
"(",
"addr",
".",
"rdt",
",",
"val",
".",
"rdt",
")"
] | Store a VexValue in memory at the specified loaction.
:param val: The VexValue of the value to store
:param addr: The VexValue of the address to store into
:return: None | [
"Store",
"a",
"VexValue",
"in",
"memory",
"at",
"the",
"specified",
"loaction",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L285-L293 | train | 231,945 |
angr/pyvex | pyvex/lifting/util/instr_helper.py | Instruction.jump | def jump(self, condition, to_addr, jumpkind=JumpKind.Boring, ip_offset=None):
"""
Jump to a specified destination, under the specified condition.
Used for branches, jumps, calls, returns, etc.
:param condition: The VexValue representing the expression for the guard, or None for an unconditional jump
:param to_addr: The address to jump to.
:param jumpkind: The JumpKind to use. See the VEX docs for what these are; you only need them for things
aren't normal jumps (e.g., calls, interrupts, program exits, etc etc)
:return: None
"""
to_addr_ty = None
if isinstance(to_addr, VexValue):
# Unpack a VV
to_addr_rdt = to_addr.rdt
to_addr_ty = to_addr.ty
elif isinstance(to_addr, int):
# Direct jump to an int, make an RdT and Ty
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr = self.constant(to_addr, to_addr_ty) # TODO archinfo may be changing
to_addr_rdt = to_addr.rdt
elif isinstance(to_addr, RdTmp):
# An RdT; just get the Ty of the arch's pointer type
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr_rdt = to_addr
else:
raise ValueError("Jump destination has unknown type: " + repr(type(to_addr)))
if not condition:
# This is the default exit.
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt
else:
# add another exit
# EDG says: We should make sure folks set ArchXYZ.ip_offset like they're supposed to
if ip_offset is None:
ip_offset = self.arch.ip_offset
assert ip_offset is not None
negated_condition_rdt = self.ite(condition, self.constant(0, condition.ty), self.constant(1, condition.ty))
direct_exit_target = self.constant(self.addr + (self.bitwidth // 8), to_addr_ty)
self.irsb_c.add_exit(negated_condition_rdt, direct_exit_target.rdt, jumpkind, ip_offset)
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt | python | def jump(self, condition, to_addr, jumpkind=JumpKind.Boring, ip_offset=None):
"""
Jump to a specified destination, under the specified condition.
Used for branches, jumps, calls, returns, etc.
:param condition: The VexValue representing the expression for the guard, or None for an unconditional jump
:param to_addr: The address to jump to.
:param jumpkind: The JumpKind to use. See the VEX docs for what these are; you only need them for things
aren't normal jumps (e.g., calls, interrupts, program exits, etc etc)
:return: None
"""
to_addr_ty = None
if isinstance(to_addr, VexValue):
# Unpack a VV
to_addr_rdt = to_addr.rdt
to_addr_ty = to_addr.ty
elif isinstance(to_addr, int):
# Direct jump to an int, make an RdT and Ty
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr = self.constant(to_addr, to_addr_ty) # TODO archinfo may be changing
to_addr_rdt = to_addr.rdt
elif isinstance(to_addr, RdTmp):
# An RdT; just get the Ty of the arch's pointer type
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr_rdt = to_addr
else:
raise ValueError("Jump destination has unknown type: " + repr(type(to_addr)))
if not condition:
# This is the default exit.
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt
else:
# add another exit
# EDG says: We should make sure folks set ArchXYZ.ip_offset like they're supposed to
if ip_offset is None:
ip_offset = self.arch.ip_offset
assert ip_offset is not None
negated_condition_rdt = self.ite(condition, self.constant(0, condition.ty), self.constant(1, condition.ty))
direct_exit_target = self.constant(self.addr + (self.bitwidth // 8), to_addr_ty)
self.irsb_c.add_exit(negated_condition_rdt, direct_exit_target.rdt, jumpkind, ip_offset)
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt | [
"def",
"jump",
"(",
"self",
",",
"condition",
",",
"to_addr",
",",
"jumpkind",
"=",
"JumpKind",
".",
"Boring",
",",
"ip_offset",
"=",
"None",
")",
":",
"to_addr_ty",
"=",
"None",
"if",
"isinstance",
"(",
"to_addr",
",",
"VexValue",
")",
":",
"# Unpack a VV",
"to_addr_rdt",
"=",
"to_addr",
".",
"rdt",
"to_addr_ty",
"=",
"to_addr",
".",
"ty",
"elif",
"isinstance",
"(",
"to_addr",
",",
"int",
")",
":",
"# Direct jump to an int, make an RdT and Ty",
"to_addr_ty",
"=",
"vex_int_class",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
".",
"bits",
")",
".",
"type",
"to_addr",
"=",
"self",
".",
"constant",
"(",
"to_addr",
",",
"to_addr_ty",
")",
"# TODO archinfo may be changing",
"to_addr_rdt",
"=",
"to_addr",
".",
"rdt",
"elif",
"isinstance",
"(",
"to_addr",
",",
"RdTmp",
")",
":",
"# An RdT; just get the Ty of the arch's pointer type",
"to_addr_ty",
"=",
"vex_int_class",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
".",
"bits",
")",
".",
"type",
"to_addr_rdt",
"=",
"to_addr",
"else",
":",
"raise",
"ValueError",
"(",
"\"Jump destination has unknown type: \"",
"+",
"repr",
"(",
"type",
"(",
"to_addr",
")",
")",
")",
"if",
"not",
"condition",
":",
"# This is the default exit.",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"jumpkind",
"=",
"jumpkind",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"next",
"=",
"to_addr_rdt",
"else",
":",
"# add another exit",
"# EDG says: We should make sure folks set ArchXYZ.ip_offset like they're supposed to",
"if",
"ip_offset",
"is",
"None",
":",
"ip_offset",
"=",
"self",
".",
"arch",
".",
"ip_offset",
"assert",
"ip_offset",
"is",
"not",
"None",
"negated_condition_rdt",
"=",
"self",
".",
"ite",
"(",
"condition",
",",
"self",
".",
"constant",
"(",
"0",
",",
"condition",
".",
"ty",
")",
",",
"self",
".",
"constant",
"(",
"1",
",",
"condition",
".",
"ty",
")",
")",
"direct_exit_target",
"=",
"self",
".",
"constant",
"(",
"self",
".",
"addr",
"+",
"(",
"self",
".",
"bitwidth",
"//",
"8",
")",
",",
"to_addr_ty",
")",
"self",
".",
"irsb_c",
".",
"add_exit",
"(",
"negated_condition_rdt",
",",
"direct_exit_target",
".",
"rdt",
",",
"jumpkind",
",",
"ip_offset",
")",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"jumpkind",
"=",
"jumpkind",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"next",
"=",
"to_addr_rdt"
] | Jump to a specified destination, under the specified condition.
Used for branches, jumps, calls, returns, etc.
:param condition: The VexValue representing the expression for the guard, or None for an unconditional jump
:param to_addr: The address to jump to.
:param jumpkind: The JumpKind to use. See the VEX docs for what these are; you only need them for things
aren't normal jumps (e.g., calls, interrupts, program exits, etc etc)
:return: None | [
"Jump",
"to",
"a",
"specified",
"destination",
"under",
"the",
"specified",
"condition",
".",
"Used",
"for",
"branches",
"jumps",
"calls",
"returns",
"etc",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L295-L337 | train | 231,946 |
angr/pyvex | pyvex/lifting/__init__.py | register | def register(lifter, arch_name):
"""
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocessor`
"""
if issubclass(lifter, Lifter):
l.debug("Registering lifter %s for architecture %s.", lifter.__name__, arch_name)
lifters[arch_name].append(lifter)
if issubclass(lifter, Postprocessor):
l.debug("Registering postprocessor %s for architecture %s.", lifter.__name__, arch_name)
postprocessors[arch_name].append(lifter) | python | def register(lifter, arch_name):
"""
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocessor`
"""
if issubclass(lifter, Lifter):
l.debug("Registering lifter %s for architecture %s.", lifter.__name__, arch_name)
lifters[arch_name].append(lifter)
if issubclass(lifter, Postprocessor):
l.debug("Registering postprocessor %s for architecture %s.", lifter.__name__, arch_name)
postprocessors[arch_name].append(lifter) | [
"def",
"register",
"(",
"lifter",
",",
"arch_name",
")",
":",
"if",
"issubclass",
"(",
"lifter",
",",
"Lifter",
")",
":",
"l",
".",
"debug",
"(",
"\"Registering lifter %s for architecture %s.\"",
",",
"lifter",
".",
"__name__",
",",
"arch_name",
")",
"lifters",
"[",
"arch_name",
"]",
".",
"append",
"(",
"lifter",
")",
"if",
"issubclass",
"(",
"lifter",
",",
"Postprocessor",
")",
":",
"l",
".",
"debug",
"(",
"\"Registering postprocessor %s for architecture %s.\"",
",",
"lifter",
".",
"__name__",
",",
"arch_name",
")",
"postprocessors",
"[",
"arch_name",
"]",
".",
"append",
"(",
"lifter",
")"
] | Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocessor` | [
"Registers",
"a",
"Lifter",
"or",
"Postprocessor",
"to",
"be",
"used",
"by",
"pyvex",
".",
"Lifters",
"are",
"are",
"given",
"priority",
"based",
"on",
"the",
"order",
"in",
"which",
"they",
"are",
"registered",
".",
"Postprocessors",
"will",
"be",
"run",
"in",
"registration",
"order",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/__init__.py#L216-L229 | train | 231,947 |
angr/pyvex | pyvex/expr.py | IRExpr.child_expressions | def child_expressions(self):
"""
A list of all of the expressions that this expression ends up evaluating.
"""
expressions = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
expressions.append(v)
expressions.extend(v.child_expressions)
return expressions | python | def child_expressions(self):
"""
A list of all of the expressions that this expression ends up evaluating.
"""
expressions = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
expressions.append(v)
expressions.extend(v.child_expressions)
return expressions | [
"def",
"child_expressions",
"(",
"self",
")",
":",
"expressions",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"__slots__",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"if",
"isinstance",
"(",
"v",
",",
"IRExpr",
")",
":",
"expressions",
".",
"append",
"(",
"v",
")",
"expressions",
".",
"extend",
"(",
"v",
".",
"child_expressions",
")",
"return",
"expressions"
] | A list of all of the expressions that this expression ends up evaluating. | [
"A",
"list",
"of",
"all",
"of",
"the",
"expressions",
"that",
"this",
"expression",
"ends",
"up",
"evaluating",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/expr.py#L26-L36 | train | 231,948 |
angr/pyvex | pyvex/expr.py | IRExpr.constants | def constants(self):
"""
A list of all of the constants that this expression ends up using.
"""
constants = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
constants.extend(v.constants)
elif isinstance(v, IRConst):
constants.append(v)
return constants | python | def constants(self):
"""
A list of all of the constants that this expression ends up using.
"""
constants = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
constants.extend(v.constants)
elif isinstance(v, IRConst):
constants.append(v)
return constants | [
"def",
"constants",
"(",
"self",
")",
":",
"constants",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"__slots__",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"if",
"isinstance",
"(",
"v",
",",
"IRExpr",
")",
":",
"constants",
".",
"extend",
"(",
"v",
".",
"constants",
")",
"elif",
"isinstance",
"(",
"v",
",",
"IRConst",
")",
":",
"constants",
".",
"append",
"(",
"v",
")",
"return",
"constants"
] | A list of all of the constants that this expression ends up using. | [
"A",
"list",
"of",
"all",
"of",
"the",
"constants",
"that",
"this",
"expression",
"ends",
"up",
"using",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/expr.py#L39-L50 | train | 231,949 |
angr/pyvex | pyvex/block.py | IRSB.expressions | def expressions(self):
"""
Return an iterator of all expressions contained in the IRSB.
"""
for s in self.statements:
for expr_ in s.expressions:
yield expr_
yield self.next | python | def expressions(self):
"""
Return an iterator of all expressions contained in the IRSB.
"""
for s in self.statements:
for expr_ in s.expressions:
yield expr_
yield self.next | [
"def",
"expressions",
"(",
"self",
")",
":",
"for",
"s",
"in",
"self",
".",
"statements",
":",
"for",
"expr_",
"in",
"s",
".",
"expressions",
":",
"yield",
"expr_",
"yield",
"self",
".",
"next"
] | Return an iterator of all expressions contained in the IRSB. | [
"Return",
"an",
"iterator",
"of",
"all",
"expressions",
"contained",
"in",
"the",
"IRSB",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L338-L345 | train | 231,950 |
angr/pyvex | pyvex/block.py | IRSB.instructions | def instructions(self):
"""
The number of instructions in this block
"""
if self._instructions is None:
if self.statements is None:
self._instructions = 0
else:
self._instructions = len([s for s in self.statements if type(s) is stmt.IMark])
return self._instructions | python | def instructions(self):
"""
The number of instructions in this block
"""
if self._instructions is None:
if self.statements is None:
self._instructions = 0
else:
self._instructions = len([s for s in self.statements if type(s) is stmt.IMark])
return self._instructions | [
"def",
"instructions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instructions",
"is",
"None",
":",
"if",
"self",
".",
"statements",
"is",
"None",
":",
"self",
".",
"_instructions",
"=",
"0",
"else",
":",
"self",
".",
"_instructions",
"=",
"len",
"(",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"statements",
"if",
"type",
"(",
"s",
")",
"is",
"stmt",
".",
"IMark",
"]",
")",
"return",
"self",
".",
"_instructions"
] | The number of instructions in this block | [
"The",
"number",
"of",
"instructions",
"in",
"this",
"block"
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L348-L357 | train | 231,951 |
angr/pyvex | pyvex/block.py | IRSB.instruction_addresses | def instruction_addresses(self):
"""
Addresses of instructions in this block.
"""
if self._instruction_addresses is None:
if self.statements is None:
self._instruction_addresses = [ ]
else:
self._instruction_addresses = [ (s.addr + s.delta) for s in self.statements if type(s) is stmt.IMark ]
return self._instruction_addresses | python | def instruction_addresses(self):
"""
Addresses of instructions in this block.
"""
if self._instruction_addresses is None:
if self.statements is None:
self._instruction_addresses = [ ]
else:
self._instruction_addresses = [ (s.addr + s.delta) for s in self.statements if type(s) is stmt.IMark ]
return self._instruction_addresses | [
"def",
"instruction_addresses",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instruction_addresses",
"is",
"None",
":",
"if",
"self",
".",
"statements",
"is",
"None",
":",
"self",
".",
"_instruction_addresses",
"=",
"[",
"]",
"else",
":",
"self",
".",
"_instruction_addresses",
"=",
"[",
"(",
"s",
".",
"addr",
"+",
"s",
".",
"delta",
")",
"for",
"s",
"in",
"self",
".",
"statements",
"if",
"type",
"(",
"s",
")",
"is",
"stmt",
".",
"IMark",
"]",
"return",
"self",
".",
"_instruction_addresses"
] | Addresses of instructions in this block. | [
"Addresses",
"of",
"instructions",
"in",
"this",
"block",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L360-L369 | train | 231,952 |
angr/pyvex | pyvex/block.py | IRSB.size | def size(self):
"""
The size of this block, in bytes
"""
if self._size is None:
self._size = sum(s.len for s in self.statements if type(s) is stmt.IMark)
return self._size | python | def size(self):
"""
The size of this block, in bytes
"""
if self._size is None:
self._size = sum(s.len for s in self.statements if type(s) is stmt.IMark)
return self._size | [
"def",
"size",
"(",
"self",
")",
":",
"if",
"self",
".",
"_size",
"is",
"None",
":",
"self",
".",
"_size",
"=",
"sum",
"(",
"s",
".",
"len",
"for",
"s",
"in",
"self",
".",
"statements",
"if",
"type",
"(",
"s",
")",
"is",
"stmt",
".",
"IMark",
")",
"return",
"self",
".",
"_size"
] | The size of this block, in bytes | [
"The",
"size",
"of",
"this",
"block",
"in",
"bytes"
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L372-L378 | train | 231,953 |
angr/pyvex | pyvex/block.py | IRSB.operations | def operations(self):
"""
A list of all operations done by the IRSB, as libVEX enum names
"""
ops = []
for e in self.expressions:
if hasattr(e, 'op'):
ops.append(e.op)
return ops | python | def operations(self):
"""
A list of all operations done by the IRSB, as libVEX enum names
"""
ops = []
for e in self.expressions:
if hasattr(e, 'op'):
ops.append(e.op)
return ops | [
"def",
"operations",
"(",
"self",
")",
":",
"ops",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"expressions",
":",
"if",
"hasattr",
"(",
"e",
",",
"'op'",
")",
":",
"ops",
".",
"append",
"(",
"e",
".",
"op",
")",
"return",
"ops"
] | A list of all operations done by the IRSB, as libVEX enum names | [
"A",
"list",
"of",
"all",
"operations",
"done",
"by",
"the",
"IRSB",
"as",
"libVEX",
"enum",
"names"
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L381-L389 | train | 231,954 |
angr/pyvex | pyvex/block.py | IRSB.constant_jump_targets | def constant_jump_targets(self):
"""
A set of the static jump targets of the basic block.
"""
exits = set()
if self.exit_statements:
for _, _, stmt_ in self.exit_statements:
exits.add(stmt_.dst.value)
default_target = self.default_exit_target
if default_target is not None:
exits.add(default_target)
return exits | python | def constant_jump_targets(self):
"""
A set of the static jump targets of the basic block.
"""
exits = set()
if self.exit_statements:
for _, _, stmt_ in self.exit_statements:
exits.add(stmt_.dst.value)
default_target = self.default_exit_target
if default_target is not None:
exits.add(default_target)
return exits | [
"def",
"constant_jump_targets",
"(",
"self",
")",
":",
"exits",
"=",
"set",
"(",
")",
"if",
"self",
".",
"exit_statements",
":",
"for",
"_",
",",
"_",
",",
"stmt_",
"in",
"self",
".",
"exit_statements",
":",
"exits",
".",
"add",
"(",
"stmt_",
".",
"dst",
".",
"value",
")",
"default_target",
"=",
"self",
".",
"default_exit_target",
"if",
"default_target",
"is",
"not",
"None",
":",
"exits",
".",
"add",
"(",
"default_target",
")",
"return",
"exits"
] | A set of the static jump targets of the basic block. | [
"A",
"set",
"of",
"the",
"static",
"jump",
"targets",
"of",
"the",
"basic",
"block",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L407-L421 | train | 231,955 |
angr/pyvex | pyvex/block.py | IRSB.constant_jump_targets_and_jumpkinds | def constant_jump_targets_and_jumpkinds(self):
"""
A dict of the static jump targets of the basic block to their jumpkind.
"""
exits = dict()
if self.exit_statements:
for _, _, stmt_ in self.exit_statements:
exits[stmt_.dst.value] = stmt_.jumpkind
default_target = self.default_exit_target
if default_target is not None:
exits[default_target] = self.jumpkind
return exits | python | def constant_jump_targets_and_jumpkinds(self):
"""
A dict of the static jump targets of the basic block to their jumpkind.
"""
exits = dict()
if self.exit_statements:
for _, _, stmt_ in self.exit_statements:
exits[stmt_.dst.value] = stmt_.jumpkind
default_target = self.default_exit_target
if default_target is not None:
exits[default_target] = self.jumpkind
return exits | [
"def",
"constant_jump_targets_and_jumpkinds",
"(",
"self",
")",
":",
"exits",
"=",
"dict",
"(",
")",
"if",
"self",
".",
"exit_statements",
":",
"for",
"_",
",",
"_",
",",
"stmt_",
"in",
"self",
".",
"exit_statements",
":",
"exits",
"[",
"stmt_",
".",
"dst",
".",
"value",
"]",
"=",
"stmt_",
".",
"jumpkind",
"default_target",
"=",
"self",
".",
"default_exit_target",
"if",
"default_target",
"is",
"not",
"None",
":",
"exits",
"[",
"default_target",
"]",
"=",
"self",
".",
"jumpkind",
"return",
"exits"
] | A dict of the static jump targets of the basic block to their jumpkind. | [
"A",
"dict",
"of",
"the",
"static",
"jump",
"targets",
"of",
"the",
"basic",
"block",
"to",
"their",
"jumpkind",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L424-L438 | train | 231,956 |
angr/pyvex | pyvex/block.py | IRSB._pp_str | def _pp_str(self):
"""
Return the pretty-printed IRSB.
:rtype: str
"""
sa = []
sa.append("IRSB {")
if self.statements is not None:
sa.append(" %s" % self.tyenv)
sa.append("")
if self.statements is not None:
for i, s in enumerate(self.statements):
if isinstance(s, stmt.Put):
stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.offset, s.data.result_size(self.tyenv) // 8))
elif isinstance(s, stmt.WrTmp) and isinstance(s.data, expr.Get):
stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.data.offset, s.data.result_size(self.tyenv) // 8))
elif isinstance(s, stmt.Exit):
stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.offsIP, self.arch.bits // 8))
else:
stmt_str = s.__str__()
sa.append(" %02d | %s" % (i, stmt_str))
else:
sa.append(" Statements are omitted.")
sa.append(
" NEXT: PUT(%s) = %s; %s" % (self.arch.translate_register_name(self.offsIP), self.next, self.jumpkind))
sa.append("}")
return '\n'.join(sa) | python | def _pp_str(self):
"""
Return the pretty-printed IRSB.
:rtype: str
"""
sa = []
sa.append("IRSB {")
if self.statements is not None:
sa.append(" %s" % self.tyenv)
sa.append("")
if self.statements is not None:
for i, s in enumerate(self.statements):
if isinstance(s, stmt.Put):
stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.offset, s.data.result_size(self.tyenv) // 8))
elif isinstance(s, stmt.WrTmp) and isinstance(s.data, expr.Get):
stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.data.offset, s.data.result_size(self.tyenv) // 8))
elif isinstance(s, stmt.Exit):
stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.offsIP, self.arch.bits // 8))
else:
stmt_str = s.__str__()
sa.append(" %02d | %s" % (i, stmt_str))
else:
sa.append(" Statements are omitted.")
sa.append(
" NEXT: PUT(%s) = %s; %s" % (self.arch.translate_register_name(self.offsIP), self.next, self.jumpkind))
sa.append("}")
return '\n'.join(sa) | [
"def",
"_pp_str",
"(",
"self",
")",
":",
"sa",
"=",
"[",
"]",
"sa",
".",
"append",
"(",
"\"IRSB {\"",
")",
"if",
"self",
".",
"statements",
"is",
"not",
"None",
":",
"sa",
".",
"append",
"(",
"\" %s\"",
"%",
"self",
".",
"tyenv",
")",
"sa",
".",
"append",
"(",
"\"\"",
")",
"if",
"self",
".",
"statements",
"is",
"not",
"None",
":",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"self",
".",
"statements",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"stmt",
".",
"Put",
")",
":",
"stmt_str",
"=",
"s",
".",
"__str__",
"(",
"reg_name",
"=",
"self",
".",
"arch",
".",
"translate_register_name",
"(",
"s",
".",
"offset",
",",
"s",
".",
"data",
".",
"result_size",
"(",
"self",
".",
"tyenv",
")",
"//",
"8",
")",
")",
"elif",
"isinstance",
"(",
"s",
",",
"stmt",
".",
"WrTmp",
")",
"and",
"isinstance",
"(",
"s",
".",
"data",
",",
"expr",
".",
"Get",
")",
":",
"stmt_str",
"=",
"s",
".",
"__str__",
"(",
"reg_name",
"=",
"self",
".",
"arch",
".",
"translate_register_name",
"(",
"s",
".",
"data",
".",
"offset",
",",
"s",
".",
"data",
".",
"result_size",
"(",
"self",
".",
"tyenv",
")",
"//",
"8",
")",
")",
"elif",
"isinstance",
"(",
"s",
",",
"stmt",
".",
"Exit",
")",
":",
"stmt_str",
"=",
"s",
".",
"__str__",
"(",
"reg_name",
"=",
"self",
".",
"arch",
".",
"translate_register_name",
"(",
"s",
".",
"offsIP",
",",
"self",
".",
"arch",
".",
"bits",
"//",
"8",
")",
")",
"else",
":",
"stmt_str",
"=",
"s",
".",
"__str__",
"(",
")",
"sa",
".",
"append",
"(",
"\" %02d | %s\"",
"%",
"(",
"i",
",",
"stmt_str",
")",
")",
"else",
":",
"sa",
".",
"append",
"(",
"\" Statements are omitted.\"",
")",
"sa",
".",
"append",
"(",
"\" NEXT: PUT(%s) = %s; %s\"",
"%",
"(",
"self",
".",
"arch",
".",
"translate_register_name",
"(",
"self",
".",
"offsIP",
")",
",",
"self",
".",
"next",
",",
"self",
".",
"jumpkind",
")",
")",
"sa",
".",
"append",
"(",
"\"}\"",
")",
"return",
"'\\n'",
".",
"join",
"(",
"sa",
")"
] | Return the pretty-printed IRSB.
:rtype: str | [
"Return",
"the",
"pretty",
"-",
"printed",
"IRSB",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L444-L471 | train | 231,957 |
angr/pyvex | pyvex/block.py | IRSB._is_defaultexit_direct_jump | def _is_defaultexit_direct_jump(self):
"""
Checks if the default of this IRSB a direct jump or not.
"""
if not (self.jumpkind == 'Ijk_InvalICache' or self.jumpkind == 'Ijk_Boring' or self.jumpkind == 'Ijk_Call'):
return False
target = self.default_exit_target
return target is not None | python | def _is_defaultexit_direct_jump(self):
"""
Checks if the default of this IRSB a direct jump or not.
"""
if not (self.jumpkind == 'Ijk_InvalICache' or self.jumpkind == 'Ijk_Boring' or self.jumpkind == 'Ijk_Call'):
return False
target = self.default_exit_target
return target is not None | [
"def",
"_is_defaultexit_direct_jump",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"jumpkind",
"==",
"'Ijk_InvalICache'",
"or",
"self",
".",
"jumpkind",
"==",
"'Ijk_Boring'",
"or",
"self",
".",
"jumpkind",
"==",
"'Ijk_Call'",
")",
":",
"return",
"False",
"target",
"=",
"self",
".",
"default_exit_target",
"return",
"target",
"is",
"not",
"None"
] | Checks if the default of this IRSB a direct jump or not. | [
"Checks",
"if",
"the",
"default",
"of",
"this",
"IRSB",
"a",
"direct",
"jump",
"or",
"not",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L473-L481 | train | 231,958 |
angr/pyvex | pyvex/block.py | IRTypeEnv.lookup | def lookup(self, tmp):
"""
Return the type of temporary variable `tmp` as an enum string
"""
if tmp < 0 or tmp > self.types_used:
l.debug("Invalid temporary number %d", tmp)
raise IndexError(tmp)
return self.types[tmp] | python | def lookup(self, tmp):
"""
Return the type of temporary variable `tmp` as an enum string
"""
if tmp < 0 or tmp > self.types_used:
l.debug("Invalid temporary number %d", tmp)
raise IndexError(tmp)
return self.types[tmp] | [
"def",
"lookup",
"(",
"self",
",",
"tmp",
")",
":",
"if",
"tmp",
"<",
"0",
"or",
"tmp",
">",
"self",
".",
"types_used",
":",
"l",
".",
"debug",
"(",
"\"Invalid temporary number %d\"",
",",
"tmp",
")",
"raise",
"IndexError",
"(",
"tmp",
")",
"return",
"self",
".",
"types",
"[",
"tmp",
"]"
] | Return the type of temporary variable `tmp` as an enum string | [
"Return",
"the",
"type",
"of",
"temporary",
"variable",
"tmp",
"as",
"an",
"enum",
"string"
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L568-L575 | train | 231,959 |
angr/pyvex | pyvex/lifting/lifter.py | Lifter._lift | def _lift(self,
data,
bytes_offset=None,
max_bytes=None,
max_inst=None,
opt_level=1,
traceflags=None,
allow_arch_optimizations=None,
strict_block_end=None,
skip_stmts=False,
collect_data_refs=False):
"""
Wrapper around the `lift` method on Lifters. Should not be overridden in child classes.
:param data: The bytes to lift as either a python string of bytes or a cffi buffer object.
:param bytes_offset: The offset into `data` to start lifting at.
:param max_bytes: The maximum number of bytes to lift. If set to None, no byte limit is used.
:param max_inst: The maximum number of instructions to lift. If set to None, no instruction limit is used.
:param opt_level: The level of optimization to apply to the IR, 0-2. Most likely will be ignored in any lifter
other then LibVEX.
:param traceflags: The libVEX traceflags, controlling VEX debug prints. Most likely will be ignored in any
lifter other than LibVEX.
:param allow_arch_optimizations: Should the LibVEX lifter be allowed to perform lift-time preprocessing optimizations
(e.g., lookback ITSTATE optimization on THUMB)
Most likely will be ignored in any lifter other than LibVEX.
:param strict_block_end: Should the LibVEX arm-thumb split block at some instructions, for example CB{N}Z.
:param skip_stmts: Should the lifter skip transferring IRStmts from C to Python.
:param collect_data_refs: Should the LibVEX lifter collect data references in C.
"""
irsb = IRSB.empty_block(self.arch, self.addr)
self.data = data
self.bytes_offset = bytes_offset
self.opt_level = opt_level
self.traceflags = traceflags
self.allow_arch_optimizations = allow_arch_optimizations
self.strict_block_end = strict_block_end
self.collect_data_refs = collect_data_refs
self.max_inst = max_inst
self.max_bytes = max_bytes
self.skip_stmts = skip_stmts
self.irsb = irsb
self.lift()
return self.irsb | python | def _lift(self,
data,
bytes_offset=None,
max_bytes=None,
max_inst=None,
opt_level=1,
traceflags=None,
allow_arch_optimizations=None,
strict_block_end=None,
skip_stmts=False,
collect_data_refs=False):
"""
Wrapper around the `lift` method on Lifters. Should not be overridden in child classes.
:param data: The bytes to lift as either a python string of bytes or a cffi buffer object.
:param bytes_offset: The offset into `data` to start lifting at.
:param max_bytes: The maximum number of bytes to lift. If set to None, no byte limit is used.
:param max_inst: The maximum number of instructions to lift. If set to None, no instruction limit is used.
:param opt_level: The level of optimization to apply to the IR, 0-2. Most likely will be ignored in any lifter
other then LibVEX.
:param traceflags: The libVEX traceflags, controlling VEX debug prints. Most likely will be ignored in any
lifter other than LibVEX.
:param allow_arch_optimizations: Should the LibVEX lifter be allowed to perform lift-time preprocessing optimizations
(e.g., lookback ITSTATE optimization on THUMB)
Most likely will be ignored in any lifter other than LibVEX.
:param strict_block_end: Should the LibVEX arm-thumb split block at some instructions, for example CB{N}Z.
:param skip_stmts: Should the lifter skip transferring IRStmts from C to Python.
:param collect_data_refs: Should the LibVEX lifter collect data references in C.
"""
irsb = IRSB.empty_block(self.arch, self.addr)
self.data = data
self.bytes_offset = bytes_offset
self.opt_level = opt_level
self.traceflags = traceflags
self.allow_arch_optimizations = allow_arch_optimizations
self.strict_block_end = strict_block_end
self.collect_data_refs = collect_data_refs
self.max_inst = max_inst
self.max_bytes = max_bytes
self.skip_stmts = skip_stmts
self.irsb = irsb
self.lift()
return self.irsb | [
"def",
"_lift",
"(",
"self",
",",
"data",
",",
"bytes_offset",
"=",
"None",
",",
"max_bytes",
"=",
"None",
",",
"max_inst",
"=",
"None",
",",
"opt_level",
"=",
"1",
",",
"traceflags",
"=",
"None",
",",
"allow_arch_optimizations",
"=",
"None",
",",
"strict_block_end",
"=",
"None",
",",
"skip_stmts",
"=",
"False",
",",
"collect_data_refs",
"=",
"False",
")",
":",
"irsb",
"=",
"IRSB",
".",
"empty_block",
"(",
"self",
".",
"arch",
",",
"self",
".",
"addr",
")",
"self",
".",
"data",
"=",
"data",
"self",
".",
"bytes_offset",
"=",
"bytes_offset",
"self",
".",
"opt_level",
"=",
"opt_level",
"self",
".",
"traceflags",
"=",
"traceflags",
"self",
".",
"allow_arch_optimizations",
"=",
"allow_arch_optimizations",
"self",
".",
"strict_block_end",
"=",
"strict_block_end",
"self",
".",
"collect_data_refs",
"=",
"collect_data_refs",
"self",
".",
"max_inst",
"=",
"max_inst",
"self",
".",
"max_bytes",
"=",
"max_bytes",
"self",
".",
"skip_stmts",
"=",
"skip_stmts",
"self",
".",
"irsb",
"=",
"irsb",
"self",
".",
"lift",
"(",
")",
"return",
"self",
".",
"irsb"
] | Wrapper around the `lift` method on Lifters. Should not be overridden in child classes.
:param data: The bytes to lift as either a python string of bytes or a cffi buffer object.
:param bytes_offset: The offset into `data` to start lifting at.
:param max_bytes: The maximum number of bytes to lift. If set to None, no byte limit is used.
:param max_inst: The maximum number of instructions to lift. If set to None, no instruction limit is used.
:param opt_level: The level of optimization to apply to the IR, 0-2. Most likely will be ignored in any lifter
other then LibVEX.
:param traceflags: The libVEX traceflags, controlling VEX debug prints. Most likely will be ignored in any
lifter other than LibVEX.
:param allow_arch_optimizations: Should the LibVEX lifter be allowed to perform lift-time preprocessing optimizations
(e.g., lookback ITSTATE optimization on THUMB)
Most likely will be ignored in any lifter other than LibVEX.
:param strict_block_end: Should the LibVEX arm-thumb split block at some instructions, for example CB{N}Z.
:param skip_stmts: Should the lifter skip transferring IRStmts from C to Python.
:param collect_data_refs: Should the LibVEX lifter collect data references in C. | [
"Wrapper",
"around",
"the",
"lift",
"method",
"on",
"Lifters",
".",
"Should",
"not",
"be",
"overridden",
"in",
"child",
"classes",
"."
] | c418edc1146982b2a0579bf56e5993c1c7046b19 | https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/lifter.py#L36-L78 | train | 231,960 |
TeamHG-Memex/scrapy-rotating-proxies | rotating_proxies/expire.py | exp_backoff | def exp_backoff(attempt, cap=3600, base=300):
""" Exponential backoff time """
# this is a numerically stable version of
# min(cap, base * 2 ** attempt)
max_attempts = math.log(cap / base, 2)
if attempt <= max_attempts:
return base * 2 ** attempt
return cap | python | def exp_backoff(attempt, cap=3600, base=300):
""" Exponential backoff time """
# this is a numerically stable version of
# min(cap, base * 2 ** attempt)
max_attempts = math.log(cap / base, 2)
if attempt <= max_attempts:
return base * 2 ** attempt
return cap | [
"def",
"exp_backoff",
"(",
"attempt",
",",
"cap",
"=",
"3600",
",",
"base",
"=",
"300",
")",
":",
"# this is a numerically stable version of",
"# min(cap, base * 2 ** attempt)",
"max_attempts",
"=",
"math",
".",
"log",
"(",
"cap",
"/",
"base",
",",
"2",
")",
"if",
"attempt",
"<=",
"max_attempts",
":",
"return",
"base",
"*",
"2",
"**",
"attempt",
"return",
"cap"
] | Exponential backoff time | [
"Exponential",
"backoff",
"time"
] | 89bb677fea6285a5e02e0a5c7dfb1c40330b17f0 | https://github.com/TeamHG-Memex/scrapy-rotating-proxies/blob/89bb677fea6285a5e02e0a5c7dfb1c40330b17f0/rotating_proxies/expire.py#L149-L156 | train | 231,961 |
TeamHG-Memex/scrapy-rotating-proxies | rotating_proxies/expire.py | Proxies.get_proxy | def get_proxy(self, proxy_address):
"""
Return complete proxy name associated with a hostport of a given
``proxy_address``. If ``proxy_address`` is unkonwn or empty,
return None.
"""
if not proxy_address:
return None
hostport = extract_proxy_hostport(proxy_address)
return self.proxies_by_hostport.get(hostport, None) | python | def get_proxy(self, proxy_address):
"""
Return complete proxy name associated with a hostport of a given
``proxy_address``. If ``proxy_address`` is unkonwn or empty,
return None.
"""
if not proxy_address:
return None
hostport = extract_proxy_hostport(proxy_address)
return self.proxies_by_hostport.get(hostport, None) | [
"def",
"get_proxy",
"(",
"self",
",",
"proxy_address",
")",
":",
"if",
"not",
"proxy_address",
":",
"return",
"None",
"hostport",
"=",
"extract_proxy_hostport",
"(",
"proxy_address",
")",
"return",
"self",
".",
"proxies_by_hostport",
".",
"get",
"(",
"hostport",
",",
"None",
")"
] | Return complete proxy name associated with a hostport of a given
``proxy_address``. If ``proxy_address`` is unkonwn or empty,
return None. | [
"Return",
"complete",
"proxy",
"name",
"associated",
"with",
"a",
"hostport",
"of",
"a",
"given",
"proxy_address",
".",
"If",
"proxy_address",
"is",
"unkonwn",
"or",
"empty",
"return",
"None",
"."
] | 89bb677fea6285a5e02e0a5c7dfb1c40330b17f0 | https://github.com/TeamHG-Memex/scrapy-rotating-proxies/blob/89bb677fea6285a5e02e0a5c7dfb1c40330b17f0/rotating_proxies/expire.py#L56-L65 | train | 231,962 |
TeamHG-Memex/scrapy-rotating-proxies | rotating_proxies/expire.py | Proxies.mark_dead | def mark_dead(self, proxy, _time=None):
""" Mark a proxy as dead """
if proxy not in self.proxies:
logger.warn("Proxy <%s> was not found in proxies list" % proxy)
return
if proxy in self.good:
logger.debug("GOOD proxy became DEAD: <%s>" % proxy)
else:
logger.debug("Proxy <%s> is DEAD" % proxy)
self.unchecked.discard(proxy)
self.good.discard(proxy)
self.dead.add(proxy)
now = _time or time.time()
state = self.proxies[proxy]
state.backoff_time = self.backoff(state.failed_attempts)
state.next_check = now + state.backoff_time
state.failed_attempts += 1 | python | def mark_dead(self, proxy, _time=None):
""" Mark a proxy as dead """
if proxy not in self.proxies:
logger.warn("Proxy <%s> was not found in proxies list" % proxy)
return
if proxy in self.good:
logger.debug("GOOD proxy became DEAD: <%s>" % proxy)
else:
logger.debug("Proxy <%s> is DEAD" % proxy)
self.unchecked.discard(proxy)
self.good.discard(proxy)
self.dead.add(proxy)
now = _time or time.time()
state = self.proxies[proxy]
state.backoff_time = self.backoff(state.failed_attempts)
state.next_check = now + state.backoff_time
state.failed_attempts += 1 | [
"def",
"mark_dead",
"(",
"self",
",",
"proxy",
",",
"_time",
"=",
"None",
")",
":",
"if",
"proxy",
"not",
"in",
"self",
".",
"proxies",
":",
"logger",
".",
"warn",
"(",
"\"Proxy <%s> was not found in proxies list\"",
"%",
"proxy",
")",
"return",
"if",
"proxy",
"in",
"self",
".",
"good",
":",
"logger",
".",
"debug",
"(",
"\"GOOD proxy became DEAD: <%s>\"",
"%",
"proxy",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Proxy <%s> is DEAD\"",
"%",
"proxy",
")",
"self",
".",
"unchecked",
".",
"discard",
"(",
"proxy",
")",
"self",
".",
"good",
".",
"discard",
"(",
"proxy",
")",
"self",
".",
"dead",
".",
"add",
"(",
"proxy",
")",
"now",
"=",
"_time",
"or",
"time",
".",
"time",
"(",
")",
"state",
"=",
"self",
".",
"proxies",
"[",
"proxy",
"]",
"state",
".",
"backoff_time",
"=",
"self",
".",
"backoff",
"(",
"state",
".",
"failed_attempts",
")",
"state",
".",
"next_check",
"=",
"now",
"+",
"state",
".",
"backoff_time",
"state",
".",
"failed_attempts",
"+=",
"1"
] | Mark a proxy as dead | [
"Mark",
"a",
"proxy",
"as",
"dead"
] | 89bb677fea6285a5e02e0a5c7dfb1c40330b17f0 | https://github.com/TeamHG-Memex/scrapy-rotating-proxies/blob/89bb677fea6285a5e02e0a5c7dfb1c40330b17f0/rotating_proxies/expire.py#L67-L86 | train | 231,963 |
TeamHG-Memex/scrapy-rotating-proxies | rotating_proxies/expire.py | Proxies.mark_good | def mark_good(self, proxy):
""" Mark a proxy as good """
if proxy not in self.proxies:
logger.warn("Proxy <%s> was not found in proxies list" % proxy)
return
if proxy not in self.good:
logger.debug("Proxy <%s> is GOOD" % proxy)
self.unchecked.discard(proxy)
self.dead.discard(proxy)
self.good.add(proxy)
self.proxies[proxy].failed_attempts = 0 | python | def mark_good(self, proxy):
""" Mark a proxy as good """
if proxy not in self.proxies:
logger.warn("Proxy <%s> was not found in proxies list" % proxy)
return
if proxy not in self.good:
logger.debug("Proxy <%s> is GOOD" % proxy)
self.unchecked.discard(proxy)
self.dead.discard(proxy)
self.good.add(proxy)
self.proxies[proxy].failed_attempts = 0 | [
"def",
"mark_good",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"proxy",
"not",
"in",
"self",
".",
"proxies",
":",
"logger",
".",
"warn",
"(",
"\"Proxy <%s> was not found in proxies list\"",
"%",
"proxy",
")",
"return",
"if",
"proxy",
"not",
"in",
"self",
".",
"good",
":",
"logger",
".",
"debug",
"(",
"\"Proxy <%s> is GOOD\"",
"%",
"proxy",
")",
"self",
".",
"unchecked",
".",
"discard",
"(",
"proxy",
")",
"self",
".",
"dead",
".",
"discard",
"(",
"proxy",
")",
"self",
".",
"good",
".",
"add",
"(",
"proxy",
")",
"self",
".",
"proxies",
"[",
"proxy",
"]",
".",
"failed_attempts",
"=",
"0"
] | Mark a proxy as good | [
"Mark",
"a",
"proxy",
"as",
"good"
] | 89bb677fea6285a5e02e0a5c7dfb1c40330b17f0 | https://github.com/TeamHG-Memex/scrapy-rotating-proxies/blob/89bb677fea6285a5e02e0a5c7dfb1c40330b17f0/rotating_proxies/expire.py#L88-L100 | train | 231,964 |
TeamHG-Memex/scrapy-rotating-proxies | rotating_proxies/expire.py | Proxies.reanimate | def reanimate(self, _time=None):
""" Move dead proxies to unchecked if a backoff timeout passes """
n_reanimated = 0
now = _time or time.time()
for proxy in list(self.dead):
state = self.proxies[proxy]
assert state.next_check is not None
if state.next_check <= now:
self.dead.remove(proxy)
self.unchecked.add(proxy)
n_reanimated += 1
return n_reanimated | python | def reanimate(self, _time=None):
""" Move dead proxies to unchecked if a backoff timeout passes """
n_reanimated = 0
now = _time or time.time()
for proxy in list(self.dead):
state = self.proxies[proxy]
assert state.next_check is not None
if state.next_check <= now:
self.dead.remove(proxy)
self.unchecked.add(proxy)
n_reanimated += 1
return n_reanimated | [
"def",
"reanimate",
"(",
"self",
",",
"_time",
"=",
"None",
")",
":",
"n_reanimated",
"=",
"0",
"now",
"=",
"_time",
"or",
"time",
".",
"time",
"(",
")",
"for",
"proxy",
"in",
"list",
"(",
"self",
".",
"dead",
")",
":",
"state",
"=",
"self",
".",
"proxies",
"[",
"proxy",
"]",
"assert",
"state",
".",
"next_check",
"is",
"not",
"None",
"if",
"state",
".",
"next_check",
"<=",
"now",
":",
"self",
".",
"dead",
".",
"remove",
"(",
"proxy",
")",
"self",
".",
"unchecked",
".",
"add",
"(",
"proxy",
")",
"n_reanimated",
"+=",
"1",
"return",
"n_reanimated"
] | Move dead proxies to unchecked if a backoff timeout passes | [
"Move",
"dead",
"proxies",
"to",
"unchecked",
"if",
"a",
"backoff",
"timeout",
"passes"
] | 89bb677fea6285a5e02e0a5c7dfb1c40330b17f0 | https://github.com/TeamHG-Memex/scrapy-rotating-proxies/blob/89bb677fea6285a5e02e0a5c7dfb1c40330b17f0/rotating_proxies/expire.py#L102-L113 | train | 231,965 |
TeamHG-Memex/scrapy-rotating-proxies | rotating_proxies/expire.py | Proxies.reset | def reset(self):
""" Mark all dead proxies as unchecked """
for proxy in list(self.dead):
self.dead.remove(proxy)
self.unchecked.add(proxy) | python | def reset(self):
""" Mark all dead proxies as unchecked """
for proxy in list(self.dead):
self.dead.remove(proxy)
self.unchecked.add(proxy) | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"proxy",
"in",
"list",
"(",
"self",
".",
"dead",
")",
":",
"self",
".",
"dead",
".",
"remove",
"(",
"proxy",
")",
"self",
".",
"unchecked",
".",
"add",
"(",
"proxy",
")"
] | Mark all dead proxies as unchecked | [
"Mark",
"all",
"dead",
"proxies",
"as",
"unchecked"
] | 89bb677fea6285a5e02e0a5c7dfb1c40330b17f0 | https://github.com/TeamHG-Memex/scrapy-rotating-proxies/blob/89bb677fea6285a5e02e0a5c7dfb1c40330b17f0/rotating_proxies/expire.py#L115-L119 | train | 231,966 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable.on_change | def on_change(self, path, event_type):
"""Respond to changes in the file system
This method will be given the path to a file that
has changed on disk. We need to reload the keywords
from that file
"""
# I can do all this work in a sql statement, but
# for debugging it's easier to do it in stages.
sql = """SELECT collection_id
FROM collection_table
WHERE path == ?
"""
cursor = self._execute(sql, (path,))
results = cursor.fetchall()
# there should always be exactly one result, but
# there's no harm in using a loop to process the
# single result
for result in results:
collection_id = result[0]
# remove all keywords in this collection
sql = """DELETE from keyword_table
WHERE collection_id == ?
"""
cursor = self._execute(sql, (collection_id,))
self._load_keywords(collection_id, path=path) | python | def on_change(self, path, event_type):
"""Respond to changes in the file system
This method will be given the path to a file that
has changed on disk. We need to reload the keywords
from that file
"""
# I can do all this work in a sql statement, but
# for debugging it's easier to do it in stages.
sql = """SELECT collection_id
FROM collection_table
WHERE path == ?
"""
cursor = self._execute(sql, (path,))
results = cursor.fetchall()
# there should always be exactly one result, but
# there's no harm in using a loop to process the
# single result
for result in results:
collection_id = result[0]
# remove all keywords in this collection
sql = """DELETE from keyword_table
WHERE collection_id == ?
"""
cursor = self._execute(sql, (collection_id,))
self._load_keywords(collection_id, path=path) | [
"def",
"on_change",
"(",
"self",
",",
"path",
",",
"event_type",
")",
":",
"# I can do all this work in a sql statement, but",
"# for debugging it's easier to do it in stages.",
"sql",
"=",
"\"\"\"SELECT collection_id\n FROM collection_table\n WHERE path == ?\n \"\"\"",
"cursor",
"=",
"self",
".",
"_execute",
"(",
"sql",
",",
"(",
"path",
",",
")",
")",
"results",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"# there should always be exactly one result, but",
"# there's no harm in using a loop to process the",
"# single result",
"for",
"result",
"in",
"results",
":",
"collection_id",
"=",
"result",
"[",
"0",
"]",
"# remove all keywords in this collection",
"sql",
"=",
"\"\"\"DELETE from keyword_table\n WHERE collection_id == ?\n \"\"\"",
"cursor",
"=",
"self",
".",
"_execute",
"(",
"sql",
",",
"(",
"collection_id",
",",
")",
")",
"self",
".",
"_load_keywords",
"(",
"collection_id",
",",
"path",
"=",
"path",
")"
] | Respond to changes in the file system
This method will be given the path to a file that
has changed on disk. We need to reload the keywords
from that file | [
"Respond",
"to",
"changes",
"in",
"the",
"file",
"system"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L86-L111 | train | 231,967 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable._load_keywords | def _load_keywords(self, collection_id, path=None, libdoc=None):
"""Load a collection of keywords
One of path or libdoc needs to be passed in...
"""
if libdoc is None and path is None:
raise(Exception("You must provide either a path or libdoc argument"))
if libdoc is None:
libdoc = LibraryDocumentation(path)
if len(libdoc.keywords) > 0:
for keyword in libdoc.keywords:
self._add_keyword(collection_id, keyword.name, keyword.doc, keyword.args) | python | def _load_keywords(self, collection_id, path=None, libdoc=None):
"""Load a collection of keywords
One of path or libdoc needs to be passed in...
"""
if libdoc is None and path is None:
raise(Exception("You must provide either a path or libdoc argument"))
if libdoc is None:
libdoc = LibraryDocumentation(path)
if len(libdoc.keywords) > 0:
for keyword in libdoc.keywords:
self._add_keyword(collection_id, keyword.name, keyword.doc, keyword.args) | [
"def",
"_load_keywords",
"(",
"self",
",",
"collection_id",
",",
"path",
"=",
"None",
",",
"libdoc",
"=",
"None",
")",
":",
"if",
"libdoc",
"is",
"None",
"and",
"path",
"is",
"None",
":",
"raise",
"(",
"Exception",
"(",
"\"You must provide either a path or libdoc argument\"",
")",
")",
"if",
"libdoc",
"is",
"None",
":",
"libdoc",
"=",
"LibraryDocumentation",
"(",
"path",
")",
"if",
"len",
"(",
"libdoc",
".",
"keywords",
")",
">",
"0",
":",
"for",
"keyword",
"in",
"libdoc",
".",
"keywords",
":",
"self",
".",
"_add_keyword",
"(",
"collection_id",
",",
"keyword",
".",
"name",
",",
"keyword",
".",
"doc",
",",
"keyword",
".",
"args",
")"
] | Load a collection of keywords
One of path or libdoc needs to be passed in... | [
"Load",
"a",
"collection",
"of",
"keywords"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L113-L126 | train | 231,968 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable.add_file | def add_file(self, path):
"""Add a resource file or library file to the database"""
libdoc = LibraryDocumentation(path)
if len(libdoc.keywords) > 0:
if libdoc.doc.startswith("Documentation for resource file"):
# bah! The file doesn't have an file-level documentation
# and libdoc substitutes some placeholder text.
libdoc.doc = ""
collection_id = self.add_collection(path, libdoc.name, libdoc.type,
libdoc.doc, libdoc.version,
libdoc.scope, libdoc.named_args,
libdoc.doc_format)
self._load_keywords(collection_id, libdoc=libdoc) | python | def add_file(self, path):
"""Add a resource file or library file to the database"""
libdoc = LibraryDocumentation(path)
if len(libdoc.keywords) > 0:
if libdoc.doc.startswith("Documentation for resource file"):
# bah! The file doesn't have an file-level documentation
# and libdoc substitutes some placeholder text.
libdoc.doc = ""
collection_id = self.add_collection(path, libdoc.name, libdoc.type,
libdoc.doc, libdoc.version,
libdoc.scope, libdoc.named_args,
libdoc.doc_format)
self._load_keywords(collection_id, libdoc=libdoc) | [
"def",
"add_file",
"(",
"self",
",",
"path",
")",
":",
"libdoc",
"=",
"LibraryDocumentation",
"(",
"path",
")",
"if",
"len",
"(",
"libdoc",
".",
"keywords",
")",
">",
"0",
":",
"if",
"libdoc",
".",
"doc",
".",
"startswith",
"(",
"\"Documentation for resource file\"",
")",
":",
"# bah! The file doesn't have an file-level documentation",
"# and libdoc substitutes some placeholder text.",
"libdoc",
".",
"doc",
"=",
"\"\"",
"collection_id",
"=",
"self",
".",
"add_collection",
"(",
"path",
",",
"libdoc",
".",
"name",
",",
"libdoc",
".",
"type",
",",
"libdoc",
".",
"doc",
",",
"libdoc",
".",
"version",
",",
"libdoc",
".",
"scope",
",",
"libdoc",
".",
"named_args",
",",
"libdoc",
".",
"doc_format",
")",
"self",
".",
"_load_keywords",
"(",
"collection_id",
",",
"libdoc",
"=",
"libdoc",
")"
] | Add a resource file or library file to the database | [
"Add",
"a",
"resource",
"file",
"or",
"library",
"file",
"to",
"the",
"database"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L128-L141 | train | 231,969 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable.add_library | def add_library(self, name):
"""Add a library to the database
This method is for adding a library by name (eg: "BuiltIn")
rather than by a file.
"""
libdoc = LibraryDocumentation(name)
if len(libdoc.keywords) > 0:
# FIXME: figure out the path to the library file
collection_id = self.add_collection(None, libdoc.name, libdoc.type,
libdoc.doc, libdoc.version,
libdoc.scope, libdoc.named_args,
libdoc.doc_format)
self._load_keywords(collection_id, libdoc=libdoc) | python | def add_library(self, name):
"""Add a library to the database
This method is for adding a library by name (eg: "BuiltIn")
rather than by a file.
"""
libdoc = LibraryDocumentation(name)
if len(libdoc.keywords) > 0:
# FIXME: figure out the path to the library file
collection_id = self.add_collection(None, libdoc.name, libdoc.type,
libdoc.doc, libdoc.version,
libdoc.scope, libdoc.named_args,
libdoc.doc_format)
self._load_keywords(collection_id, libdoc=libdoc) | [
"def",
"add_library",
"(",
"self",
",",
"name",
")",
":",
"libdoc",
"=",
"LibraryDocumentation",
"(",
"name",
")",
"if",
"len",
"(",
"libdoc",
".",
"keywords",
")",
">",
"0",
":",
"# FIXME: figure out the path to the library file",
"collection_id",
"=",
"self",
".",
"add_collection",
"(",
"None",
",",
"libdoc",
".",
"name",
",",
"libdoc",
".",
"type",
",",
"libdoc",
".",
"doc",
",",
"libdoc",
".",
"version",
",",
"libdoc",
".",
"scope",
",",
"libdoc",
".",
"named_args",
",",
"libdoc",
".",
"doc_format",
")",
"self",
".",
"_load_keywords",
"(",
"collection_id",
",",
"libdoc",
"=",
"libdoc",
")"
] | Add a library to the database
This method is for adding a library by name (eg: "BuiltIn")
rather than by a file. | [
"Add",
"a",
"library",
"to",
"the",
"database"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L143-L156 | train | 231,970 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable.add_folder | def add_folder(self, dirname, watch=True):
"""Recursively add all files in a folder to the database
By "all files" I mean, "all files that are resource files
or library files". It will silently ignore files that don't
look like they belong in the database. Pity the fool who
uses non-standard suffixes.
N.B. folders with names that begin with '." will be skipped
"""
ignore_file = os.path.join(dirname, ".rfhubignore")
exclude_patterns = []
try:
with open(ignore_file, "r") as f:
exclude_patterns = []
for line in f.readlines():
line = line.strip()
if (re.match(r'^\s*#', line)): continue
if len(line.strip()) > 0:
exclude_patterns.append(line)
except:
# should probably warn the user?
pass
for filename in os.listdir(dirname):
path = os.path.join(dirname, filename)
(basename, ext) = os.path.splitext(filename.lower())
try:
if (os.path.isdir(path)):
if (not basename.startswith(".")):
if os.access(path, os.R_OK):
self.add_folder(path, watch=False)
else:
if (ext in (".xml", ".robot", ".txt", ".py", ".tsv")):
if os.access(path, os.R_OK):
self.add(path)
except Exception as e:
# I really need to get the logging situation figured out.
print("bummer:", str(e))
# FIXME:
# instead of passing a flag around, I should just keep track
# of which folders we're watching, and don't add wathers for
# any subfolders. That will work better in the case where
# the user accidentally starts up the hub giving the same
# folder, or a folder and it's children, on the command line...
if watch:
# add watcher on normalized path
dirname = os.path.abspath(dirname)
event_handler = WatchdogHandler(self, dirname)
self.observer.schedule(event_handler, dirname, recursive=True) | python | def add_folder(self, dirname, watch=True):
"""Recursively add all files in a folder to the database
By "all files" I mean, "all files that are resource files
or library files". It will silently ignore files that don't
look like they belong in the database. Pity the fool who
uses non-standard suffixes.
N.B. folders with names that begin with '." will be skipped
"""
ignore_file = os.path.join(dirname, ".rfhubignore")
exclude_patterns = []
try:
with open(ignore_file, "r") as f:
exclude_patterns = []
for line in f.readlines():
line = line.strip()
if (re.match(r'^\s*#', line)): continue
if len(line.strip()) > 0:
exclude_patterns.append(line)
except:
# should probably warn the user?
pass
for filename in os.listdir(dirname):
path = os.path.join(dirname, filename)
(basename, ext) = os.path.splitext(filename.lower())
try:
if (os.path.isdir(path)):
if (not basename.startswith(".")):
if os.access(path, os.R_OK):
self.add_folder(path, watch=False)
else:
if (ext in (".xml", ".robot", ".txt", ".py", ".tsv")):
if os.access(path, os.R_OK):
self.add(path)
except Exception as e:
# I really need to get the logging situation figured out.
print("bummer:", str(e))
# FIXME:
# instead of passing a flag around, I should just keep track
# of which folders we're watching, and don't add wathers for
# any subfolders. That will work better in the case where
# the user accidentally starts up the hub giving the same
# folder, or a folder and it's children, on the command line...
if watch:
# add watcher on normalized path
dirname = os.path.abspath(dirname)
event_handler = WatchdogHandler(self, dirname)
self.observer.schedule(event_handler, dirname, recursive=True) | [
"def",
"add_folder",
"(",
"self",
",",
"dirname",
",",
"watch",
"=",
"True",
")",
":",
"ignore_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"\".rfhubignore\"",
")",
"exclude_patterns",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"ignore_file",
",",
"\"r\"",
")",
"as",
"f",
":",
"exclude_patterns",
"=",
"[",
"]",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"(",
"re",
".",
"match",
"(",
"r'^\\s*#'",
",",
"line",
")",
")",
":",
"continue",
"if",
"len",
"(",
"line",
".",
"strip",
"(",
")",
")",
">",
"0",
":",
"exclude_patterns",
".",
"append",
"(",
"line",
")",
"except",
":",
"# should probably warn the user?",
"pass",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"dirname",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"filename",
")",
"(",
"basename",
",",
"ext",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
".",
"lower",
"(",
")",
")",
"try",
":",
"if",
"(",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
")",
":",
"if",
"(",
"not",
"basename",
".",
"startswith",
"(",
"\".\"",
")",
")",
":",
"if",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"R_OK",
")",
":",
"self",
".",
"add_folder",
"(",
"path",
",",
"watch",
"=",
"False",
")",
"else",
":",
"if",
"(",
"ext",
"in",
"(",
"\".xml\"",
",",
"\".robot\"",
",",
"\".txt\"",
",",
"\".py\"",
",",
"\".tsv\"",
")",
")",
":",
"if",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"R_OK",
")",
":",
"self",
".",
"add",
"(",
"path",
")",
"except",
"Exception",
"as",
"e",
":",
"# I really need to get the logging situation figured out.",
"print",
"(",
"\"bummer:\"",
",",
"str",
"(",
"e",
")",
")",
"# FIXME:",
"# instead of passing a flag around, I should just keep track",
"# of which folders we're watching, and don't add wathers for",
"# any subfolders. That will work better in the case where",
"# the user accidentally starts up the hub giving the same",
"# folder, or a folder and it's children, on the command line...",
"if",
"watch",
":",
"# add watcher on normalized path",
"dirname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dirname",
")",
"event_handler",
"=",
"WatchdogHandler",
"(",
"self",
",",
"dirname",
")",
"self",
".",
"observer",
".",
"schedule",
"(",
"event_handler",
",",
"dirname",
",",
"recursive",
"=",
"True",
")"
] | Recursively add all files in a folder to the database
By "all files" I mean, "all files that are resource files
or library files". It will silently ignore files that don't
look like they belong in the database. Pity the fool who
uses non-standard suffixes.
N.B. folders with names that begin with '." will be skipped | [
"Recursively",
"add",
"all",
"files",
"in",
"a",
"folder",
"to",
"the",
"database"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L158-L210 | train | 231,971 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable.add_installed_libraries | def add_installed_libraries(self, extra_libs = ["Selenium2Library",
"SudsLibrary",
"RequestsLibrary"]):
"""Add any installed libraries that we can find
We do this by looking in the `libraries` folder where
robot is installed. If you have libraries installed
in a non-standard place, this won't pick them up.
"""
libdir = os.path.dirname(robot.libraries.__file__)
loaded = []
for filename in os.listdir(libdir):
if filename.endswith(".py") or filename.endswith(".pyc"):
libname, ext = os.path.splitext(filename)
if (libname.lower() not in loaded and
not self._should_ignore(libname)):
try:
self.add(libname)
loaded.append(libname.lower())
except Exception as e:
# need a better way to log this...
self.log.debug("unable to add library: " + str(e))
# I hate how I implemented this, but I don't think there's
# any way to find out which installed python packages are
# robot libraries.
for library in extra_libs:
if (library.lower() not in loaded and
not self._should_ignore(library)):
try:
self.add(library)
loaded.append(library.lower())
except Exception as e:
self.log.debug("unable to add external library %s: %s" % \
(library, str(e))) | python | def add_installed_libraries(self, extra_libs = ["Selenium2Library",
"SudsLibrary",
"RequestsLibrary"]):
"""Add any installed libraries that we can find
We do this by looking in the `libraries` folder where
robot is installed. If you have libraries installed
in a non-standard place, this won't pick them up.
"""
libdir = os.path.dirname(robot.libraries.__file__)
loaded = []
for filename in os.listdir(libdir):
if filename.endswith(".py") or filename.endswith(".pyc"):
libname, ext = os.path.splitext(filename)
if (libname.lower() not in loaded and
not self._should_ignore(libname)):
try:
self.add(libname)
loaded.append(libname.lower())
except Exception as e:
# need a better way to log this...
self.log.debug("unable to add library: " + str(e))
# I hate how I implemented this, but I don't think there's
# any way to find out which installed python packages are
# robot libraries.
for library in extra_libs:
if (library.lower() not in loaded and
not self._should_ignore(library)):
try:
self.add(library)
loaded.append(library.lower())
except Exception as e:
self.log.debug("unable to add external library %s: %s" % \
(library, str(e))) | [
"def",
"add_installed_libraries",
"(",
"self",
",",
"extra_libs",
"=",
"[",
"\"Selenium2Library\"",
",",
"\"SudsLibrary\"",
",",
"\"RequestsLibrary\"",
"]",
")",
":",
"libdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"robot",
".",
"libraries",
".",
"__file__",
")",
"loaded",
"=",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"libdir",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"\".py\"",
")",
"or",
"filename",
".",
"endswith",
"(",
"\".pyc\"",
")",
":",
"libname",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"(",
"libname",
".",
"lower",
"(",
")",
"not",
"in",
"loaded",
"and",
"not",
"self",
".",
"_should_ignore",
"(",
"libname",
")",
")",
":",
"try",
":",
"self",
".",
"add",
"(",
"libname",
")",
"loaded",
".",
"append",
"(",
"libname",
".",
"lower",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"# need a better way to log this...",
"self",
".",
"log",
".",
"debug",
"(",
"\"unable to add library: \"",
"+",
"str",
"(",
"e",
")",
")",
"# I hate how I implemented this, but I don't think there's",
"# any way to find out which installed python packages are",
"# robot libraries.",
"for",
"library",
"in",
"extra_libs",
":",
"if",
"(",
"library",
".",
"lower",
"(",
")",
"not",
"in",
"loaded",
"and",
"not",
"self",
".",
"_should_ignore",
"(",
"library",
")",
")",
":",
"try",
":",
"self",
".",
"add",
"(",
"library",
")",
"loaded",
".",
"append",
"(",
"library",
".",
"lower",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"unable to add external library %s: %s\"",
"%",
"(",
"library",
",",
"str",
"(",
"e",
")",
")",
")"
] | Add any installed libraries that we can find
We do this by looking in the `libraries` folder where
robot is installed. If you have libraries installed
in a non-standard place, this won't pick them up. | [
"Add",
"any",
"installed",
"libraries",
"that",
"we",
"can",
"find"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L230-L266 | train | 231,972 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable.get_collection | def get_collection(self, collection_id):
"""Get a specific collection"""
sql = """SELECT collection.collection_id, collection.type,
collection.name, collection.path,
collection.doc,
collection.version, collection.scope,
collection.namedargs,
collection.doc_format
FROM collection_table as collection
WHERE collection_id == ? OR collection.name like ?
"""
cursor = self._execute(sql, (collection_id, collection_id))
# need to handle the case where we get more than one result...
sql_result = cursor.fetchone()
return {
"collection_id": sql_result[0],
"type": sql_result[1],
"name": sql_result[2],
"path": sql_result[3],
"doc": sql_result[4],
"version": sql_result[5],
"scope": sql_result[6],
"namedargs": sql_result[7],
"doc_format": sql_result[8]
}
return sql_result | python | def get_collection(self, collection_id):
"""Get a specific collection"""
sql = """SELECT collection.collection_id, collection.type,
collection.name, collection.path,
collection.doc,
collection.version, collection.scope,
collection.namedargs,
collection.doc_format
FROM collection_table as collection
WHERE collection_id == ? OR collection.name like ?
"""
cursor = self._execute(sql, (collection_id, collection_id))
# need to handle the case where we get more than one result...
sql_result = cursor.fetchone()
return {
"collection_id": sql_result[0],
"type": sql_result[1],
"name": sql_result[2],
"path": sql_result[3],
"doc": sql_result[4],
"version": sql_result[5],
"scope": sql_result[6],
"namedargs": sql_result[7],
"doc_format": sql_result[8]
}
return sql_result | [
"def",
"get_collection",
"(",
"self",
",",
"collection_id",
")",
":",
"sql",
"=",
"\"\"\"SELECT collection.collection_id, collection.type,\n collection.name, collection.path,\n collection.doc,\n collection.version, collection.scope,\n collection.namedargs,\n collection.doc_format\n FROM collection_table as collection\n WHERE collection_id == ? OR collection.name like ?\n \"\"\"",
"cursor",
"=",
"self",
".",
"_execute",
"(",
"sql",
",",
"(",
"collection_id",
",",
"collection_id",
")",
")",
"# need to handle the case where we get more than one result...",
"sql_result",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"{",
"\"collection_id\"",
":",
"sql_result",
"[",
"0",
"]",
",",
"\"type\"",
":",
"sql_result",
"[",
"1",
"]",
",",
"\"name\"",
":",
"sql_result",
"[",
"2",
"]",
",",
"\"path\"",
":",
"sql_result",
"[",
"3",
"]",
",",
"\"doc\"",
":",
"sql_result",
"[",
"4",
"]",
",",
"\"version\"",
":",
"sql_result",
"[",
"5",
"]",
",",
"\"scope\"",
":",
"sql_result",
"[",
"6",
"]",
",",
"\"namedargs\"",
":",
"sql_result",
"[",
"7",
"]",
",",
"\"doc_format\"",
":",
"sql_result",
"[",
"8",
"]",
"}",
"return",
"sql_result"
] | Get a specific collection | [
"Get",
"a",
"specific",
"collection"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L268-L293 | train | 231,973 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable.get_keyword | def get_keyword(self, collection_id, name):
"""Get a specific keyword from a library"""
sql = """SELECT keyword.name, keyword.args, keyword.doc
FROM keyword_table as keyword
WHERE keyword.collection_id == ?
AND keyword.name like ?
"""
cursor = self._execute(sql, (collection_id,name))
# We're going to assume no library has duplicate keywords
# While that in theory _could_ happen, it never _should_,
# and you get what you deserve if it does.
row = cursor.fetchone()
if row is not None:
return {"name": row[0],
"args": json.loads(row[1]),
"doc": row[2],
"collection_id": collection_id
}
return {} | python | def get_keyword(self, collection_id, name):
"""Get a specific keyword from a library"""
sql = """SELECT keyword.name, keyword.args, keyword.doc
FROM keyword_table as keyword
WHERE keyword.collection_id == ?
AND keyword.name like ?
"""
cursor = self._execute(sql, (collection_id,name))
# We're going to assume no library has duplicate keywords
# While that in theory _could_ happen, it never _should_,
# and you get what you deserve if it does.
row = cursor.fetchone()
if row is not None:
return {"name": row[0],
"args": json.loads(row[1]),
"doc": row[2],
"collection_id": collection_id
}
return {} | [
"def",
"get_keyword",
"(",
"self",
",",
"collection_id",
",",
"name",
")",
":",
"sql",
"=",
"\"\"\"SELECT keyword.name, keyword.args, keyword.doc\n FROM keyword_table as keyword\n WHERE keyword.collection_id == ?\n AND keyword.name like ?\n \"\"\"",
"cursor",
"=",
"self",
".",
"_execute",
"(",
"sql",
",",
"(",
"collection_id",
",",
"name",
")",
")",
"# We're going to assume no library has duplicate keywords",
"# While that in theory _could_ happen, it never _should_,",
"# and you get what you deserve if it does.",
"row",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"if",
"row",
"is",
"not",
"None",
":",
"return",
"{",
"\"name\"",
":",
"row",
"[",
"0",
"]",
",",
"\"args\"",
":",
"json",
".",
"loads",
"(",
"row",
"[",
"1",
"]",
")",
",",
"\"doc\"",
":",
"row",
"[",
"2",
"]",
",",
"\"collection_id\"",
":",
"collection_id",
"}",
"return",
"{",
"}"
] | Get a specific keyword from a library | [
"Get",
"a",
"specific",
"keyword",
"from",
"a",
"library"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L326-L344 | train | 231,974 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable._looks_like_libdoc_file | def _looks_like_libdoc_file(self, name):
"""Return true if an xml file looks like a libdoc file"""
# inefficient since we end up reading the file twice,
# but it's fast enough for our purposes, and prevents
# us from doing a full parse of files that are obviously
# not libdoc files
if name.lower().endswith(".xml"):
with open(name, "r") as f:
# read the first few lines; if we don't see
# what looks like libdoc data, return false
data = f.read(200)
index = data.lower().find("<keywordspec ")
if index > 0:
return True
return False | python | def _looks_like_libdoc_file(self, name):
"""Return true if an xml file looks like a libdoc file"""
# inefficient since we end up reading the file twice,
# but it's fast enough for our purposes, and prevents
# us from doing a full parse of files that are obviously
# not libdoc files
if name.lower().endswith(".xml"):
with open(name, "r") as f:
# read the first few lines; if we don't see
# what looks like libdoc data, return false
data = f.read(200)
index = data.lower().find("<keywordspec ")
if index > 0:
return True
return False | [
"def",
"_looks_like_libdoc_file",
"(",
"self",
",",
"name",
")",
":",
"# inefficient since we end up reading the file twice,",
"# but it's fast enough for our purposes, and prevents",
"# us from doing a full parse of files that are obviously",
"# not libdoc files",
"if",
"name",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".xml\"",
")",
":",
"with",
"open",
"(",
"name",
",",
"\"r\"",
")",
"as",
"f",
":",
"# read the first few lines; if we don't see",
"# what looks like libdoc data, return false",
"data",
"=",
"f",
".",
"read",
"(",
"200",
")",
"index",
"=",
"data",
".",
"lower",
"(",
")",
".",
"find",
"(",
"\"<keywordspec \"",
")",
"if",
"index",
">",
"0",
":",
"return",
"True",
"return",
"False"
] | Return true if an xml file looks like a libdoc file | [
"Return",
"true",
"if",
"an",
"xml",
"file",
"looks",
"like",
"a",
"libdoc",
"file"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L447-L461 | train | 231,975 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable._looks_like_resource_file | def _looks_like_resource_file(self, name):
"""Return true if the file has a keyword table but not a testcase table"""
# inefficient since we end up reading the file twice,
# but it's fast enough for our purposes, and prevents
# us from doing a full parse of files that are obviously
# not robot files
if (re.search(r'__init__.(txt|robot|html|tsv)$', name)):
# These are initialize files, not resource files
return False
found_keyword_table = False
if (name.lower().endswith(".robot") or
name.lower().endswith(".txt") or
name.lower().endswith(".tsv")):
with open(name, "r") as f:
data = f.read()
for match in re.finditer(r'^\*+\s*(Test Cases?|(?:User )?Keywords?)',
data, re.MULTILINE|re.IGNORECASE):
if (re.match(r'Test Cases?', match.group(1), re.IGNORECASE)):
# if there's a test case table, it's not a keyword file
return False
if (not found_keyword_table and
re.match(r'(User )?Keywords?', match.group(1), re.IGNORECASE)):
found_keyword_table = True
return found_keyword_table | python | def _looks_like_resource_file(self, name):
"""Return true if the file has a keyword table but not a testcase table"""
# inefficient since we end up reading the file twice,
# but it's fast enough for our purposes, and prevents
# us from doing a full parse of files that are obviously
# not robot files
if (re.search(r'__init__.(txt|robot|html|tsv)$', name)):
# These are initialize files, not resource files
return False
found_keyword_table = False
if (name.lower().endswith(".robot") or
name.lower().endswith(".txt") or
name.lower().endswith(".tsv")):
with open(name, "r") as f:
data = f.read()
for match in re.finditer(r'^\*+\s*(Test Cases?|(?:User )?Keywords?)',
data, re.MULTILINE|re.IGNORECASE):
if (re.match(r'Test Cases?', match.group(1), re.IGNORECASE)):
# if there's a test case table, it's not a keyword file
return False
if (not found_keyword_table and
re.match(r'(User )?Keywords?', match.group(1), re.IGNORECASE)):
found_keyword_table = True
return found_keyword_table | [
"def",
"_looks_like_resource_file",
"(",
"self",
",",
"name",
")",
":",
"# inefficient since we end up reading the file twice,",
"# but it's fast enough for our purposes, and prevents",
"# us from doing a full parse of files that are obviously",
"# not robot files",
"if",
"(",
"re",
".",
"search",
"(",
"r'__init__.(txt|robot|html|tsv)$'",
",",
"name",
")",
")",
":",
"# These are initialize files, not resource files",
"return",
"False",
"found_keyword_table",
"=",
"False",
"if",
"(",
"name",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".robot\"",
")",
"or",
"name",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".txt\"",
")",
"or",
"name",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".tsv\"",
")",
")",
":",
"with",
"open",
"(",
"name",
",",
"\"r\"",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'^\\*+\\s*(Test Cases?|(?:User )?Keywords?)'",
",",
"data",
",",
"re",
".",
"MULTILINE",
"|",
"re",
".",
"IGNORECASE",
")",
":",
"if",
"(",
"re",
".",
"match",
"(",
"r'Test Cases?'",
",",
"match",
".",
"group",
"(",
"1",
")",
",",
"re",
".",
"IGNORECASE",
")",
")",
":",
"# if there's a test case table, it's not a keyword file",
"return",
"False",
"if",
"(",
"not",
"found_keyword_table",
"and",
"re",
".",
"match",
"(",
"r'(User )?Keywords?'",
",",
"match",
".",
"group",
"(",
"1",
")",
",",
"re",
".",
"IGNORECASE",
")",
")",
":",
"found_keyword_table",
"=",
"True",
"return",
"found_keyword_table"
] | Return true if the file has a keyword table but not a testcase table | [
"Return",
"true",
"if",
"the",
"file",
"has",
"a",
"keyword",
"table",
"but",
"not",
"a",
"testcase",
"table"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L463-L490 | train | 231,976 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable._should_ignore | def _should_ignore(self, name):
"""Return True if a given library name should be ignored
This is necessary because not all files we find in the library
folder are libraries. I wish there was a public robot API
for "give me a list of installed libraries"...
"""
_name = name.lower()
return (_name.startswith("deprecated") or
_name.startswith("_") or
_name in ("remote", "reserved",
"dialogs_py", "dialogs_ipy", "dialogs_jy")) | python | def _should_ignore(self, name):
"""Return True if a given library name should be ignored
This is necessary because not all files we find in the library
folder are libraries. I wish there was a public robot API
for "give me a list of installed libraries"...
"""
_name = name.lower()
return (_name.startswith("deprecated") or
_name.startswith("_") or
_name in ("remote", "reserved",
"dialogs_py", "dialogs_ipy", "dialogs_jy")) | [
"def",
"_should_ignore",
"(",
"self",
",",
"name",
")",
":",
"_name",
"=",
"name",
".",
"lower",
"(",
")",
"return",
"(",
"_name",
".",
"startswith",
"(",
"\"deprecated\"",
")",
"or",
"_name",
".",
"startswith",
"(",
"\"_\"",
")",
"or",
"_name",
"in",
"(",
"\"remote\"",
",",
"\"reserved\"",
",",
"\"dialogs_py\"",
",",
"\"dialogs_ipy\"",
",",
"\"dialogs_jy\"",
")",
")"
] | Return True if a given library name should be ignored
This is necessary because not all files we find in the library
folder are libraries. I wish there was a public robot API
for "give me a list of installed libraries"... | [
"Return",
"True",
"if",
"a",
"given",
"library",
"name",
"should",
"be",
"ignored"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L492-L503 | train | 231,977 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable._execute | def _execute(self, *args):
"""Execute an SQL query
This exists because I think it's tedious to get a cursor and
then use a cursor.
"""
cursor = self.db.cursor()
cursor.execute(*args)
return cursor | python | def _execute(self, *args):
"""Execute an SQL query
This exists because I think it's tedious to get a cursor and
then use a cursor.
"""
cursor = self.db.cursor()
cursor.execute(*args)
return cursor | [
"def",
"_execute",
"(",
"self",
",",
"*",
"args",
")",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"*",
"args",
")",
"return",
"cursor"
] | Execute an SQL query
This exists because I think it's tedious to get a cursor and
then use a cursor. | [
"Execute",
"an",
"SQL",
"query"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L505-L513 | train | 231,978 |
boakley/robotframework-hub | rfhub/kwdb.py | KeywordTable._glob_to_sql | def _glob_to_sql(self, string):
"""Convert glob-like wildcards to SQL wildcards
* becomes %
? becomes _
% becomes \%
\\ remains \\
\* remains \*
\? remains \?
This also adds a leading and trailing %, unless the pattern begins with
^ or ends with $
"""
# What's with the chr(1) and chr(2) nonsense? It's a trick to
# hide \* and \? from the * and ? substitutions. This trick
# depends on the substitutiones being done in order. chr(1)
# and chr(2) were picked because I know those characters
# almost certainly won't be in the input string
table = ((r'\\', chr(1)), (r'\*', chr(2)), (r'\?', chr(3)),
(r'%', r'\%'), (r'?', '_'), (r'*', '%'),
(chr(1), r'\\'), (chr(2), r'\*'), (chr(3), r'\?'))
for (a, b) in table:
string = string.replace(a,b)
string = string[1:] if string.startswith("^") else "%" + string
string = string[:-1] if string.endswith("$") else string + "%"
return string | python | def _glob_to_sql(self, string):
"""Convert glob-like wildcards to SQL wildcards
* becomes %
? becomes _
% becomes \%
\\ remains \\
\* remains \*
\? remains \?
This also adds a leading and trailing %, unless the pattern begins with
^ or ends with $
"""
# What's with the chr(1) and chr(2) nonsense? It's a trick to
# hide \* and \? from the * and ? substitutions. This trick
# depends on the substitutiones being done in order. chr(1)
# and chr(2) were picked because I know those characters
# almost certainly won't be in the input string
table = ((r'\\', chr(1)), (r'\*', chr(2)), (r'\?', chr(3)),
(r'%', r'\%'), (r'?', '_'), (r'*', '%'),
(chr(1), r'\\'), (chr(2), r'\*'), (chr(3), r'\?'))
for (a, b) in table:
string = string.replace(a,b)
string = string[1:] if string.startswith("^") else "%" + string
string = string[:-1] if string.endswith("$") else string + "%"
return string | [
"def",
"_glob_to_sql",
"(",
"self",
",",
"string",
")",
":",
"# What's with the chr(1) and chr(2) nonsense? It's a trick to",
"# hide \\* and \\? from the * and ? substitutions. This trick",
"# depends on the substitutiones being done in order. chr(1)",
"# and chr(2) were picked because I know those characters",
"# almost certainly won't be in the input string",
"table",
"=",
"(",
"(",
"r'\\\\'",
",",
"chr",
"(",
"1",
")",
")",
",",
"(",
"r'\\*'",
",",
"chr",
"(",
"2",
")",
")",
",",
"(",
"r'\\?'",
",",
"chr",
"(",
"3",
")",
")",
",",
"(",
"r'%'",
",",
"r'\\%'",
")",
",",
"(",
"r'?'",
",",
"'_'",
")",
",",
"(",
"r'*'",
",",
"'%'",
")",
",",
"(",
"chr",
"(",
"1",
")",
",",
"r'\\\\'",
")",
",",
"(",
"chr",
"(",
"2",
")",
",",
"r'\\*'",
")",
",",
"(",
"chr",
"(",
"3",
")",
",",
"r'\\?'",
")",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"table",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"a",
",",
"b",
")",
"string",
"=",
"string",
"[",
"1",
":",
"]",
"if",
"string",
".",
"startswith",
"(",
"\"^\"",
")",
"else",
"\"%\"",
"+",
"string",
"string",
"=",
"string",
"[",
":",
"-",
"1",
"]",
"if",
"string",
".",
"endswith",
"(",
"\"$\"",
")",
"else",
"string",
"+",
"\"%\"",
"return",
"string"
] | Convert glob-like wildcards to SQL wildcards
* becomes %
? becomes _
% becomes \%
\\ remains \\
\* remains \*
\? remains \?
This also adds a leading and trailing %, unless the pattern begins with
^ or ends with $ | [
"Convert",
"glob",
"-",
"like",
"wildcards",
"to",
"SQL",
"wildcards"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L565-L594 | train | 231,979 |
boakley/robotframework-hub | rfhub/blueprints/doc/__init__.py | doc | def doc():
"""Show a list of libraries, along with the nav panel on the left"""
kwdb = current_app.kwdb
libraries = get_collections(kwdb, libtype="library")
resource_files = get_collections(kwdb, libtype="resource")
hierarchy = get_navpanel_data(kwdb)
return flask.render_template("home.html",
data={"libraries": libraries,
"version": __version__,
"libdoc": None,
"hierarchy": hierarchy,
"resource_files": resource_files
}) | python | def doc():
"""Show a list of libraries, along with the nav panel on the left"""
kwdb = current_app.kwdb
libraries = get_collections(kwdb, libtype="library")
resource_files = get_collections(kwdb, libtype="resource")
hierarchy = get_navpanel_data(kwdb)
return flask.render_template("home.html",
data={"libraries": libraries,
"version": __version__,
"libdoc": None,
"hierarchy": hierarchy,
"resource_files": resource_files
}) | [
"def",
"doc",
"(",
")",
":",
"kwdb",
"=",
"current_app",
".",
"kwdb",
"libraries",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"library\"",
")",
"resource_files",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"resource\"",
")",
"hierarchy",
"=",
"get_navpanel_data",
"(",
"kwdb",
")",
"return",
"flask",
".",
"render_template",
"(",
"\"home.html\"",
",",
"data",
"=",
"{",
"\"libraries\"",
":",
"libraries",
",",
"\"version\"",
":",
"__version__",
",",
"\"libdoc\"",
":",
"None",
",",
"\"hierarchy\"",
":",
"hierarchy",
",",
"\"resource_files\"",
":",
"resource_files",
"}",
")"
] | Show a list of libraries, along with the nav panel on the left | [
"Show",
"a",
"list",
"of",
"libraries",
"along",
"with",
"the",
"nav",
"panel",
"on",
"the",
"left"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/blueprints/doc/__init__.py#L14-L28 | train | 231,980 |
boakley/robotframework-hub | rfhub/blueprints/doc/__init__.py | index | def index():
"""Show a list of available libraries, and resource files"""
kwdb = current_app.kwdb
libraries = get_collections(kwdb, libtype="library")
resource_files = get_collections(kwdb, libtype="resource")
return flask.render_template("libraryNames.html",
data={"libraries": libraries,
"version": __version__,
"resource_files": resource_files
}) | python | def index():
"""Show a list of available libraries, and resource files"""
kwdb = current_app.kwdb
libraries = get_collections(kwdb, libtype="library")
resource_files = get_collections(kwdb, libtype="resource")
return flask.render_template("libraryNames.html",
data={"libraries": libraries,
"version": __version__,
"resource_files": resource_files
}) | [
"def",
"index",
"(",
")",
":",
"kwdb",
"=",
"current_app",
".",
"kwdb",
"libraries",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"library\"",
")",
"resource_files",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"resource\"",
")",
"return",
"flask",
".",
"render_template",
"(",
"\"libraryNames.html\"",
",",
"data",
"=",
"{",
"\"libraries\"",
":",
"libraries",
",",
"\"version\"",
":",
"__version__",
",",
"\"resource_files\"",
":",
"resource_files",
"}",
")"
] | Show a list of available libraries, and resource files | [
"Show",
"a",
"list",
"of",
"available",
"libraries",
"and",
"resource",
"files"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/blueprints/doc/__init__.py#L32-L43 | train | 231,981 |
boakley/robotframework-hub | rfhub/blueprints/doc/__init__.py | search | def search():
"""Show all keywords that match a pattern"""
pattern = flask.request.args.get('pattern', "*").strip().lower()
# if the pattern contains "in:<collection>" (eg: in:builtin),
# filter results to only that (or those) collections
# This was kind-of hacked together, but seems to work well enough
collections = [c["name"].lower() for c in current_app.kwdb.get_collections()]
words = []
filters = []
if pattern.startswith("name:"):
pattern = pattern[5:].strip()
mode = "name"
else:
mode="both"
for word in pattern.split(" "):
if word.lower().startswith("in:"):
filters.extend([name for name in collections if name.startswith(word[3:])])
else:
words.append(word)
pattern = " ".join(words)
keywords = []
for keyword in current_app.kwdb.search(pattern, mode):
kw = list(keyword)
collection_id = kw[0]
collection_name = kw[1].lower()
if len(filters) == 0 or collection_name in filters:
url = flask.url_for(".doc_for_library", collection_id=kw[0], keyword=kw[2])
row_id = "row-%s.%s" % (keyword[1].lower(), keyword[2].lower().replace(" ","-"))
keywords.append({"collection_id": keyword[0],
"collection_name": keyword[1],
"name": keyword[2],
"synopsis": keyword[3],
"version": __version__,
"url": url,
"row_id": row_id
})
keywords.sort(key=lambda kw: kw["name"])
return flask.render_template("search.html",
data={"keywords": keywords,
"version": __version__,
"pattern": pattern
}) | python | def search():
"""Show all keywords that match a pattern"""
pattern = flask.request.args.get('pattern', "*").strip().lower()
# if the pattern contains "in:<collection>" (eg: in:builtin),
# filter results to only that (or those) collections
# This was kind-of hacked together, but seems to work well enough
collections = [c["name"].lower() for c in current_app.kwdb.get_collections()]
words = []
filters = []
if pattern.startswith("name:"):
pattern = pattern[5:].strip()
mode = "name"
else:
mode="both"
for word in pattern.split(" "):
if word.lower().startswith("in:"):
filters.extend([name for name in collections if name.startswith(word[3:])])
else:
words.append(word)
pattern = " ".join(words)
keywords = []
for keyword in current_app.kwdb.search(pattern, mode):
kw = list(keyword)
collection_id = kw[0]
collection_name = kw[1].lower()
if len(filters) == 0 or collection_name in filters:
url = flask.url_for(".doc_for_library", collection_id=kw[0], keyword=kw[2])
row_id = "row-%s.%s" % (keyword[1].lower(), keyword[2].lower().replace(" ","-"))
keywords.append({"collection_id": keyword[0],
"collection_name": keyword[1],
"name": keyword[2],
"synopsis": keyword[3],
"version": __version__,
"url": url,
"row_id": row_id
})
keywords.sort(key=lambda kw: kw["name"])
return flask.render_template("search.html",
data={"keywords": keywords,
"version": __version__,
"pattern": pattern
}) | [
"def",
"search",
"(",
")",
":",
"pattern",
"=",
"flask",
".",
"request",
".",
"args",
".",
"get",
"(",
"'pattern'",
",",
"\"*\"",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"# if the pattern contains \"in:<collection>\" (eg: in:builtin),",
"# filter results to only that (or those) collections",
"# This was kind-of hacked together, but seems to work well enough",
"collections",
"=",
"[",
"c",
"[",
"\"name\"",
"]",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"current_app",
".",
"kwdb",
".",
"get_collections",
"(",
")",
"]",
"words",
"=",
"[",
"]",
"filters",
"=",
"[",
"]",
"if",
"pattern",
".",
"startswith",
"(",
"\"name:\"",
")",
":",
"pattern",
"=",
"pattern",
"[",
"5",
":",
"]",
".",
"strip",
"(",
")",
"mode",
"=",
"\"name\"",
"else",
":",
"mode",
"=",
"\"both\"",
"for",
"word",
"in",
"pattern",
".",
"split",
"(",
"\" \"",
")",
":",
"if",
"word",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"in:\"",
")",
":",
"filters",
".",
"extend",
"(",
"[",
"name",
"for",
"name",
"in",
"collections",
"if",
"name",
".",
"startswith",
"(",
"word",
"[",
"3",
":",
"]",
")",
"]",
")",
"else",
":",
"words",
".",
"append",
"(",
"word",
")",
"pattern",
"=",
"\" \"",
".",
"join",
"(",
"words",
")",
"keywords",
"=",
"[",
"]",
"for",
"keyword",
"in",
"current_app",
".",
"kwdb",
".",
"search",
"(",
"pattern",
",",
"mode",
")",
":",
"kw",
"=",
"list",
"(",
"keyword",
")",
"collection_id",
"=",
"kw",
"[",
"0",
"]",
"collection_name",
"=",
"kw",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"len",
"(",
"filters",
")",
"==",
"0",
"or",
"collection_name",
"in",
"filters",
":",
"url",
"=",
"flask",
".",
"url_for",
"(",
"\".doc_for_library\"",
",",
"collection_id",
"=",
"kw",
"[",
"0",
"]",
",",
"keyword",
"=",
"kw",
"[",
"2",
"]",
")",
"row_id",
"=",
"\"row-%s.%s\"",
"%",
"(",
"keyword",
"[",
"1",
"]",
".",
"lower",
"(",
")",
",",
"keyword",
"[",
"2",
"]",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"-\"",
")",
")",
"keywords",
".",
"append",
"(",
"{",
"\"collection_id\"",
":",
"keyword",
"[",
"0",
"]",
",",
"\"collection_name\"",
":",
"keyword",
"[",
"1",
"]",
",",
"\"name\"",
":",
"keyword",
"[",
"2",
"]",
",",
"\"synopsis\"",
":",
"keyword",
"[",
"3",
"]",
",",
"\"version\"",
":",
"__version__",
",",
"\"url\"",
":",
"url",
",",
"\"row_id\"",
":",
"row_id",
"}",
")",
"keywords",
".",
"sort",
"(",
"key",
"=",
"lambda",
"kw",
":",
"kw",
"[",
"\"name\"",
"]",
")",
"return",
"flask",
".",
"render_template",
"(",
"\"search.html\"",
",",
"data",
"=",
"{",
"\"keywords\"",
":",
"keywords",
",",
"\"version\"",
":",
"__version__",
",",
"\"pattern\"",
":",
"pattern",
"}",
")"
] | Show all keywords that match a pattern | [
"Show",
"all",
"keywords",
"that",
"match",
"a",
"pattern"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/blueprints/doc/__init__.py#L47-L92 | train | 231,982 |
boakley/robotframework-hub | rfhub/blueprints/doc/__init__.py | get_collections | def get_collections(kwdb, libtype="*"):
"""Get list of collections from kwdb, then add urls necessary for hyperlinks"""
collections = kwdb.get_collections(libtype=libtype)
for result in collections:
url = flask.url_for(".doc_for_library", collection_id=result["collection_id"])
result["url"] = url
return collections | python | def get_collections(kwdb, libtype="*"):
"""Get list of collections from kwdb, then add urls necessary for hyperlinks"""
collections = kwdb.get_collections(libtype=libtype)
for result in collections:
url = flask.url_for(".doc_for_library", collection_id=result["collection_id"])
result["url"] = url
return collections | [
"def",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"*\"",
")",
":",
"collections",
"=",
"kwdb",
".",
"get_collections",
"(",
"libtype",
"=",
"libtype",
")",
"for",
"result",
"in",
"collections",
":",
"url",
"=",
"flask",
".",
"url_for",
"(",
"\".doc_for_library\"",
",",
"collection_id",
"=",
"result",
"[",
"\"collection_id\"",
"]",
")",
"result",
"[",
"\"url\"",
"]",
"=",
"url",
"return",
"collections"
] | Get list of collections from kwdb, then add urls necessary for hyperlinks | [
"Get",
"list",
"of",
"collections",
"from",
"kwdb",
"then",
"add",
"urls",
"necessary",
"for",
"hyperlinks"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/blueprints/doc/__init__.py#L129-L136 | train | 231,983 |
boakley/robotframework-hub | rfhub/blueprints/doc/__init__.py | get_navpanel_data | def get_navpanel_data(kwdb):
"""Get navpanel data from kwdb, and add urls necessary for hyperlinks"""
data = kwdb.get_keyword_hierarchy()
for library in data:
library["url"] = flask.url_for(".doc_for_library", collection_id=library["collection_id"])
for keyword in library["keywords"]:
url = flask.url_for(".doc_for_library",
collection_id=library["collection_id"],
keyword=keyword["name"])
keyword["url"] = url
return data | python | def get_navpanel_data(kwdb):
"""Get navpanel data from kwdb, and add urls necessary for hyperlinks"""
data = kwdb.get_keyword_hierarchy()
for library in data:
library["url"] = flask.url_for(".doc_for_library", collection_id=library["collection_id"])
for keyword in library["keywords"]:
url = flask.url_for(".doc_for_library",
collection_id=library["collection_id"],
keyword=keyword["name"])
keyword["url"] = url
return data | [
"def",
"get_navpanel_data",
"(",
"kwdb",
")",
":",
"data",
"=",
"kwdb",
".",
"get_keyword_hierarchy",
"(",
")",
"for",
"library",
"in",
"data",
":",
"library",
"[",
"\"url\"",
"]",
"=",
"flask",
".",
"url_for",
"(",
"\".doc_for_library\"",
",",
"collection_id",
"=",
"library",
"[",
"\"collection_id\"",
"]",
")",
"for",
"keyword",
"in",
"library",
"[",
"\"keywords\"",
"]",
":",
"url",
"=",
"flask",
".",
"url_for",
"(",
"\".doc_for_library\"",
",",
"collection_id",
"=",
"library",
"[",
"\"collection_id\"",
"]",
",",
"keyword",
"=",
"keyword",
"[",
"\"name\"",
"]",
")",
"keyword",
"[",
"\"url\"",
"]",
"=",
"url",
"return",
"data"
] | Get navpanel data from kwdb, and add urls necessary for hyperlinks | [
"Get",
"navpanel",
"data",
"from",
"kwdb",
"and",
"add",
"urls",
"necessary",
"for",
"hyperlinks"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/blueprints/doc/__init__.py#L138-L149 | train | 231,984 |
boakley/robotframework-hub | rfhub/blueprints/doc/__init__.py | doc_to_html | def doc_to_html(doc, doc_format="ROBOT"):
"""Convert documentation to HTML"""
from robot.libdocpkg.htmlwriter import DocToHtml
return DocToHtml(doc_format)(doc) | python | def doc_to_html(doc, doc_format="ROBOT"):
"""Convert documentation to HTML"""
from robot.libdocpkg.htmlwriter import DocToHtml
return DocToHtml(doc_format)(doc) | [
"def",
"doc_to_html",
"(",
"doc",
",",
"doc_format",
"=",
"\"ROBOT\"",
")",
":",
"from",
"robot",
".",
"libdocpkg",
".",
"htmlwriter",
"import",
"DocToHtml",
"return",
"DocToHtml",
"(",
"doc_format",
")",
"(",
"doc",
")"
] | Convert documentation to HTML | [
"Convert",
"documentation",
"to",
"HTML"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/blueprints/doc/__init__.py#L152-L155 | train | 231,985 |
boakley/robotframework-hub | rfhub/app.py | RobotHub.start | def start(self):
"""Start the app"""
if self.args.debug:
self.app.run(port=self.args.port, debug=self.args.debug, host=self.args.interface)
else:
root = "http://%s:%s" % (self.args.interface, self.args.port)
print("tornado web server running on " + root)
self.shutdown_requested = False
http_server = HTTPServer(WSGIContainer(self.app))
http_server.listen(port=self.args.port, address=self.args.interface)
signal.signal(signal.SIGINT, self.signal_handler)
tornado.ioloop.PeriodicCallback(self.check_shutdown_flag, 500).start()
tornado.ioloop.IOLoop.instance().start() | python | def start(self):
"""Start the app"""
if self.args.debug:
self.app.run(port=self.args.port, debug=self.args.debug, host=self.args.interface)
else:
root = "http://%s:%s" % (self.args.interface, self.args.port)
print("tornado web server running on " + root)
self.shutdown_requested = False
http_server = HTTPServer(WSGIContainer(self.app))
http_server.listen(port=self.args.port, address=self.args.interface)
signal.signal(signal.SIGINT, self.signal_handler)
tornado.ioloop.PeriodicCallback(self.check_shutdown_flag, 500).start()
tornado.ioloop.IOLoop.instance().start() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
".",
"debug",
":",
"self",
".",
"app",
".",
"run",
"(",
"port",
"=",
"self",
".",
"args",
".",
"port",
",",
"debug",
"=",
"self",
".",
"args",
".",
"debug",
",",
"host",
"=",
"self",
".",
"args",
".",
"interface",
")",
"else",
":",
"root",
"=",
"\"http://%s:%s\"",
"%",
"(",
"self",
".",
"args",
".",
"interface",
",",
"self",
".",
"args",
".",
"port",
")",
"print",
"(",
"\"tornado web server running on \"",
"+",
"root",
")",
"self",
".",
"shutdown_requested",
"=",
"False",
"http_server",
"=",
"HTTPServer",
"(",
"WSGIContainer",
"(",
"self",
".",
"app",
")",
")",
"http_server",
".",
"listen",
"(",
"port",
"=",
"self",
".",
"args",
".",
"port",
",",
"address",
"=",
"self",
".",
"args",
".",
"interface",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"signal_handler",
")",
"tornado",
".",
"ioloop",
".",
"PeriodicCallback",
"(",
"self",
".",
"check_shutdown_flag",
",",
"500",
")",
".",
"start",
"(",
")",
"tornado",
".",
"ioloop",
".",
"IOLoop",
".",
"instance",
"(",
")",
".",
"start",
"(",
")"
] | Start the app | [
"Start",
"the",
"app"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/app.py#L50-L63 | train | 231,986 |
boakley/robotframework-hub | rfhub/app.py | RobotHub.check_shutdown_flag | def check_shutdown_flag(self):
"""Shutdown the server if the flag has been set"""
if self.shutdown_requested:
tornado.ioloop.IOLoop.instance().stop()
print("web server stopped.") | python | def check_shutdown_flag(self):
"""Shutdown the server if the flag has been set"""
if self.shutdown_requested:
tornado.ioloop.IOLoop.instance().stop()
print("web server stopped.") | [
"def",
"check_shutdown_flag",
"(",
"self",
")",
":",
"if",
"self",
".",
"shutdown_requested",
":",
"tornado",
".",
"ioloop",
".",
"IOLoop",
".",
"instance",
"(",
")",
".",
"stop",
"(",
")",
"print",
"(",
"\"web server stopped.\"",
")"
] | Shutdown the server if the flag has been set | [
"Shutdown",
"the",
"server",
"if",
"the",
"flag",
"has",
"been",
"set"
] | f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/app.py#L69-L73 | train | 231,987 |
jazzband/python-geojson | geojson/utils.py | coords | def coords(obj):
"""
Yields the coordinates from a Feature or Geometry.
:param obj: A geometry or feature to extract the coordinates from.
:type obj: Feature, Geometry
:return: A generator with coordinate tuples from the geometry or feature.
:rtype: generator
"""
# Handle recursive case first
if 'features' in obj:
for f in obj['features']:
# For Python 2 compatibility
# See https://www.reddit.com/r/learnpython/comments/4rc15s/yield_from_and_python_27/ # noqa: E501
for c in coords(f):
yield c
else:
if isinstance(obj, (tuple, list)):
coordinates = obj
elif 'geometry' in obj:
coordinates = obj['geometry']['coordinates']
else:
coordinates = obj.get('coordinates', obj)
for e in coordinates:
if isinstance(e, (float, int)):
yield tuple(coordinates)
break
for f in coords(e):
yield f | python | def coords(obj):
"""
Yields the coordinates from a Feature or Geometry.
:param obj: A geometry or feature to extract the coordinates from.
:type obj: Feature, Geometry
:return: A generator with coordinate tuples from the geometry or feature.
:rtype: generator
"""
# Handle recursive case first
if 'features' in obj:
for f in obj['features']:
# For Python 2 compatibility
# See https://www.reddit.com/r/learnpython/comments/4rc15s/yield_from_and_python_27/ # noqa: E501
for c in coords(f):
yield c
else:
if isinstance(obj, (tuple, list)):
coordinates = obj
elif 'geometry' in obj:
coordinates = obj['geometry']['coordinates']
else:
coordinates = obj.get('coordinates', obj)
for e in coordinates:
if isinstance(e, (float, int)):
yield tuple(coordinates)
break
for f in coords(e):
yield f | [
"def",
"coords",
"(",
"obj",
")",
":",
"# Handle recursive case first",
"if",
"'features'",
"in",
"obj",
":",
"for",
"f",
"in",
"obj",
"[",
"'features'",
"]",
":",
"# For Python 2 compatibility",
"# See https://www.reddit.com/r/learnpython/comments/4rc15s/yield_from_and_python_27/ # noqa: E501",
"for",
"c",
"in",
"coords",
"(",
"f",
")",
":",
"yield",
"c",
"else",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"coordinates",
"=",
"obj",
"elif",
"'geometry'",
"in",
"obj",
":",
"coordinates",
"=",
"obj",
"[",
"'geometry'",
"]",
"[",
"'coordinates'",
"]",
"else",
":",
"coordinates",
"=",
"obj",
".",
"get",
"(",
"'coordinates'",
",",
"obj",
")",
"for",
"e",
"in",
"coordinates",
":",
"if",
"isinstance",
"(",
"e",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"yield",
"tuple",
"(",
"coordinates",
")",
"break",
"for",
"f",
"in",
"coords",
"(",
"e",
")",
":",
"yield",
"f"
] | Yields the coordinates from a Feature or Geometry.
:param obj: A geometry or feature to extract the coordinates from.
:type obj: Feature, Geometry
:return: A generator with coordinate tuples from the geometry or feature.
:rtype: generator | [
"Yields",
"the",
"coordinates",
"from",
"a",
"Feature",
"or",
"Geometry",
"."
] | 14abb31ba73a9f3cdb81d81c56656ea736f3c865 | https://github.com/jazzband/python-geojson/blob/14abb31ba73a9f3cdb81d81c56656ea736f3c865/geojson/utils.py#L4-L32 | train | 231,988 |
jazzband/python-geojson | geojson/utils.py | map_tuples | def map_tuples(func, obj):
"""
Returns the mapped coordinates from a Geometry after applying the provided
function to each coordinate.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: Point, LineString, MultiPoint, MultiLineString, Polygon,
MultiPolygon
:return: The result of applying the function to each dimension in the
array.
:rtype: list
:raises ValueError: if the provided object is not GeoJSON.
"""
if obj['type'] == 'Point':
coordinates = tuple(func(obj['coordinates']))
elif obj['type'] in ['LineString', 'MultiPoint']:
coordinates = [tuple(func(c)) for c in obj['coordinates']]
elif obj['type'] in ['MultiLineString', 'Polygon']:
coordinates = [[
tuple(func(c)) for c in curve]
for curve in obj['coordinates']]
elif obj['type'] == 'MultiPolygon':
coordinates = [[[
tuple(func(c)) for c in curve]
for curve in part]
for part in obj['coordinates']]
elif obj['type'] in ['Feature', 'FeatureCollection', 'GeometryCollection']:
return map_geometries(lambda g: map_tuples(func, g), obj)
else:
raise ValueError("Invalid geometry object %s" % repr(obj))
return {'type': obj['type'], 'coordinates': coordinates} | python | def map_tuples(func, obj):
"""
Returns the mapped coordinates from a Geometry after applying the provided
function to each coordinate.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: Point, LineString, MultiPoint, MultiLineString, Polygon,
MultiPolygon
:return: The result of applying the function to each dimension in the
array.
:rtype: list
:raises ValueError: if the provided object is not GeoJSON.
"""
if obj['type'] == 'Point':
coordinates = tuple(func(obj['coordinates']))
elif obj['type'] in ['LineString', 'MultiPoint']:
coordinates = [tuple(func(c)) for c in obj['coordinates']]
elif obj['type'] in ['MultiLineString', 'Polygon']:
coordinates = [[
tuple(func(c)) for c in curve]
for curve in obj['coordinates']]
elif obj['type'] == 'MultiPolygon':
coordinates = [[[
tuple(func(c)) for c in curve]
for curve in part]
for part in obj['coordinates']]
elif obj['type'] in ['Feature', 'FeatureCollection', 'GeometryCollection']:
return map_geometries(lambda g: map_tuples(func, g), obj)
else:
raise ValueError("Invalid geometry object %s" % repr(obj))
return {'type': obj['type'], 'coordinates': coordinates} | [
"def",
"map_tuples",
"(",
"func",
",",
"obj",
")",
":",
"if",
"obj",
"[",
"'type'",
"]",
"==",
"'Point'",
":",
"coordinates",
"=",
"tuple",
"(",
"func",
"(",
"obj",
"[",
"'coordinates'",
"]",
")",
")",
"elif",
"obj",
"[",
"'type'",
"]",
"in",
"[",
"'LineString'",
",",
"'MultiPoint'",
"]",
":",
"coordinates",
"=",
"[",
"tuple",
"(",
"func",
"(",
"c",
")",
")",
"for",
"c",
"in",
"obj",
"[",
"'coordinates'",
"]",
"]",
"elif",
"obj",
"[",
"'type'",
"]",
"in",
"[",
"'MultiLineString'",
",",
"'Polygon'",
"]",
":",
"coordinates",
"=",
"[",
"[",
"tuple",
"(",
"func",
"(",
"c",
")",
")",
"for",
"c",
"in",
"curve",
"]",
"for",
"curve",
"in",
"obj",
"[",
"'coordinates'",
"]",
"]",
"elif",
"obj",
"[",
"'type'",
"]",
"==",
"'MultiPolygon'",
":",
"coordinates",
"=",
"[",
"[",
"[",
"tuple",
"(",
"func",
"(",
"c",
")",
")",
"for",
"c",
"in",
"curve",
"]",
"for",
"curve",
"in",
"part",
"]",
"for",
"part",
"in",
"obj",
"[",
"'coordinates'",
"]",
"]",
"elif",
"obj",
"[",
"'type'",
"]",
"in",
"[",
"'Feature'",
",",
"'FeatureCollection'",
",",
"'GeometryCollection'",
"]",
":",
"return",
"map_geometries",
"(",
"lambda",
"g",
":",
"map_tuples",
"(",
"func",
",",
"g",
")",
",",
"obj",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid geometry object %s\"",
"%",
"repr",
"(",
"obj",
")",
")",
"return",
"{",
"'type'",
":",
"obj",
"[",
"'type'",
"]",
",",
"'coordinates'",
":",
"coordinates",
"}"
] | Returns the mapped coordinates from a Geometry after applying the provided
function to each coordinate.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: Point, LineString, MultiPoint, MultiLineString, Polygon,
MultiPolygon
:return: The result of applying the function to each dimension in the
array.
:rtype: list
:raises ValueError: if the provided object is not GeoJSON. | [
"Returns",
"the",
"mapped",
"coordinates",
"from",
"a",
"Geometry",
"after",
"applying",
"the",
"provided",
"function",
"to",
"each",
"coordinate",
"."
] | 14abb31ba73a9f3cdb81d81c56656ea736f3c865 | https://github.com/jazzband/python-geojson/blob/14abb31ba73a9f3cdb81d81c56656ea736f3c865/geojson/utils.py#L58-L91 | train | 231,989 |
jazzband/python-geojson | geojson/utils.py | map_geometries | def map_geometries(func, obj):
"""
Returns the result of passing every geometry in the given geojson object
through func.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: GeoJSON
:return: The result of applying the function to each geometry
:rtype: list
:raises ValueError: if the provided object is not geojson.
"""
simple_types = [
'Point',
'LineString',
'MultiPoint',
'MultiLineString',
'Polygon',
'MultiPolygon',
]
if obj['type'] in simple_types:
return func(obj)
elif obj['type'] == 'GeometryCollection':
geoms = [func(geom) if geom else None for geom in obj['geometries']]
return {'type': obj['type'], 'geometries': geoms}
elif obj['type'] == 'Feature':
geom = func(obj['geometry']) if obj['geometry'] else None
return {
'type': obj['type'],
'geometry': geom,
'properties': obj['properties'],
}
elif obj['type'] == 'FeatureCollection':
feats = [map_geometries(func, feat) for feat in obj['features']]
return {'type': obj['type'], 'features': feats}
else:
raise ValueError("Invalid GeoJSON object %s" % repr(obj)) | python | def map_geometries(func, obj):
"""
Returns the result of passing every geometry in the given geojson object
through func.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: GeoJSON
:return: The result of applying the function to each geometry
:rtype: list
:raises ValueError: if the provided object is not geojson.
"""
simple_types = [
'Point',
'LineString',
'MultiPoint',
'MultiLineString',
'Polygon',
'MultiPolygon',
]
if obj['type'] in simple_types:
return func(obj)
elif obj['type'] == 'GeometryCollection':
geoms = [func(geom) if geom else None for geom in obj['geometries']]
return {'type': obj['type'], 'geometries': geoms}
elif obj['type'] == 'Feature':
geom = func(obj['geometry']) if obj['geometry'] else None
return {
'type': obj['type'],
'geometry': geom,
'properties': obj['properties'],
}
elif obj['type'] == 'FeatureCollection':
feats = [map_geometries(func, feat) for feat in obj['features']]
return {'type': obj['type'], 'features': feats}
else:
raise ValueError("Invalid GeoJSON object %s" % repr(obj)) | [
"def",
"map_geometries",
"(",
"func",
",",
"obj",
")",
":",
"simple_types",
"=",
"[",
"'Point'",
",",
"'LineString'",
",",
"'MultiPoint'",
",",
"'MultiLineString'",
",",
"'Polygon'",
",",
"'MultiPolygon'",
",",
"]",
"if",
"obj",
"[",
"'type'",
"]",
"in",
"simple_types",
":",
"return",
"func",
"(",
"obj",
")",
"elif",
"obj",
"[",
"'type'",
"]",
"==",
"'GeometryCollection'",
":",
"geoms",
"=",
"[",
"func",
"(",
"geom",
")",
"if",
"geom",
"else",
"None",
"for",
"geom",
"in",
"obj",
"[",
"'geometries'",
"]",
"]",
"return",
"{",
"'type'",
":",
"obj",
"[",
"'type'",
"]",
",",
"'geometries'",
":",
"geoms",
"}",
"elif",
"obj",
"[",
"'type'",
"]",
"==",
"'Feature'",
":",
"geom",
"=",
"func",
"(",
"obj",
"[",
"'geometry'",
"]",
")",
"if",
"obj",
"[",
"'geometry'",
"]",
"else",
"None",
"return",
"{",
"'type'",
":",
"obj",
"[",
"'type'",
"]",
",",
"'geometry'",
":",
"geom",
",",
"'properties'",
":",
"obj",
"[",
"'properties'",
"]",
",",
"}",
"elif",
"obj",
"[",
"'type'",
"]",
"==",
"'FeatureCollection'",
":",
"feats",
"=",
"[",
"map_geometries",
"(",
"func",
",",
"feat",
")",
"for",
"feat",
"in",
"obj",
"[",
"'features'",
"]",
"]",
"return",
"{",
"'type'",
":",
"obj",
"[",
"'type'",
"]",
",",
"'features'",
":",
"feats",
"}",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid GeoJSON object %s\"",
"%",
"repr",
"(",
"obj",
")",
")"
] | Returns the result of passing every geometry in the given geojson object
through func.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: GeoJSON
:return: The result of applying the function to each geometry
:rtype: list
:raises ValueError: if the provided object is not geojson. | [
"Returns",
"the",
"result",
"of",
"passing",
"every",
"geometry",
"in",
"the",
"given",
"geojson",
"object",
"through",
"func",
"."
] | 14abb31ba73a9f3cdb81d81c56656ea736f3c865 | https://github.com/jazzband/python-geojson/blob/14abb31ba73a9f3cdb81d81c56656ea736f3c865/geojson/utils.py#L94-L132 | train | 231,990 |
jazzband/python-geojson | geojson/base.py | GeoJSON.to_instance | def to_instance(cls, ob, default=None, strict=False):
"""Encode a GeoJSON dict into an GeoJSON object.
Assumes the caller knows that the dict should satisfy a GeoJSON type.
:param cls: Dict containing the elements to be encoded into a GeoJSON
object.
:type cls: dict
:param ob: GeoJSON object into which to encode the dict provided in
`cls`.
:type ob: GeoJSON
:param default: A default instance to append the content of the dict
to if none is provided.
:type default: GeoJSON
:param strict: Raise error if unable to coerce particular keys or
attributes to a valid GeoJSON structure.
:type strict: bool
:return: A GeoJSON object with the dict's elements as its constituents.
:rtype: GeoJSON
:raises TypeError: If the input dict contains items that are not valid
GeoJSON types.
:raises UnicodeEncodeError: If the input dict contains items of a type
that contain non-ASCII characters.
:raises AttributeError: If the input dict contains items that are not
valid GeoJSON types.
"""
if ob is None and default is not None:
instance = default()
elif isinstance(ob, GeoJSON):
instance = ob
else:
mapping = to_mapping(ob)
d = {}
for k in mapping:
d[k] = mapping[k]
try:
type_ = d.pop("type")
try:
type_ = str(type_)
except UnicodeEncodeError:
# If the type contains non-ascii characters, we can assume
# it's not a valid GeoJSON type
raise AttributeError(
"{0} is not a GeoJSON type").format(type_)
geojson_factory = getattr(geojson.factory, type_)
instance = geojson_factory(**d)
except (AttributeError, KeyError) as invalid:
if strict:
msg = "Cannot coerce %r into a valid GeoJSON structure: %s"
msg %= (ob, invalid)
raise ValueError(msg)
instance = ob
return instance | python | def to_instance(cls, ob, default=None, strict=False):
"""Encode a GeoJSON dict into an GeoJSON object.
Assumes the caller knows that the dict should satisfy a GeoJSON type.
:param cls: Dict containing the elements to be encoded into a GeoJSON
object.
:type cls: dict
:param ob: GeoJSON object into which to encode the dict provided in
`cls`.
:type ob: GeoJSON
:param default: A default instance to append the content of the dict
to if none is provided.
:type default: GeoJSON
:param strict: Raise error if unable to coerce particular keys or
attributes to a valid GeoJSON structure.
:type strict: bool
:return: A GeoJSON object with the dict's elements as its constituents.
:rtype: GeoJSON
:raises TypeError: If the input dict contains items that are not valid
GeoJSON types.
:raises UnicodeEncodeError: If the input dict contains items of a type
that contain non-ASCII characters.
:raises AttributeError: If the input dict contains items that are not
valid GeoJSON types.
"""
if ob is None and default is not None:
instance = default()
elif isinstance(ob, GeoJSON):
instance = ob
else:
mapping = to_mapping(ob)
d = {}
for k in mapping:
d[k] = mapping[k]
try:
type_ = d.pop("type")
try:
type_ = str(type_)
except UnicodeEncodeError:
# If the type contains non-ascii characters, we can assume
# it's not a valid GeoJSON type
raise AttributeError(
"{0} is not a GeoJSON type").format(type_)
geojson_factory = getattr(geojson.factory, type_)
instance = geojson_factory(**d)
except (AttributeError, KeyError) as invalid:
if strict:
msg = "Cannot coerce %r into a valid GeoJSON structure: %s"
msg %= (ob, invalid)
raise ValueError(msg)
instance = ob
return instance | [
"def",
"to_instance",
"(",
"cls",
",",
"ob",
",",
"default",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"if",
"ob",
"is",
"None",
"and",
"default",
"is",
"not",
"None",
":",
"instance",
"=",
"default",
"(",
")",
"elif",
"isinstance",
"(",
"ob",
",",
"GeoJSON",
")",
":",
"instance",
"=",
"ob",
"else",
":",
"mapping",
"=",
"to_mapping",
"(",
"ob",
")",
"d",
"=",
"{",
"}",
"for",
"k",
"in",
"mapping",
":",
"d",
"[",
"k",
"]",
"=",
"mapping",
"[",
"k",
"]",
"try",
":",
"type_",
"=",
"d",
".",
"pop",
"(",
"\"type\"",
")",
"try",
":",
"type_",
"=",
"str",
"(",
"type_",
")",
"except",
"UnicodeEncodeError",
":",
"# If the type contains non-ascii characters, we can assume",
"# it's not a valid GeoJSON type",
"raise",
"AttributeError",
"(",
"\"{0} is not a GeoJSON type\"",
")",
".",
"format",
"(",
"type_",
")",
"geojson_factory",
"=",
"getattr",
"(",
"geojson",
".",
"factory",
",",
"type_",
")",
"instance",
"=",
"geojson_factory",
"(",
"*",
"*",
"d",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
"as",
"invalid",
":",
"if",
"strict",
":",
"msg",
"=",
"\"Cannot coerce %r into a valid GeoJSON structure: %s\"",
"msg",
"%=",
"(",
"ob",
",",
"invalid",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"instance",
"=",
"ob",
"return",
"instance"
] | Encode a GeoJSON dict into an GeoJSON object.
Assumes the caller knows that the dict should satisfy a GeoJSON type.
:param cls: Dict containing the elements to be encoded into a GeoJSON
object.
:type cls: dict
:param ob: GeoJSON object into which to encode the dict provided in
`cls`.
:type ob: GeoJSON
:param default: A default instance to append the content of the dict
to if none is provided.
:type default: GeoJSON
:param strict: Raise error if unable to coerce particular keys or
attributes to a valid GeoJSON structure.
:type strict: bool
:return: A GeoJSON object with the dict's elements as its constituents.
:rtype: GeoJSON
:raises TypeError: If the input dict contains items that are not valid
GeoJSON types.
:raises UnicodeEncodeError: If the input dict contains items of a type
that contain non-ASCII characters.
:raises AttributeError: If the input dict contains items that are not
valid GeoJSON types. | [
"Encode",
"a",
"GeoJSON",
"dict",
"into",
"an",
"GeoJSON",
"object",
".",
"Assumes",
"the",
"caller",
"knows",
"that",
"the",
"dict",
"should",
"satisfy",
"a",
"GeoJSON",
"type",
"."
] | 14abb31ba73a9f3cdb81d81c56656ea736f3c865 | https://github.com/jazzband/python-geojson/blob/14abb31ba73a9f3cdb81d81c56656ea736f3c865/geojson/base.py#L71-L122 | train | 231,991 |
jazzband/python-geojson | geojson/base.py | GeoJSON.check_list_errors | def check_list_errors(self, checkFunc, lst):
"""Validation helper function."""
# check for errors on each subitem, filter only subitems with errors
results = (checkFunc(i) for i in lst)
return [err for err in results if err] | python | def check_list_errors(self, checkFunc, lst):
"""Validation helper function."""
# check for errors on each subitem, filter only subitems with errors
results = (checkFunc(i) for i in lst)
return [err for err in results if err] | [
"def",
"check_list_errors",
"(",
"self",
",",
"checkFunc",
",",
"lst",
")",
":",
"# check for errors on each subitem, filter only subitems with errors",
"results",
"=",
"(",
"checkFunc",
"(",
"i",
")",
"for",
"i",
"in",
"lst",
")",
"return",
"[",
"err",
"for",
"err",
"in",
"results",
"if",
"err",
"]"
] | Validation helper function. | [
"Validation",
"helper",
"function",
"."
] | 14abb31ba73a9f3cdb81d81c56656ea736f3c865 | https://github.com/jazzband/python-geojson/blob/14abb31ba73a9f3cdb81d81c56656ea736f3c865/geojson/base.py#L128-L132 | train | 231,992 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.run_only_once | def run_only_once(self, keyword):
"""
Runs a keyword only once in one of the parallel processes.
As the keyword will be called
only in one process and the return value could basically be anything.
The "Run Only Once" can't return the actual return value.
If the keyword fails, "Run Only Once" fails.
Others executing "Run Only Once" wait before going through this
keyword before the actual command has been executed.
NOTE! This is a potential "Shoot yourself in to knee" keyword
Especially note that all the namespace changes are only visible
in the process that actually executed the keyword.
Also note that this might lead to odd situations if used inside
of other keywords.
Also at this point the keyword will be identified to be same
if it has the same name.
"""
lock_name = 'pabot_run_only_once_%s' % keyword
try:
self.acquire_lock(lock_name)
passed = self.get_parallel_value_for_key(lock_name)
if passed != '':
if passed == 'FAILED':
raise AssertionError('Keyword failed in other process')
return
BuiltIn().run_keyword(keyword)
self.set_parallel_value_for_key(lock_name, 'PASSED')
except:
self.set_parallel_value_for_key(lock_name, 'FAILED')
raise
finally:
self.release_lock(lock_name) | python | def run_only_once(self, keyword):
"""
Runs a keyword only once in one of the parallel processes.
As the keyword will be called
only in one process and the return value could basically be anything.
The "Run Only Once" can't return the actual return value.
If the keyword fails, "Run Only Once" fails.
Others executing "Run Only Once" wait before going through this
keyword before the actual command has been executed.
NOTE! This is a potential "Shoot yourself in to knee" keyword
Especially note that all the namespace changes are only visible
in the process that actually executed the keyword.
Also note that this might lead to odd situations if used inside
of other keywords.
Also at this point the keyword will be identified to be same
if it has the same name.
"""
lock_name = 'pabot_run_only_once_%s' % keyword
try:
self.acquire_lock(lock_name)
passed = self.get_parallel_value_for_key(lock_name)
if passed != '':
if passed == 'FAILED':
raise AssertionError('Keyword failed in other process')
return
BuiltIn().run_keyword(keyword)
self.set_parallel_value_for_key(lock_name, 'PASSED')
except:
self.set_parallel_value_for_key(lock_name, 'FAILED')
raise
finally:
self.release_lock(lock_name) | [
"def",
"run_only_once",
"(",
"self",
",",
"keyword",
")",
":",
"lock_name",
"=",
"'pabot_run_only_once_%s'",
"%",
"keyword",
"try",
":",
"self",
".",
"acquire_lock",
"(",
"lock_name",
")",
"passed",
"=",
"self",
".",
"get_parallel_value_for_key",
"(",
"lock_name",
")",
"if",
"passed",
"!=",
"''",
":",
"if",
"passed",
"==",
"'FAILED'",
":",
"raise",
"AssertionError",
"(",
"'Keyword failed in other process'",
")",
"return",
"BuiltIn",
"(",
")",
".",
"run_keyword",
"(",
"keyword",
")",
"self",
".",
"set_parallel_value_for_key",
"(",
"lock_name",
",",
"'PASSED'",
")",
"except",
":",
"self",
".",
"set_parallel_value_for_key",
"(",
"lock_name",
",",
"'FAILED'",
")",
"raise",
"finally",
":",
"self",
".",
"release_lock",
"(",
"lock_name",
")"
] | Runs a keyword only once in one of the parallel processes.
As the keyword will be called
only in one process and the return value could basically be anything.
The "Run Only Once" can't return the actual return value.
If the keyword fails, "Run Only Once" fails.
Others executing "Run Only Once" wait before going through this
keyword before the actual command has been executed.
NOTE! This is a potential "Shoot yourself in to knee" keyword
Especially note that all the namespace changes are only visible
in the process that actually executed the keyword.
Also note that this might lead to odd situations if used inside
of other keywords.
Also at this point the keyword will be identified to be same
if it has the same name. | [
"Runs",
"a",
"keyword",
"only",
"once",
"in",
"one",
"of",
"the",
"parallel",
"processes",
".",
"As",
"the",
"keyword",
"will",
"be",
"called",
"only",
"in",
"one",
"process",
"and",
"the",
"return",
"value",
"could",
"basically",
"be",
"anything",
".",
"The",
"Run",
"Only",
"Once",
"can",
"t",
"return",
"the",
"actual",
"return",
"value",
".",
"If",
"the",
"keyword",
"fails",
"Run",
"Only",
"Once",
"fails",
".",
"Others",
"executing",
"Run",
"Only",
"Once",
"wait",
"before",
"going",
"through",
"this",
"keyword",
"before",
"the",
"actual",
"command",
"has",
"been",
"executed",
".",
"NOTE!",
"This",
"is",
"a",
"potential",
"Shoot",
"yourself",
"in",
"to",
"knee",
"keyword",
"Especially",
"note",
"that",
"all",
"the",
"namespace",
"changes",
"are",
"only",
"visible",
"in",
"the",
"process",
"that",
"actually",
"executed",
"the",
"keyword",
".",
"Also",
"note",
"that",
"this",
"might",
"lead",
"to",
"odd",
"situations",
"if",
"used",
"inside",
"of",
"other",
"keywords",
".",
"Also",
"at",
"this",
"point",
"the",
"keyword",
"will",
"be",
"identified",
"to",
"be",
"same",
"if",
"it",
"has",
"the",
"same",
"name",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L136-L167 | train | 231,993 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.set_parallel_value_for_key | def set_parallel_value_for_key(self, key, value):
"""
Set a globally available key and value that can be accessed
from all the pabot processes.
"""
if self._remotelib:
self._remotelib.run_keyword('set_parallel_value_for_key',
[key, value], {})
else:
_PabotLib.set_parallel_value_for_key(self, key, value) | python | def set_parallel_value_for_key(self, key, value):
"""
Set a globally available key and value that can be accessed
from all the pabot processes.
"""
if self._remotelib:
self._remotelib.run_keyword('set_parallel_value_for_key',
[key, value], {})
else:
_PabotLib.set_parallel_value_for_key(self, key, value) | [
"def",
"set_parallel_value_for_key",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"_remotelib",
":",
"self",
".",
"_remotelib",
".",
"run_keyword",
"(",
"'set_parallel_value_for_key'",
",",
"[",
"key",
",",
"value",
"]",
",",
"{",
"}",
")",
"else",
":",
"_PabotLib",
".",
"set_parallel_value_for_key",
"(",
"self",
",",
"key",
",",
"value",
")"
] | Set a globally available key and value that can be accessed
from all the pabot processes. | [
"Set",
"a",
"globally",
"available",
"key",
"and",
"value",
"that",
"can",
"be",
"accessed",
"from",
"all",
"the",
"pabot",
"processes",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L169-L178 | train | 231,994 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.get_parallel_value_for_key | def get_parallel_value_for_key(self, key):
"""
Get the value for a key. If there is no value for the key then empty
string is returned.
"""
if self._remotelib:
return self._remotelib.run_keyword('get_parallel_value_for_key',
[key], {})
return _PabotLib.get_parallel_value_for_key(self, key) | python | def get_parallel_value_for_key(self, key):
"""
Get the value for a key. If there is no value for the key then empty
string is returned.
"""
if self._remotelib:
return self._remotelib.run_keyword('get_parallel_value_for_key',
[key], {})
return _PabotLib.get_parallel_value_for_key(self, key) | [
"def",
"get_parallel_value_for_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"_remotelib",
":",
"return",
"self",
".",
"_remotelib",
".",
"run_keyword",
"(",
"'get_parallel_value_for_key'",
",",
"[",
"key",
"]",
",",
"{",
"}",
")",
"return",
"_PabotLib",
".",
"get_parallel_value_for_key",
"(",
"self",
",",
"key",
")"
] | Get the value for a key. If there is no value for the key then empty
string is returned. | [
"Get",
"the",
"value",
"for",
"a",
"key",
".",
"If",
"there",
"is",
"no",
"value",
"for",
"the",
"key",
"then",
"empty",
"string",
"is",
"returned",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L180-L188 | train | 231,995 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.acquire_lock | def acquire_lock(self, name):
"""
Wait for a lock with name.
This will prevent other processes from acquiring the lock with
the name while it is held. Thus they will wait in the position
where they are acquiring the lock until the process that has it
releases it.
"""
if self._remotelib:
try:
while not self._remotelib.run_keyword('acquire_lock',
[name, self._my_id], {}):
time.sleep(0.1)
logger.debug('waiting for lock to release')
return True
except RuntimeError:
logger.warn('no connection')
self.__remotelib = None
return _PabotLib.acquire_lock(self, name, self._my_id) | python | def acquire_lock(self, name):
"""
Wait for a lock with name.
This will prevent other processes from acquiring the lock with
the name while it is held. Thus they will wait in the position
where they are acquiring the lock until the process that has it
releases it.
"""
if self._remotelib:
try:
while not self._remotelib.run_keyword('acquire_lock',
[name, self._my_id], {}):
time.sleep(0.1)
logger.debug('waiting for lock to release')
return True
except RuntimeError:
logger.warn('no connection')
self.__remotelib = None
return _PabotLib.acquire_lock(self, name, self._my_id) | [
"def",
"acquire_lock",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_remotelib",
":",
"try",
":",
"while",
"not",
"self",
".",
"_remotelib",
".",
"run_keyword",
"(",
"'acquire_lock'",
",",
"[",
"name",
",",
"self",
".",
"_my_id",
"]",
",",
"{",
"}",
")",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"logger",
".",
"debug",
"(",
"'waiting for lock to release'",
")",
"return",
"True",
"except",
"RuntimeError",
":",
"logger",
".",
"warn",
"(",
"'no connection'",
")",
"self",
".",
"__remotelib",
"=",
"None",
"return",
"_PabotLib",
".",
"acquire_lock",
"(",
"self",
",",
"name",
",",
"self",
".",
"_my_id",
")"
] | Wait for a lock with name.
This will prevent other processes from acquiring the lock with
the name while it is held. Thus they will wait in the position
where they are acquiring the lock until the process that has it
releases it. | [
"Wait",
"for",
"a",
"lock",
"with",
"name",
".",
"This",
"will",
"prevent",
"other",
"processes",
"from",
"acquiring",
"the",
"lock",
"with",
"the",
"name",
"while",
"it",
"is",
"held",
".",
"Thus",
"they",
"will",
"wait",
"in",
"the",
"position",
"where",
"they",
"are",
"acquiring",
"the",
"lock",
"until",
"the",
"process",
"that",
"has",
"it",
"releases",
"it",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L190-L208 | train | 231,996 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.release_lock | def release_lock(self, name):
"""
Release a lock with name.
This will enable others to acquire the lock.
"""
if self._remotelib:
self._remotelib.run_keyword('release_lock',
[name, self._my_id], {})
else:
_PabotLib.release_lock(self, name, self._my_id) | python | def release_lock(self, name):
"""
Release a lock with name.
This will enable others to acquire the lock.
"""
if self._remotelib:
self._remotelib.run_keyword('release_lock',
[name, self._my_id], {})
else:
_PabotLib.release_lock(self, name, self._my_id) | [
"def",
"release_lock",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_remotelib",
":",
"self",
".",
"_remotelib",
".",
"run_keyword",
"(",
"'release_lock'",
",",
"[",
"name",
",",
"self",
".",
"_my_id",
"]",
",",
"{",
"}",
")",
"else",
":",
"_PabotLib",
".",
"release_lock",
"(",
"self",
",",
"name",
",",
"self",
".",
"_my_id",
")"
] | Release a lock with name.
This will enable others to acquire the lock. | [
"Release",
"a",
"lock",
"with",
"name",
".",
"This",
"will",
"enable",
"others",
"to",
"acquire",
"the",
"lock",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L210-L219 | train | 231,997 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.release_locks | def release_locks(self):
"""
Release all locks called by instance.
"""
if self._remotelib:
self._remotelib.run_keyword('release_locks',
[self._my_id], {})
else:
_PabotLib.release_locks(self, self._my_id) | python | def release_locks(self):
"""
Release all locks called by instance.
"""
if self._remotelib:
self._remotelib.run_keyword('release_locks',
[self._my_id], {})
else:
_PabotLib.release_locks(self, self._my_id) | [
"def",
"release_locks",
"(",
"self",
")",
":",
"if",
"self",
".",
"_remotelib",
":",
"self",
".",
"_remotelib",
".",
"run_keyword",
"(",
"'release_locks'",
",",
"[",
"self",
".",
"_my_id",
"]",
",",
"{",
"}",
")",
"else",
":",
"_PabotLib",
".",
"release_locks",
"(",
"self",
",",
"self",
".",
"_my_id",
")"
] | Release all locks called by instance. | [
"Release",
"all",
"locks",
"called",
"by",
"instance",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L221-L229 | train | 231,998 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.acquire_value_set | def acquire_value_set(self, *tags):
"""
Reserve a set of values for this execution.
No other process can reserve the same set of values while the set is
reserved. Acquired value set needs to be released after use to allow
other processes to access it.
Add tags to limit the possible value sets that this returns.
"""
setname = self._acquire_value_set(*tags)
if setname is None:
raise ValueError("Could not aquire a value set")
return setname | python | def acquire_value_set(self, *tags):
"""
Reserve a set of values for this execution.
No other process can reserve the same set of values while the set is
reserved. Acquired value set needs to be released after use to allow
other processes to access it.
Add tags to limit the possible value sets that this returns.
"""
setname = self._acquire_value_set(*tags)
if setname is None:
raise ValueError("Could not aquire a value set")
return setname | [
"def",
"acquire_value_set",
"(",
"self",
",",
"*",
"tags",
")",
":",
"setname",
"=",
"self",
".",
"_acquire_value_set",
"(",
"*",
"tags",
")",
"if",
"setname",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Could not aquire a value set\"",
")",
"return",
"setname"
] | Reserve a set of values for this execution.
No other process can reserve the same set of values while the set is
reserved. Acquired value set needs to be released after use to allow
other processes to access it.
Add tags to limit the possible value sets that this returns. | [
"Reserve",
"a",
"set",
"of",
"values",
"for",
"this",
"execution",
".",
"No",
"other",
"process",
"can",
"reserve",
"the",
"same",
"set",
"of",
"values",
"while",
"the",
"set",
"is",
"reserved",
".",
"Acquired",
"value",
"set",
"needs",
"to",
"be",
"released",
"after",
"use",
"to",
"allow",
"other",
"processes",
"to",
"access",
"it",
".",
"Add",
"tags",
"to",
"limit",
"the",
"possible",
"value",
"sets",
"that",
"this",
"returns",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L231-L242 | train | 231,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.